@tracewayapp/backend 0.3.0 → 1.0.1

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.
package/README.md CHANGED
@@ -72,6 +72,7 @@ process.on("SIGTERM", async () => {
72
72
  | `captureExceptionWithAttributes(error, attrs?, traceId?)` | Capture with explicit context |
73
73
  | `captureMessage(msg, attrs?)` | Capture message (auto-detects trace context) |
74
74
  | `captureMetric(name, value)` | Capture a custom metric |
75
+ | `captureMetricWithTags(name, value, tags)` | Capture a metric with key-value tags |
75
76
  | `captureTrace(...)` | Capture HTTP trace (manual mode) |
76
77
  | `captureTask(...)` | Capture background task (manual mode) |
77
78
  | `captureCurrentTrace()` | Capture trace from current context |
package/dist/index.d.mts CHANGED
@@ -7,6 +7,7 @@ declare function captureException(error: Error): void;
7
7
  declare function captureExceptionWithAttributes(error: Error, attributes?: Record<string, string>, traceId?: string): void;
8
8
  declare function captureMessage(msg: string, attributes?: Record<string, string>): void;
9
9
  declare function captureMetric(name: string, value: number): void;
10
+ declare function captureMetricWithTags(name: string, value: number, tags: Record<string, string>): void;
10
11
  declare function captureTrace(traceId: string, endpoint: string, durationMs: number, startedAt: Date, statusCode: number, bodySize: number, clientIP: string, attributes?: Record<string, string>, spans?: Span[]): void;
11
12
  declare function captureTask(traceId: string, taskName: string, durationMs: number, startedAt: Date, attributes?: Record<string, string>, spans?: Span[]): void;
12
13
  /** Handle returned by startSpan for tracking span timing */
@@ -45,7 +46,7 @@ declare function endSpan(span: SpanHandle, addToContext?: boolean): Span;
45
46
  declare function captureCurrentTrace(): void;
46
47
  declare function shouldSample(isError: boolean): boolean;
47
48
  declare function measureTask(title: string, fn: () => void | Promise<void>): void;
48
- declare function shutdown(): Promise<void>;
49
+ declare function shutdown(timeoutMs?: number): Promise<void>;
49
50
 
50
51
  /**
51
52
  * Trace context stored in AsyncLocalStorage.
@@ -226,7 +227,7 @@ declare class CollectionFrameStore {
226
227
  private processSendQueue;
227
228
  private triggerUpload;
228
229
  private collectSystemMetrics;
229
- shutdown(): Promise<void>;
230
+ shutdown(timeoutMs?: number): Promise<void>;
230
231
  }
231
232
 
232
- export { CollectionFrameStore, type CollectionFrameStoreOptions, type SpanHandle, type TraceContext, type TraceContextOptions, addSpanToContext, captureCurrentTrace, captureException, captureExceptionWithAttributes, captureMessage, captureMetric, captureTask, captureTrace, collectMetrics, endSpan, forkTraceContext, formatErrorStackTrace, getTraceContext, getTraceDuration, getTraceId, getTraceSpans, hasTraceContext, init, measureTask, resetCpuTracking, runWithTraceContext, setTraceAttribute, setTraceAttributes, setTraceResponseInfo, shouldSample, shutdown, startSpan, asyncLocalStorage as traceContextStorage, withTraceContext };
233
+ export { CollectionFrameStore, type CollectionFrameStoreOptions, type SpanHandle, type TraceContext, type TraceContextOptions, addSpanToContext, captureCurrentTrace, captureException, captureExceptionWithAttributes, captureMessage, captureMetric, captureMetricWithTags, captureTask, captureTrace, collectMetrics, endSpan, forkTraceContext, formatErrorStackTrace, getTraceContext, getTraceDuration, getTraceId, getTraceSpans, hasTraceContext, init, measureTask, resetCpuTracking, runWithTraceContext, setTraceAttribute, setTraceAttributes, setTraceResponseInfo, shouldSample, shutdown, startSpan, asyncLocalStorage as traceContextStorage, withTraceContext };
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ declare function captureException(error: Error): void;
7
7
  declare function captureExceptionWithAttributes(error: Error, attributes?: Record<string, string>, traceId?: string): void;
8
8
  declare function captureMessage(msg: string, attributes?: Record<string, string>): void;
9
9
  declare function captureMetric(name: string, value: number): void;
10
+ declare function captureMetricWithTags(name: string, value: number, tags: Record<string, string>): void;
10
11
  declare function captureTrace(traceId: string, endpoint: string, durationMs: number, startedAt: Date, statusCode: number, bodySize: number, clientIP: string, attributes?: Record<string, string>, spans?: Span[]): void;
11
12
  declare function captureTask(traceId: string, taskName: string, durationMs: number, startedAt: Date, attributes?: Record<string, string>, spans?: Span[]): void;
12
13
  /** Handle returned by startSpan for tracking span timing */
@@ -45,7 +46,7 @@ declare function endSpan(span: SpanHandle, addToContext?: boolean): Span;
45
46
  declare function captureCurrentTrace(): void;
46
47
  declare function shouldSample(isError: boolean): boolean;
47
48
  declare function measureTask(title: string, fn: () => void | Promise<void>): void;
48
- declare function shutdown(): Promise<void>;
49
+ declare function shutdown(timeoutMs?: number): Promise<void>;
49
50
 
50
51
  /**
51
52
  * Trace context stored in AsyncLocalStorage.
@@ -226,7 +227,7 @@ declare class CollectionFrameStore {
226
227
  private processSendQueue;
227
228
  private triggerUpload;
228
229
  private collectSystemMetrics;
229
- shutdown(): Promise<void>;
230
+ shutdown(timeoutMs?: number): Promise<void>;
230
231
  }
231
232
 
232
- export { CollectionFrameStore, type CollectionFrameStoreOptions, type SpanHandle, type TraceContext, type TraceContextOptions, addSpanToContext, captureCurrentTrace, captureException, captureExceptionWithAttributes, captureMessage, captureMetric, captureTask, captureTrace, collectMetrics, endSpan, forkTraceContext, formatErrorStackTrace, getTraceContext, getTraceDuration, getTraceId, getTraceSpans, hasTraceContext, init, measureTask, resetCpuTracking, runWithTraceContext, setTraceAttribute, setTraceAttributes, setTraceResponseInfo, shouldSample, shutdown, startSpan, asyncLocalStorage as traceContextStorage, withTraceContext };
233
+ export { CollectionFrameStore, type CollectionFrameStoreOptions, type SpanHandle, type TraceContext, type TraceContextOptions, addSpanToContext, captureCurrentTrace, captureException, captureExceptionWithAttributes, captureMessage, captureMetric, captureMetricWithTags, captureTask, captureTrace, collectMetrics, endSpan, forkTraceContext, formatErrorStackTrace, getTraceContext, getTraceDuration, getTraceId, getTraceSpans, hasTraceContext, init, measureTask, resetCpuTracking, runWithTraceContext, setTraceAttribute, setTraceAttributes, setTraceResponseInfo, shouldSample, shutdown, startSpan, asyncLocalStorage as traceContextStorage, withTraceContext };
package/dist/index.js CHANGED
@@ -37,6 +37,7 @@ __export(index_exports, {
37
37
  captureExceptionWithAttributes: () => captureExceptionWithAttributes,
38
38
  captureMessage: () => captureMessage,
39
39
  captureMetric: () => captureMetric,
40
+ captureMetricWithTags: () => captureMetricWithTags,
40
41
  captureTask: () => captureTask,
41
42
  captureTrace: () => captureTrace,
42
43
  collectMetrics: () => collectMetrics,
@@ -323,7 +324,7 @@ var CollectionFrameStore = class {
323
324
  }
324
325
  }
325
326
  }
326
- async shutdown() {
327
+ async shutdown(timeoutMs) {
327
328
  if (this.collectionTimer !== null) {
328
329
  clearInterval(this.collectionTimer);
329
330
  this.collectionTimer = null;
@@ -335,30 +336,40 @@ var CollectionFrameStore = class {
335
336
  this.rotateCurrentCollectionFrame();
336
337
  const frames = this.sendQueue.readAll();
337
338
  if (frames.length === 0) return;
338
- const payload = {
339
- collectionFrames: frames,
340
- appVersion: this.version,
341
- serverName: this.serverName
342
- };
343
- try {
344
- const jsonData = JSON.stringify(payload);
345
- const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));
346
- const resp = await fetch(this.apiUrl, {
347
- method: "POST",
348
- headers: {
349
- "Content-Type": "application/json",
350
- "Content-Encoding": "gzip",
351
- Authorization: `Bearer ${this.token}`
352
- },
353
- body: gzipped
354
- });
355
- if (resp.status === 200) {
356
- this.sendQueue.remove(frames);
357
- }
358
- } catch (err) {
359
- if (this.debug) {
360
- console.error("Traceway: shutdown upload failed:", err);
339
+ const uploadPromise = (async () => {
340
+ const payload = {
341
+ collectionFrames: frames,
342
+ appVersion: this.version,
343
+ serverName: this.serverName
344
+ };
345
+ try {
346
+ const jsonData = JSON.stringify(payload);
347
+ const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));
348
+ const resp = await fetch(this.apiUrl, {
349
+ method: "POST",
350
+ headers: {
351
+ "Content-Type": "application/json",
352
+ "Content-Encoding": "gzip",
353
+ Authorization: `Bearer ${this.token}`
354
+ },
355
+ body: gzipped
356
+ });
357
+ if (resp.status === 200) {
358
+ this.sendQueue.remove(frames);
359
+ }
360
+ } catch (err) {
361
+ if (this.debug) {
362
+ console.error("Traceway: shutdown upload failed:", err);
363
+ }
361
364
  }
365
+ })();
366
+ if (timeoutMs !== void 0) {
367
+ await Promise.race([
368
+ uploadPromise,
369
+ new Promise((resolve) => setTimeout(resolve, timeoutMs))
370
+ ]);
371
+ } else {
372
+ await uploadPromise;
362
373
  }
363
374
  }
364
375
  };
@@ -569,6 +580,15 @@ function captureMetric(name, value) {
569
580
  recordedAt: (0, import_core4.nowISO)()
570
581
  });
571
582
  }
583
+ function captureMetricWithTags(name, value, tags) {
584
+ if (!store) return;
585
+ store.addMetric({
586
+ name,
587
+ value,
588
+ recordedAt: (0, import_core4.nowISO)(),
589
+ tags
590
+ });
591
+ }
572
592
  function captureTrace(traceId, endpoint, durationMs, startedAt, statusCode, bodySize, clientIP, attributes, spans) {
573
593
  if (!store) return;
574
594
  store.addTrace({
@@ -700,11 +720,11 @@ function measureTask(title, fn) {
700
720
  throw err;
701
721
  }
702
722
  }
703
- async function shutdown() {
723
+ async function shutdown(timeoutMs) {
704
724
  if (!store) return;
705
725
  const s = store;
706
726
  store = null;
707
- await s.shutdown();
727
+ await s.shutdown(timeoutMs);
708
728
  }
709
729
  // Annotate the CommonJS export names for ESM import in node:
710
730
  0 && (module.exports = {
@@ -715,6 +735,7 @@ async function shutdown() {
715
735
  captureExceptionWithAttributes,
716
736
  captureMessage,
717
737
  captureMetric,
738
+ captureMetricWithTags,
718
739
  captureTask,
719
740
  captureTrace,
720
741
  collectMetrics,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/traceway.ts","../src/collection-frame-store.ts","../src/typed-ring.ts","../src/metrics.ts","../src/stack-trace.ts","../src/context.ts"],"sourcesContent":["export {\n init,\n captureException,\n captureExceptionWithAttributes,\n captureMessage,\n captureMetric,\n captureTrace,\n captureTask,\n captureCurrentTrace,\n startSpan,\n endSpan,\n shouldSample,\n measureTask,\n shutdown,\n} from \"./traceway.js\";\nexport type { SpanHandle } from \"./traceway.js\";\n\n// Context propagation (AsyncLocalStorage-based)\nexport {\n withTraceContext,\n runWithTraceContext,\n getTraceContext,\n getTraceId,\n hasTraceContext,\n addSpanToContext,\n setTraceAttribute,\n setTraceAttributes,\n setTraceResponseInfo,\n getTraceSpans,\n getTraceDuration,\n forkTraceContext,\n traceContextStorage,\n} from \"./context.js\";\nexport type { TraceContext, TraceContextOptions } from \"./context.js\";\n\nexport { formatErrorStackTrace } from \"./stack-trace.js\";\nexport { collectMetrics, resetCpuTracking } from \"./metrics.js\";\nexport { CollectionFrameStore } from \"./collection-frame-store.js\";\nexport type { CollectionFrameStoreOptions } from \"./collection-frame-store.js\";\n\nexport type {\n ExceptionStackTrace,\n MetricRecord,\n Span,\n Trace,\n CollectionFrame,\n ReportRequest,\n TracewayOptions,\n} from \"@tracewayapp/core\";\n","import {\n generateUUID,\n parseConnectionString,\n nowISO,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport type {\n TracewayOptions,\n ExceptionStackTrace,\n Trace,\n Span,\n} from \"@tracewayapp/core\";\nimport { CollectionFrameStore } from \"./collection-frame-store.js\";\nimport { formatErrorStackTrace } from \"./stack-trace.js\";\nimport {\n getTraceContext,\n getTraceId,\n addSpanToContext,\n type TraceContext,\n} from \"./context.js\";\nimport * as os from \"os\";\n\nlet store: CollectionFrameStore | null = null;\n\nfunction getHostname(): string {\n try {\n const hostname = os.hostname();\n const dotIdx = hostname.indexOf(\".\");\n return dotIdx >= 0 ? hostname.slice(0, dotIdx) : hostname;\n } catch {\n return \"unknown\";\n }\n}\n\nexport function init(\n connectionString: string,\n options: TracewayOptions = {},\n): void {\n if (store !== null) {\n throw new Error(\"Traceway: already initialized. Call shutdown() first.\");\n }\n\n const { token, apiUrl } = parseConnectionString(connectionString);\n\n store = new CollectionFrameStore({\n apiUrl,\n token,\n debug: options.debug ?? false,\n maxCollectionFrames: options.maxCollectionFrames ?? 12,\n collectionInterval: options.collectionInterval ?? 5000,\n uploadThrottle: options.uploadThrottle ?? 2000,\n metricsInterval: options.metricsInterval ?? 30000,\n version: options.version ?? \"\",\n serverName: options.serverName ?? getHostname(),\n sampleRate: options.sampleRate ?? 1,\n errorSampleRate: options.errorSampleRate ?? 1,\n });\n}\n\nexport function captureException(error: Error): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n captureExceptionWithAttributes(\n error,\n ctx?.attributes,\n ctx?.traceId,\n );\n}\n\nexport function captureExceptionWithAttributes(\n error: Error,\n attributes?: Record<string, string>,\n traceId?: string,\n): void {\n if (!store) return;\n // Auto-detect trace context if not explicitly provided\n const ctx = getTraceContext();\n const resolvedTraceId = traceId ?? ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: formatErrorStackTrace(error),\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: false,\n });\n}\n\nexport function captureMessage(\n msg: string,\n attributes?: Record<string, string>,\n): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n const resolvedTraceId = ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: msg,\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: true,\n });\n}\n\nexport function captureMetric(name: string, value: number): void {\n if (!store) return;\n store.addMetric({\n name,\n value,\n recordedAt: nowISO(),\n });\n}\n\nexport function captureTrace(\n traceId: string,\n endpoint: string,\n durationMs: number,\n startedAt: Date,\n statusCode: number,\n bodySize: number,\n clientIP: string,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode,\n bodySize,\n clientIP,\n attributes,\n spans,\n });\n}\n\nexport function captureTask(\n traceId: string,\n taskName: string,\n durationMs: number,\n startedAt: Date,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint: taskName,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes,\n spans,\n isTask: true,\n });\n}\n\n/** Handle returned by startSpan for tracking span timing */\nexport interface SpanHandle {\n id: string;\n name: string;\n startTime: string;\n startedAt: number;\n}\n\n/**\n * Start a new span. If within a trace context, the span will be\n * automatically added to the trace when ended.\n */\nexport function startSpan(name: string): SpanHandle {\n const now = Date.now();\n return {\n id: generateUUID(),\n name,\n startTime: new Date(now).toISOString(),\n startedAt: now,\n };\n}\n\n/**\n * End a span and get the completed Span object.\n * If within a trace context, automatically adds the span to the trace.\n *\n * @param addToContext - If true (default), adds span to current trace context\n */\nexport function endSpan(span: SpanHandle, addToContext: boolean = true): Span {\n const durationMs = Date.now() - span.startedAt;\n const completedSpan: Span = {\n id: span.id,\n name: span.name,\n startTime: span.startTime,\n duration: msToNanoseconds(durationMs),\n };\n\n // Auto-add to trace context if available\n if (addToContext) {\n addSpanToContext(completedSpan);\n }\n\n return completedSpan;\n}\n\n/**\n * Capture the current trace context as a trace.\n * Call this at the end of a request/task to record the trace.\n *\n * @example\n * ```ts\n * // In Express middleware (after response)\n * withTraceContext({ endpoint: `${req.method} ${req.path}` }, async () => {\n * await handleRequest(req, res);\n * setTraceResponseInfo(res.statusCode, contentLength);\n * captureCurrentTrace(); // Records the trace with all spans\n * });\n * ```\n */\nexport function captureCurrentTrace(): void {\n if (!store) return;\n\n const ctx = getTraceContext();\n if (!ctx) return;\n\n const durationMs = Date.now() - ctx.startedAt.getTime();\n const isError = (ctx.statusCode ?? 0) >= 500;\n\n if (!shouldSample(isError)) return;\n\n if (ctx.isTask) {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown-task\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n isTask: true,\n });\n } else {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: ctx.statusCode ?? 0,\n bodySize: ctx.bodySize ?? 0,\n clientIP: ctx.clientIP ?? \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n });\n }\n}\n\nexport function shouldSample(isError: boolean): boolean {\n if (!store) return false;\n const rate = isError ? store.errorSampleRate : store.sampleRate;\n if (rate >= 1) return true;\n if (rate <= 0) return false;\n return Math.random() < rate;\n}\n\nexport function measureTask(\n title: string,\n fn: () => void | Promise<void>,\n): void {\n const traceId = generateUUID();\n const start = Date.now();\n const startDate = new Date(start);\n\n try {\n const result = fn();\n if (result && typeof (result as Promise<void>).then === \"function\") {\n (result as Promise<void>)\n .then(() => {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n })\n .catch((err: unknown) => {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n });\n } else {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n }\n } catch (err) {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n }\n}\n\nexport async function shutdown(): Promise<void> {\n if (!store) return;\n const s = store;\n store = null;\n await s.shutdown();\n}\n","import * as zlib from \"zlib\";\nimport {\n nowISO,\n generateUUID,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport { TypedRing } from \"./typed-ring.js\";\nimport type {\n CollectionFrame,\n ExceptionStackTrace,\n MetricRecord,\n Trace,\n Span,\n ReportRequest,\n} from \"@tracewayapp/core\";\nimport { collectMetrics } from \"./metrics.js\";\n\nexport interface CollectionFrameStoreOptions {\n apiUrl: string;\n token: string;\n debug: boolean;\n maxCollectionFrames: number;\n collectionInterval: number;\n uploadThrottle: number;\n metricsInterval: number;\n version: string;\n serverName: string;\n sampleRate: number;\n errorSampleRate: number;\n}\n\nexport class CollectionFrameStore {\n private current: CollectionFrame | null = null;\n private currentSetAt: number = Date.now();\n private sendQueue: TypedRing<CollectionFrame>;\n private lastUploadStarted: number | null = null;\n\n private collectionTimer: ReturnType<typeof setInterval> | null = null;\n private metricsTimer: ReturnType<typeof setInterval> | null = null;\n\n private readonly apiUrl: string;\n private readonly token: string;\n private readonly debug: boolean;\n private readonly collectionInterval: number;\n private readonly uploadThrottle: number;\n private readonly metricsInterval: number;\n private readonly version: string;\n private readonly serverName: string;\n\n readonly sampleRate: number;\n readonly errorSampleRate: number;\n\n constructor(options: CollectionFrameStoreOptions) {\n this.apiUrl = options.apiUrl;\n this.token = options.token;\n this.debug = options.debug;\n this.collectionInterval = options.collectionInterval;\n this.uploadThrottle = options.uploadThrottle;\n this.metricsInterval = options.metricsInterval;\n this.version = options.version;\n this.serverName = options.serverName;\n this.sampleRate = options.sampleRate;\n this.errorSampleRate = options.errorSampleRate;\n this.sendQueue = new TypedRing<CollectionFrame>(\n options.maxCollectionFrames,\n );\n\n this.collectionTimer = setInterval(() => {\n this.tick();\n }, this.collectionInterval);\n if (this.collectionTimer && typeof this.collectionTimer.unref === \"function\") {\n this.collectionTimer.unref();\n }\n\n this.metricsTimer = setInterval(() => {\n this.collectSystemMetrics();\n }, this.metricsInterval);\n if (this.metricsTimer && typeof this.metricsTimer.unref === \"function\") {\n this.metricsTimer.unref();\n }\n }\n\n private tick(): void {\n if (this.current !== null) {\n if (this.currentSetAt < Date.now() - this.collectionInterval) {\n this.rotateCurrentCollectionFrame();\n this.processSendQueue();\n }\n } else if (this.sendQueue.length > 0) {\n this.processSendQueue();\n }\n }\n\n private ensureCurrent(): CollectionFrame {\n if (this.current === null) {\n this.current = { stackTraces: [], metrics: [], traces: [] };\n this.currentSetAt = Date.now();\n }\n return this.current;\n }\n\n addException(exception: ExceptionStackTrace): void {\n this.ensureCurrent().stackTraces.push(exception);\n }\n\n addMetric(metric: MetricRecord): void {\n this.ensureCurrent().metrics.push(metric);\n }\n\n addTrace(trace: Trace): void {\n this.ensureCurrent().traces.push(trace);\n }\n\n private rotateCurrentCollectionFrame(): void {\n if (this.current !== null) {\n this.sendQueue.push(this.current);\n this.current = null;\n }\n }\n\n private processSendQueue(): void {\n if (\n this.lastUploadStarted === null ||\n this.lastUploadStarted < Date.now() - this.uploadThrottle\n ) {\n this.lastUploadStarted = Date.now();\n const frames = this.sendQueue.readAll();\n if (frames.length > 0) {\n this.triggerUpload(frames);\n }\n }\n }\n\n private triggerUpload(framesToSend: CollectionFrame[]): void {\n const payload: ReportRequest = {\n collectionFrames: framesToSend,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n let jsonData: string;\n try {\n jsonData = JSON.stringify(payload);\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to serialize frames:\", err);\n }\n return;\n }\n\n let gzipped: Uint8Array;\n try {\n gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to gzip:\", err);\n }\n return;\n }\n\n fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n })\n .then((resp) => {\n if (resp.status === 200) {\n this.sendQueue.remove(framesToSend);\n } else if (this.debug) {\n console.error(`Traceway: upload returned status ${resp.status}`);\n }\n })\n .catch((err) => {\n if (this.debug) {\n console.error(\"Traceway: upload failed:\", err);\n }\n });\n }\n\n private collectSystemMetrics(): void {\n try {\n const metrics = collectMetrics();\n for (const metric of metrics) {\n this.addMetric(metric);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to collect metrics:\", err);\n }\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.collectionTimer !== null) {\n clearInterval(this.collectionTimer);\n this.collectionTimer = null;\n }\n if (this.metricsTimer !== null) {\n clearInterval(this.metricsTimer);\n this.metricsTimer = null;\n }\n\n this.rotateCurrentCollectionFrame();\n\n const frames = this.sendQueue.readAll();\n if (frames.length === 0) return;\n\n const payload: ReportRequest = {\n collectionFrames: frames,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n try {\n const jsonData = JSON.stringify(payload);\n const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n\n const resp = await fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n });\n\n if (resp.status === 200) {\n this.sendQueue.remove(frames);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: shutdown upload failed:\", err);\n }\n }\n }\n}\n","export class TypedRing<T> {\n private arr: (T | null)[];\n private head: number = 0;\n private _capacity: number;\n private _len: number = 0;\n\n constructor(capacity: number) {\n this._capacity = capacity;\n this.arr = new Array<T | null>(capacity).fill(null);\n }\n\n get length(): number {\n return this._len;\n }\n\n get capacity(): number {\n return this._capacity;\n }\n\n push(val: T): void {\n this.arr[this.head] = val;\n this.head = (this.head + 1) % this._capacity;\n if (this._len < this._capacity) {\n this._len += 1;\n }\n }\n\n readAll(): T[] {\n const result: T[] = [];\n for (let i = 0; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n result.push(this.arr[idx] as T);\n }\n return result;\n }\n\n clear(): void {\n for (let i = 0; i < this.arr.length; i++) {\n this.arr[i] = null;\n }\n this.head = 0;\n this._len = 0;\n }\n\n remove(vals: T[]): number {\n if (vals.length === 0) return 0;\n\n const toRemove = new Set<T>(vals);\n let writeIdx = 0;\n let removed = 0;\n\n for (let i = 0; i < this._len; i++) {\n const readIdx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n if (toRemove.has(this.arr[readIdx] as T)) {\n removed++;\n } else {\n if (writeIdx !== i) {\n const destIdx =\n (this.head - this._len + writeIdx + this._capacity) %\n this._capacity;\n this.arr[destIdx] = this.arr[readIdx];\n }\n writeIdx++;\n }\n }\n\n for (let i = writeIdx; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n this.arr[idx] = null;\n }\n\n this._len = writeIdx;\n this.head = (this.head - removed + this._capacity) % this._capacity;\n\n return removed;\n }\n}\n","import * as os from \"os\";\nimport { METRIC_MEM_USED, METRIC_MEM_TOTAL, METRIC_CPU_USED_PCNT } from \"@tracewayapp/core\";\nimport type { MetricRecord } from \"@tracewayapp/core\";\nimport { nowISO } from \"@tracewayapp/core\";\n\nlet prevCpuUsage: NodeJS.CpuUsage | null = null;\nlet prevCpuTime: number | null = null;\n\nexport function collectMetrics(): MetricRecord[] {\n const metrics: MetricRecord[] = [];\n const recordedAt = nowISO();\n\n const mem = process.memoryUsage();\n metrics.push({\n name: METRIC_MEM_USED,\n value: Math.round((mem.rss / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const totalMem = os.totalmem();\n metrics.push({\n name: METRIC_MEM_TOTAL,\n value: Math.round((totalMem / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const currentCpuUsage = process.cpuUsage();\n const currentTime = Date.now();\n if (prevCpuUsage !== null && prevCpuTime !== null) {\n const elapsedMs = currentTime - prevCpuTime;\n if (elapsedMs > 0) {\n const userDelta = currentCpuUsage.user - prevCpuUsage.user;\n const systemDelta = currentCpuUsage.system - prevCpuUsage.system;\n const totalDeltaMs = (userDelta + systemDelta) / 1000;\n const cpuCount = os.cpus().length || 1;\n const cpuPercent = (totalDeltaMs / elapsedMs / cpuCount) * 100;\n metrics.push({\n name: METRIC_CPU_USED_PCNT,\n value: Math.round(cpuPercent * 100) / 100,\n recordedAt,\n });\n }\n }\n prevCpuUsage = currentCpuUsage;\n prevCpuTime = currentTime;\n\n return metrics;\n}\n\nexport function resetCpuTracking(): void {\n prevCpuUsage = null;\n prevCpuTime = null;\n}\n","export function formatErrorStackTrace(error: Error): string {\n const lines: string[] = [];\n\n const typeName = error.constructor.name || \"Error\";\n lines.push(`${typeName}: ${error.message}`);\n\n if (error.stack) {\n const stackLines = error.stack.split(\"\\n\");\n for (const line of stackLines) {\n const match = line.match(/^\\s+at\\s+(.+?)\\s+\\((.+):(\\d+):\\d+\\)$/);\n if (match) {\n const funcName = shortenFunctionName(match[1]);\n const file = shortenFilePath(match[2]);\n const lineNum = match[3];\n lines.push(`${funcName}()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchNoParens = line.match(/^\\s+at\\s+(.+):(\\d+):\\d+$/);\n if (matchNoParens) {\n const file = shortenFilePath(matchNoParens[1]);\n const lineNum = matchNoParens[2];\n lines.push(`<anonymous>()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchFnOnly = line.match(/^\\s+at\\s+(.+)$/);\n if (matchFnOnly) {\n const funcName = shortenFunctionName(matchFnOnly[1]);\n lines.push(`${funcName}()`);\n lines.push(` <unknown>:0`);\n }\n }\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nfunction shortenFunctionName(fn: string): string {\n const slashIdx = fn.lastIndexOf(\"/\");\n if (slashIdx >= 0) {\n fn = fn.slice(slashIdx + 1);\n }\n const dotIdx = fn.indexOf(\".\");\n if (dotIdx >= 0) {\n fn = fn.slice(dotIdx + 1);\n }\n return fn;\n}\n\nfunction shortenFilePath(filePath: string): string {\n const parts = filePath.split(\"/\");\n return parts[parts.length - 1];\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport { generateUUID } from \"@tracewayapp/core\";\nimport type { Span } from \"@tracewayapp/core\";\n\n/**\n * Trace context stored in AsyncLocalStorage.\n * Automatically propagates through async operations.\n */\nexport interface TraceContext {\n /** Unique trace identifier (UUID v4) */\n traceId: string;\n /** Whether this is a background task (vs HTTP request) */\n isTask: boolean;\n /** When the trace started */\n startedAt: Date;\n /** Collected spans within this trace */\n spans: Span[];\n /** Key-value attributes for this trace */\n attributes: Record<string, string>;\n /** For HTTP traces: endpoint like \"GET /api/users\" */\n endpoint?: string;\n /** For HTTP traces: response status code */\n statusCode?: number;\n /** For HTTP traces: response body size */\n bodySize?: number;\n /** For HTTP traces: client IP address */\n clientIP?: string;\n}\n\n/**\n * Options for creating a new trace context.\n */\nexport interface TraceContextOptions {\n /** Custom trace ID (auto-generated if not provided) */\n traceId?: string;\n /** Mark as background task instead of HTTP trace */\n isTask?: boolean;\n /** Initial attributes */\n attributes?: Record<string, string>;\n /** HTTP endpoint (e.g., \"GET /api/users\") */\n endpoint?: string;\n /** Client IP address */\n clientIP?: string;\n}\n\n// The AsyncLocalStorage instance for trace context\nconst asyncLocalStorage = new AsyncLocalStorage<TraceContext>();\n\n/**\n * Get the current trace context, if any.\n * Returns undefined if not within a trace context.\n */\nexport function getTraceContext(): TraceContext | undefined {\n return asyncLocalStorage.getStore();\n}\n\n/**\n * Get the current trace ID, if within a trace context.\n */\nexport function getTraceId(): string | undefined {\n return asyncLocalStorage.getStore()?.traceId;\n}\n\n/**\n * Check if currently within a trace context.\n */\nexport function hasTraceContext(): boolean {\n return asyncLocalStorage.getStore() !== undefined;\n}\n\n/**\n * Run a function within a new trace context.\n * All async operations within will have access to this context.\n *\n * @example\n * ```ts\n * // HTTP request handler\n * withTraceContext({ endpoint: \"GET /api/users\", clientIP: req.ip }, async () => {\n * const users = await db.query(\"SELECT * FROM users\");\n * captureException(new Error(\"oops\")); // Auto-linked to trace\n * return users;\n * });\n *\n * // Background task\n * withTraceContext({ isTask: true, endpoint: \"process-emails\" }, async () => {\n * await processEmails();\n * });\n * ```\n */\nexport function withTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T,\n): T {\n const context: TraceContext = {\n traceId: options.traceId ?? generateUUID(),\n isTask: options.isTask ?? false,\n startedAt: new Date(),\n spans: [],\n attributes: options.attributes ?? {},\n endpoint: options.endpoint,\n clientIP: options.clientIP,\n };\n return asyncLocalStorage.run(context, fn);\n}\n\n/**\n * Run a function within a trace context, automatically capturing the trace on completion.\n * This is a convenience wrapper that handles timing and capture automatically.\n *\n * @example\n * ```ts\n * // In Express middleware\n * app.use((req, res, next) => {\n * runWithTraceContext(\n * {\n * endpoint: `${req.method} ${req.path}`,\n * clientIP: req.ip,\n * attributes: { userId: req.user?.id },\n * },\n * async () => {\n * await next();\n * // Status code and body size set via setTraceResponseInfo()\n * },\n * { captureOnEnd: true }\n * );\n * });\n * ```\n */\nexport function runWithTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return withTraceContext(options, fn);\n}\n\n/**\n * Add a completed span to the current trace context.\n * No-op if not within a trace context.\n */\nexport function addSpanToContext(span: Span): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.spans.push(span);\n }\n}\n\n/**\n * Set an attribute on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttribute(key: string, value: string): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.attributes[key] = value;\n }\n}\n\n/**\n * Set multiple attributes on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttributes(attributes: Record<string, string>): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n Object.assign(ctx.attributes, attributes);\n }\n}\n\n/**\n * Set HTTP response info on the current trace context.\n * Used by framework adapters after the response is sent.\n */\nexport function setTraceResponseInfo(\n statusCode: number,\n bodySize?: number,\n): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.statusCode = statusCode;\n ctx.bodySize = bodySize;\n }\n}\n\n/**\n * Get all spans from the current trace context.\n * Returns empty array if not within a trace context.\n */\nexport function getTraceSpans(): Span[] {\n return asyncLocalStorage.getStore()?.spans ?? [];\n}\n\n/**\n * Get the duration in milliseconds since the trace started.\n * Returns 0 if not within a trace context.\n */\nexport function getTraceDuration(): number {\n const ctx = asyncLocalStorage.getStore();\n if (!ctx) return 0;\n return Date.now() - ctx.startedAt.getTime();\n}\n\n/**\n * Fork the current trace context for a sub-operation.\n * Useful for parallel operations that should have isolated spans.\n * Returns undefined if not within a trace context.\n */\nexport function forkTraceContext<T>(fn: () => T): T | undefined {\n const parentCtx = asyncLocalStorage.getStore();\n if (!parentCtx) return undefined;\n\n const forkedContext: TraceContext = {\n ...parentCtx,\n spans: [], // Forked context gets its own spans\n attributes: { ...parentCtx.attributes },\n };\n\n return asyncLocalStorage.run(forkedContext, () => {\n const result = fn();\n // Merge spans back to parent after completion\n parentCtx.spans.push(...forkedContext.spans);\n return result;\n });\n}\n\n// Export the AsyncLocalStorage instance for advanced use cases\nexport { asyncLocalStorage as traceContextStorage };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAKO;;;ACLP,WAAsB;;;ACAf,IAAM,YAAN,MAAmB;AAAA,EAChB;AAAA,EACA,OAAe;AAAA,EACf;AAAA,EACA,OAAe;AAAA,EAEvB,YAAY,UAAkB;AAC5B,SAAK,YAAY;AACjB,SAAK,MAAM,IAAI,MAAgB,QAAQ,EAAE,KAAK,IAAI;AAAA,EACpD;AAAA,EAEA,IAAI,SAAiB;AACnB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,WAAmB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AS;AACnB;","names":["import_core","import_core","import_core","os","hostname"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/traceway.ts","../src/collection-frame-store.ts","../src/typed-ring.ts","../src/metrics.ts","../src/stack-trace.ts","../src/context.ts"],"sourcesContent":["export {\n init,\n captureException,\n captureExceptionWithAttributes,\n captureMessage,\n captureMetric,\n captureMetricWithTags,\n captureTrace,\n captureTask,\n captureCurrentTrace,\n startSpan,\n endSpan,\n shouldSample,\n measureTask,\n shutdown,\n} from \"./traceway.js\";\nexport type { SpanHandle } from \"./traceway.js\";\n\n// Context propagation (AsyncLocalStorage-based)\nexport {\n withTraceContext,\n runWithTraceContext,\n getTraceContext,\n getTraceId,\n hasTraceContext,\n addSpanToContext,\n setTraceAttribute,\n setTraceAttributes,\n setTraceResponseInfo,\n getTraceSpans,\n getTraceDuration,\n forkTraceContext,\n traceContextStorage,\n} from \"./context.js\";\nexport type { TraceContext, TraceContextOptions } from \"./context.js\";\n\nexport { formatErrorStackTrace } from \"./stack-trace.js\";\nexport { collectMetrics, resetCpuTracking } from \"./metrics.js\";\nexport { CollectionFrameStore } from \"./collection-frame-store.js\";\nexport type { CollectionFrameStoreOptions } from \"./collection-frame-store.js\";\n\nexport type {\n ExceptionStackTrace,\n MetricRecord,\n Span,\n Trace,\n CollectionFrame,\n ReportRequest,\n TracewayOptions,\n} from \"@tracewayapp/core\";\n","import {\n generateUUID,\n parseConnectionString,\n nowISO,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport type {\n TracewayOptions,\n ExceptionStackTrace,\n Trace,\n Span,\n} from \"@tracewayapp/core\";\nimport { CollectionFrameStore } from \"./collection-frame-store.js\";\nimport { formatErrorStackTrace } from \"./stack-trace.js\";\nimport {\n getTraceContext,\n getTraceId,\n addSpanToContext,\n type TraceContext,\n} from \"./context.js\";\nimport * as os from \"os\";\n\nlet store: CollectionFrameStore | null = null;\n\nfunction getHostname(): string {\n try {\n const hostname = os.hostname();\n const dotIdx = hostname.indexOf(\".\");\n return dotIdx >= 0 ? hostname.slice(0, dotIdx) : hostname;\n } catch {\n return \"unknown\";\n }\n}\n\nexport function init(\n connectionString: string,\n options: TracewayOptions = {},\n): void {\n if (store !== null) {\n throw new Error(\"Traceway: already initialized. Call shutdown() first.\");\n }\n\n const { token, apiUrl } = parseConnectionString(connectionString);\n\n store = new CollectionFrameStore({\n apiUrl,\n token,\n debug: options.debug ?? false,\n maxCollectionFrames: options.maxCollectionFrames ?? 12,\n collectionInterval: options.collectionInterval ?? 5000,\n uploadThrottle: options.uploadThrottle ?? 2000,\n metricsInterval: options.metricsInterval ?? 30000,\n version: options.version ?? \"\",\n serverName: options.serverName ?? getHostname(),\n sampleRate: options.sampleRate ?? 1,\n errorSampleRate: options.errorSampleRate ?? 1,\n });\n}\n\nexport function captureException(error: Error): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n captureExceptionWithAttributes(\n error,\n ctx?.attributes,\n ctx?.traceId,\n );\n}\n\nexport function captureExceptionWithAttributes(\n error: Error,\n attributes?: Record<string, string>,\n traceId?: string,\n): void {\n if (!store) return;\n // Auto-detect trace context if not explicitly provided\n const ctx = getTraceContext();\n const resolvedTraceId = traceId ?? ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: formatErrorStackTrace(error),\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: false,\n });\n}\n\nexport function captureMessage(\n msg: string,\n attributes?: Record<string, string>,\n): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n const resolvedTraceId = ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: msg,\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: true,\n });\n}\n\nexport function captureMetric(name: string, value: number): void {\n if (!store) return;\n store.addMetric({\n name,\n value,\n recordedAt: nowISO(),\n });\n}\n\nexport function captureMetricWithTags(\n name: string,\n value: number,\n tags: Record<string, string>,\n): void {\n if (!store) return;\n store.addMetric({\n name,\n value,\n recordedAt: nowISO(),\n tags,\n });\n}\n\nexport function captureTrace(\n traceId: string,\n endpoint: string,\n durationMs: number,\n startedAt: Date,\n statusCode: number,\n bodySize: number,\n clientIP: string,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode,\n bodySize,\n clientIP,\n attributes,\n spans,\n });\n}\n\nexport function captureTask(\n traceId: string,\n taskName: string,\n durationMs: number,\n startedAt: Date,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint: taskName,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes,\n spans,\n isTask: true,\n });\n}\n\n/** Handle returned by startSpan for tracking span timing */\nexport interface SpanHandle {\n id: string;\n name: string;\n startTime: string;\n startedAt: number;\n}\n\n/**\n * Start a new span. If within a trace context, the span will be\n * automatically added to the trace when ended.\n */\nexport function startSpan(name: string): SpanHandle {\n const now = Date.now();\n return {\n id: generateUUID(),\n name,\n startTime: new Date(now).toISOString(),\n startedAt: now,\n };\n}\n\n/**\n * End a span and get the completed Span object.\n * If within a trace context, automatically adds the span to the trace.\n *\n * @param addToContext - If true (default), adds span to current trace context\n */\nexport function endSpan(span: SpanHandle, addToContext: boolean = true): Span {\n const durationMs = Date.now() - span.startedAt;\n const completedSpan: Span = {\n id: span.id,\n name: span.name,\n startTime: span.startTime,\n duration: msToNanoseconds(durationMs),\n };\n\n // Auto-add to trace context if available\n if (addToContext) {\n addSpanToContext(completedSpan);\n }\n\n return completedSpan;\n}\n\n/**\n * Capture the current trace context as a trace.\n * Call this at the end of a request/task to record the trace.\n *\n * @example\n * ```ts\n * // In Express middleware (after response)\n * withTraceContext({ endpoint: `${req.method} ${req.path}` }, async () => {\n * await handleRequest(req, res);\n * setTraceResponseInfo(res.statusCode, contentLength);\n * captureCurrentTrace(); // Records the trace with all spans\n * });\n * ```\n */\nexport function captureCurrentTrace(): void {\n if (!store) return;\n\n const ctx = getTraceContext();\n if (!ctx) return;\n\n const durationMs = Date.now() - ctx.startedAt.getTime();\n const isError = (ctx.statusCode ?? 0) >= 500;\n\n if (!shouldSample(isError)) return;\n\n if (ctx.isTask) {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown-task\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n isTask: true,\n });\n } else {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: ctx.statusCode ?? 0,\n bodySize: ctx.bodySize ?? 0,\n clientIP: ctx.clientIP ?? \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n });\n }\n}\n\nexport function shouldSample(isError: boolean): boolean {\n if (!store) return false;\n const rate = isError ? store.errorSampleRate : store.sampleRate;\n if (rate >= 1) return true;\n if (rate <= 0) return false;\n return Math.random() < rate;\n}\n\nexport function measureTask(\n title: string,\n fn: () => void | Promise<void>,\n): void {\n const traceId = generateUUID();\n const start = Date.now();\n const startDate = new Date(start);\n\n try {\n const result = fn();\n if (result && typeof (result as Promise<void>).then === \"function\") {\n (result as Promise<void>)\n .then(() => {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n })\n .catch((err: unknown) => {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n });\n } else {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n }\n } catch (err) {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n }\n}\n\nexport async function shutdown(timeoutMs?: number): Promise<void> {\n if (!store) return;\n const s = store;\n store = null;\n await s.shutdown(timeoutMs);\n}\n","import * as zlib from \"zlib\";\nimport {\n nowISO,\n generateUUID,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport { TypedRing } from \"./typed-ring.js\";\nimport type {\n CollectionFrame,\n ExceptionStackTrace,\n MetricRecord,\n Trace,\n Span,\n ReportRequest,\n} from \"@tracewayapp/core\";\nimport { collectMetrics } from \"./metrics.js\";\n\nexport interface CollectionFrameStoreOptions {\n apiUrl: string;\n token: string;\n debug: boolean;\n maxCollectionFrames: number;\n collectionInterval: number;\n uploadThrottle: number;\n metricsInterval: number;\n version: string;\n serverName: string;\n sampleRate: number;\n errorSampleRate: number;\n}\n\nexport class CollectionFrameStore {\n private current: CollectionFrame | null = null;\n private currentSetAt: number = Date.now();\n private sendQueue: TypedRing<CollectionFrame>;\n private lastUploadStarted: number | null = null;\n\n private collectionTimer: ReturnType<typeof setInterval> | null = null;\n private metricsTimer: ReturnType<typeof setInterval> | null = null;\n\n private readonly apiUrl: string;\n private readonly token: string;\n private readonly debug: boolean;\n private readonly collectionInterval: number;\n private readonly uploadThrottle: number;\n private readonly metricsInterval: number;\n private readonly version: string;\n private readonly serverName: string;\n\n readonly sampleRate: number;\n readonly errorSampleRate: number;\n\n constructor(options: CollectionFrameStoreOptions) {\n this.apiUrl = options.apiUrl;\n this.token = options.token;\n this.debug = options.debug;\n this.collectionInterval = options.collectionInterval;\n this.uploadThrottle = options.uploadThrottle;\n this.metricsInterval = options.metricsInterval;\n this.version = options.version;\n this.serverName = options.serverName;\n this.sampleRate = options.sampleRate;\n this.errorSampleRate = options.errorSampleRate;\n this.sendQueue = new TypedRing<CollectionFrame>(\n options.maxCollectionFrames,\n );\n\n this.collectionTimer = setInterval(() => {\n this.tick();\n }, this.collectionInterval);\n if (this.collectionTimer && typeof this.collectionTimer.unref === \"function\") {\n this.collectionTimer.unref();\n }\n\n this.metricsTimer = setInterval(() => {\n this.collectSystemMetrics();\n }, this.metricsInterval);\n if (this.metricsTimer && typeof this.metricsTimer.unref === \"function\") {\n this.metricsTimer.unref();\n }\n }\n\n private tick(): void {\n if (this.current !== null) {\n if (this.currentSetAt < Date.now() - this.collectionInterval) {\n this.rotateCurrentCollectionFrame();\n this.processSendQueue();\n }\n } else if (this.sendQueue.length > 0) {\n this.processSendQueue();\n }\n }\n\n private ensureCurrent(): CollectionFrame {\n if (this.current === null) {\n this.current = { stackTraces: [], metrics: [], traces: [] };\n this.currentSetAt = Date.now();\n }\n return this.current;\n }\n\n addException(exception: ExceptionStackTrace): void {\n this.ensureCurrent().stackTraces.push(exception);\n }\n\n addMetric(metric: MetricRecord): void {\n this.ensureCurrent().metrics.push(metric);\n }\n\n addTrace(trace: Trace): void {\n this.ensureCurrent().traces.push(trace);\n }\n\n private rotateCurrentCollectionFrame(): void {\n if (this.current !== null) {\n this.sendQueue.push(this.current);\n this.current = null;\n }\n }\n\n private processSendQueue(): void {\n if (\n this.lastUploadStarted === null ||\n this.lastUploadStarted < Date.now() - this.uploadThrottle\n ) {\n this.lastUploadStarted = Date.now();\n const frames = this.sendQueue.readAll();\n if (frames.length > 0) {\n this.triggerUpload(frames);\n }\n }\n }\n\n private triggerUpload(framesToSend: CollectionFrame[]): void {\n const payload: ReportRequest = {\n collectionFrames: framesToSend,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n let jsonData: string;\n try {\n jsonData = JSON.stringify(payload);\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to serialize frames:\", err);\n }\n return;\n }\n\n let gzipped: Uint8Array;\n try {\n gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to gzip:\", err);\n }\n return;\n }\n\n fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n })\n .then((resp) => {\n if (resp.status === 200) {\n this.sendQueue.remove(framesToSend);\n } else if (this.debug) {\n console.error(`Traceway: upload returned status ${resp.status}`);\n }\n })\n .catch((err) => {\n if (this.debug) {\n console.error(\"Traceway: upload failed:\", err);\n }\n });\n }\n\n private collectSystemMetrics(): void {\n try {\n const metrics = collectMetrics();\n for (const metric of metrics) {\n this.addMetric(metric);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to collect metrics:\", err);\n }\n }\n }\n\n async shutdown(timeoutMs?: number): Promise<void> {\n if (this.collectionTimer !== null) {\n clearInterval(this.collectionTimer);\n this.collectionTimer = null;\n }\n if (this.metricsTimer !== null) {\n clearInterval(this.metricsTimer);\n this.metricsTimer = null;\n }\n\n this.rotateCurrentCollectionFrame();\n\n const frames = this.sendQueue.readAll();\n if (frames.length === 0) return;\n\n const uploadPromise = (async () => {\n const payload: ReportRequest = {\n collectionFrames: frames,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n try {\n const jsonData = JSON.stringify(payload);\n const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n\n const resp = await fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n });\n\n if (resp.status === 200) {\n this.sendQueue.remove(frames);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: shutdown upload failed:\", err);\n }\n }\n })();\n\n if (timeoutMs !== undefined) {\n await Promise.race([\n uploadPromise,\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n } else {\n await uploadPromise;\n }\n }\n}\n","export class TypedRing<T> {\n private arr: (T | null)[];\n private head: number = 0;\n private _capacity: number;\n private _len: number = 0;\n\n constructor(capacity: number) {\n this._capacity = capacity;\n this.arr = new Array<T | null>(capacity).fill(null);\n }\n\n get length(): number {\n return this._len;\n }\n\n get capacity(): number {\n return this._capacity;\n }\n\n push(val: T): void {\n this.arr[this.head] = val;\n this.head = (this.head + 1) % this._capacity;\n if (this._len < this._capacity) {\n this._len += 1;\n }\n }\n\n readAll(): T[] {\n const result: T[] = [];\n for (let i = 0; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n result.push(this.arr[idx] as T);\n }\n return result;\n }\n\n clear(): void {\n for (let i = 0; i < this.arr.length; i++) {\n this.arr[i] = null;\n }\n this.head = 0;\n this._len = 0;\n }\n\n remove(vals: T[]): number {\n if (vals.length === 0) return 0;\n\n const toRemove = new Set<T>(vals);\n let writeIdx = 0;\n let removed = 0;\n\n for (let i = 0; i < this._len; i++) {\n const readIdx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n if (toRemove.has(this.arr[readIdx] as T)) {\n removed++;\n } else {\n if (writeIdx !== i) {\n const destIdx =\n (this.head - this._len + writeIdx + this._capacity) %\n this._capacity;\n this.arr[destIdx] = this.arr[readIdx];\n }\n writeIdx++;\n }\n }\n\n for (let i = writeIdx; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n this.arr[idx] = null;\n }\n\n this._len = writeIdx;\n this.head = (this.head - removed + this._capacity) % this._capacity;\n\n return removed;\n }\n}\n","import * as os from \"os\";\nimport { METRIC_MEM_USED, METRIC_MEM_TOTAL, METRIC_CPU_USED_PCNT } from \"@tracewayapp/core\";\nimport type { MetricRecord } from \"@tracewayapp/core\";\nimport { nowISO } from \"@tracewayapp/core\";\n\nlet prevCpuUsage: NodeJS.CpuUsage | null = null;\nlet prevCpuTime: number | null = null;\n\nexport function collectMetrics(): MetricRecord[] {\n const metrics: MetricRecord[] = [];\n const recordedAt = nowISO();\n\n const mem = process.memoryUsage();\n metrics.push({\n name: METRIC_MEM_USED,\n value: Math.round((mem.rss / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const totalMem = os.totalmem();\n metrics.push({\n name: METRIC_MEM_TOTAL,\n value: Math.round((totalMem / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const currentCpuUsage = process.cpuUsage();\n const currentTime = Date.now();\n if (prevCpuUsage !== null && prevCpuTime !== null) {\n const elapsedMs = currentTime - prevCpuTime;\n if (elapsedMs > 0) {\n const userDelta = currentCpuUsage.user - prevCpuUsage.user;\n const systemDelta = currentCpuUsage.system - prevCpuUsage.system;\n const totalDeltaMs = (userDelta + systemDelta) / 1000;\n const cpuCount = os.cpus().length || 1;\n const cpuPercent = (totalDeltaMs / elapsedMs / cpuCount) * 100;\n metrics.push({\n name: METRIC_CPU_USED_PCNT,\n value: Math.round(cpuPercent * 100) / 100,\n recordedAt,\n });\n }\n }\n prevCpuUsage = currentCpuUsage;\n prevCpuTime = currentTime;\n\n return metrics;\n}\n\nexport function resetCpuTracking(): void {\n prevCpuUsage = null;\n prevCpuTime = null;\n}\n","export function formatErrorStackTrace(error: Error): string {\n const lines: string[] = [];\n\n const typeName = error.constructor.name || \"Error\";\n lines.push(`${typeName}: ${error.message}`);\n\n if (error.stack) {\n const stackLines = error.stack.split(\"\\n\");\n for (const line of stackLines) {\n const match = line.match(/^\\s+at\\s+(.+?)\\s+\\((.+):(\\d+):\\d+\\)$/);\n if (match) {\n const funcName = shortenFunctionName(match[1]);\n const file = shortenFilePath(match[2]);\n const lineNum = match[3];\n lines.push(`${funcName}()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchNoParens = line.match(/^\\s+at\\s+(.+):(\\d+):\\d+$/);\n if (matchNoParens) {\n const file = shortenFilePath(matchNoParens[1]);\n const lineNum = matchNoParens[2];\n lines.push(`<anonymous>()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchFnOnly = line.match(/^\\s+at\\s+(.+)$/);\n if (matchFnOnly) {\n const funcName = shortenFunctionName(matchFnOnly[1]);\n lines.push(`${funcName}()`);\n lines.push(` <unknown>:0`);\n }\n }\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nfunction shortenFunctionName(fn: string): string {\n const slashIdx = fn.lastIndexOf(\"/\");\n if (slashIdx >= 0) {\n fn = fn.slice(slashIdx + 1);\n }\n const dotIdx = fn.indexOf(\".\");\n if (dotIdx >= 0) {\n fn = fn.slice(dotIdx + 1);\n }\n return fn;\n}\n\nfunction shortenFilePath(filePath: string): string {\n const parts = filePath.split(\"/\");\n return parts[parts.length - 1];\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport { generateUUID } from \"@tracewayapp/core\";\nimport type { Span } from \"@tracewayapp/core\";\n\n/**\n * Trace context stored in AsyncLocalStorage.\n * Automatically propagates through async operations.\n */\nexport interface TraceContext {\n /** Unique trace identifier (UUID v4) */\n traceId: string;\n /** Whether this is a background task (vs HTTP request) */\n isTask: boolean;\n /** When the trace started */\n startedAt: Date;\n /** Collected spans within this trace */\n spans: Span[];\n /** Key-value attributes for this trace */\n attributes: Record<string, string>;\n /** For HTTP traces: endpoint like \"GET /api/users\" */\n endpoint?: string;\n /** For HTTP traces: response status code */\n statusCode?: number;\n /** For HTTP traces: response body size */\n bodySize?: number;\n /** For HTTP traces: client IP address */\n clientIP?: string;\n}\n\n/**\n * Options for creating a new trace context.\n */\nexport interface TraceContextOptions {\n /** Custom trace ID (auto-generated if not provided) */\n traceId?: string;\n /** Mark as background task instead of HTTP trace */\n isTask?: boolean;\n /** Initial attributes */\n attributes?: Record<string, string>;\n /** HTTP endpoint (e.g., \"GET /api/users\") */\n endpoint?: string;\n /** Client IP address */\n clientIP?: string;\n}\n\n// The AsyncLocalStorage instance for trace context\nconst asyncLocalStorage = new AsyncLocalStorage<TraceContext>();\n\n/**\n * Get the current trace context, if any.\n * Returns undefined if not within a trace context.\n */\nexport function getTraceContext(): TraceContext | undefined {\n return asyncLocalStorage.getStore();\n}\n\n/**\n * Get the current trace ID, if within a trace context.\n */\nexport function getTraceId(): string | undefined {\n return asyncLocalStorage.getStore()?.traceId;\n}\n\n/**\n * Check if currently within a trace context.\n */\nexport function hasTraceContext(): boolean {\n return asyncLocalStorage.getStore() !== undefined;\n}\n\n/**\n * Run a function within a new trace context.\n * All async operations within will have access to this context.\n *\n * @example\n * ```ts\n * // HTTP request handler\n * withTraceContext({ endpoint: \"GET /api/users\", clientIP: req.ip }, async () => {\n * const users = await db.query(\"SELECT * FROM users\");\n * captureException(new Error(\"oops\")); // Auto-linked to trace\n * return users;\n * });\n *\n * // Background task\n * withTraceContext({ isTask: true, endpoint: \"process-emails\" }, async () => {\n * await processEmails();\n * });\n * ```\n */\nexport function withTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T,\n): T {\n const context: TraceContext = {\n traceId: options.traceId ?? generateUUID(),\n isTask: options.isTask ?? false,\n startedAt: new Date(),\n spans: [],\n attributes: options.attributes ?? {},\n endpoint: options.endpoint,\n clientIP: options.clientIP,\n };\n return asyncLocalStorage.run(context, fn);\n}\n\n/**\n * Run a function within a trace context, automatically capturing the trace on completion.\n * This is a convenience wrapper that handles timing and capture automatically.\n *\n * @example\n * ```ts\n * // In Express middleware\n * app.use((req, res, next) => {\n * runWithTraceContext(\n * {\n * endpoint: `${req.method} ${req.path}`,\n * clientIP: req.ip,\n * attributes: { userId: req.user?.id },\n * },\n * async () => {\n * await next();\n * // Status code and body size set via setTraceResponseInfo()\n * },\n * { captureOnEnd: true }\n * );\n * });\n * ```\n */\nexport function runWithTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return withTraceContext(options, fn);\n}\n\n/**\n * Add a completed span to the current trace context.\n * No-op if not within a trace context.\n */\nexport function addSpanToContext(span: Span): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.spans.push(span);\n }\n}\n\n/**\n * Set an attribute on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttribute(key: string, value: string): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.attributes[key] = value;\n }\n}\n\n/**\n * Set multiple attributes on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttributes(attributes: Record<string, string>): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n Object.assign(ctx.attributes, attributes);\n }\n}\n\n/**\n * Set HTTP response info on the current trace context.\n * Used by framework adapters after the response is sent.\n */\nexport function setTraceResponseInfo(\n statusCode: number,\n bodySize?: number,\n): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.statusCode = statusCode;\n ctx.bodySize = bodySize;\n }\n}\n\n/**\n * Get all spans from the current trace context.\n * Returns empty array if not within a trace context.\n */\nexport function getTraceSpans(): Span[] {\n return asyncLocalStorage.getStore()?.spans ?? [];\n}\n\n/**\n * Get the duration in milliseconds since the trace started.\n * Returns 0 if not within a trace context.\n */\nexport function getTraceDuration(): number {\n const ctx = asyncLocalStorage.getStore();\n if (!ctx) return 0;\n return Date.now() - ctx.startedAt.getTime();\n}\n\n/**\n * Fork the current trace context for a sub-operation.\n * Useful for parallel operations that should have isolated spans.\n * Returns undefined if not within a trace context.\n */\nexport function forkTraceContext<T>(fn: () => T): T | undefined {\n const parentCtx = asyncLocalStorage.getStore();\n if (!parentCtx) return undefined;\n\n const forkedContext: TraceContext = {\n ...parentCtx,\n spans: [], // Forked context gets its own spans\n attributes: { ...parentCtx.attributes },\n };\n\n return asyncLocalStorage.run(forkedContext, () => {\n const result = fn();\n // Merge spans back to parent after completion\n parentCtx.spans.push(...forkedContext.spans);\n return result;\n });\n}\n\n// Export the AsyncLocalStorage instance for advanced use cases\nexport { asyncLocalStorage as traceContextStorage };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAKO;;;ACLP,WAAsB;;;ACAf,IAAM,YAAN,MAAmB;AAAA,EAChB;AAAA,EACA,OAAe;AAAA,EACf;AAAA,EACA,OAAe;AAAA,EAEvB,YAAY,UAAkB;AAC5B,SAAK,YAAY;AACjB,SAAK,MAAM,IAAI,MAAgB,QAAQ,EAAE,KAAK,IAAI;AAAA,EACpD;AAAA,EAEA,IAAI,SAAiB;AACnB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,WAAmB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,KAAK,KAAc;AACjB,SAAK,IAAI,KAAK,IAAI,IAAI;AACtB,SAAK,QAAQ,KAAK,OAAO,KAAK,KAAK;AACnC,QAAI,KAAK,OAAO,KAAK,WAAW;AAC9B,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA,EAEA,UAAe;AACb,UAAM,SAAc,CAAC;AACrB,aAAS,IAAI,GAAG,IAAI,KAAK,MAAM,KAAK;AAClC,YAAM,OACH,KAAK,OAAO,KAAK,OAAO,IAAI,KAAK,aAAa,KAAK;AACtD,aAAO,KAAK,KAAK,IAAI,GAAG,CAAM;AAAA,IAChC;AACA,WAAO;AAAA,EACT;AAAA,EAEA,QAAc;AACZ,aAAS,IAAI,GAAG,IAAI,KAAK,IAAI,QAAQ,KAAK;AACxC,WAAK,IAAI,CAAC,IA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I;AACzB;AAEO,SAAS,YACd,OACA,IACM;AACN,QAAM,cAAU,2BAAa;AAC7B,QAAM,QAAQ,KAAK,IAAI;AACvB,QAAM,YAAY,IAAI,KAAK,KAAK;AAEhC,MAAI;AACF,UAAM,SAAS,GAAG;AAClB,QAAI,UAAU,OAAQ,OAAyB,SAAS,YAAY;AAClE,MAAC,OACE,KAAK,MAAM;AACV,cAAM,aAAa,KAAK,IAAI,IAAI;AAChC,YAAI,aAAa,KAAK,GAAG;AACvB,sBAAY,SAAS,OAAO,YAAY,SAAS;AAAA,QACnD;AAAA,MACF,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,cAAM,aAAa,KAAK,IAAI,IAAI;AAChC,YAAI,aAAa,IAAI,GAAG;AACtB,sBAAY,SAAS,OAAO,YAAY,SAAS;AACjD,cAAI,eAAe,OAAO;AACxB,2CAA+B,KAAK,QAAW,OAAO;AAAA,UACxD;AAAA,QACF;AACA,cAAM;AAAA,MACR,CAAC;AAAA,IACL,OAAO;AACL,YAAM,aAAa,KAAK,IAAI,IAAI;AAChC,UAAI,aAAa,KAAK,GAAG;AACvB,oBAAY,SAAS,OAAO,YAAY,SAAS;AAAA,MACnD;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,UAAM,aAAa,KAAK,IAAI,IAAI;AAChC,QAAI,aAAa,IAAI,GAAG;AACtB,kBAAY,SAAS,OAAO,YAAY,SAAS;AACjD,UAAI,eAAe,OAAO;AACxB,uCAA+B,KAAK,QAAW,OAAO;AAAA,MACxD;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACF;AAEA,eAAsB,SAAS,WAAmC;AAChE,MAAI,CAAC,MAAO;AACZ,QAAM,IAAI;AACV,UAAQ;AACR,QAAM,EAAE,SAAS,SAAS;AAC5B;","names":["import_core","import_core","import_core","os","hostname"]}
package/dist/index.mjs CHANGED
@@ -263,7 +263,7 @@ var CollectionFrameStore = class {
263
263
  }
264
264
  }
265
265
  }
266
- async shutdown() {
266
+ async shutdown(timeoutMs) {
267
267
  if (this.collectionTimer !== null) {
268
268
  clearInterval(this.collectionTimer);
269
269
  this.collectionTimer = null;
@@ -275,30 +275,40 @@ var CollectionFrameStore = class {
275
275
  this.rotateCurrentCollectionFrame();
276
276
  const frames = this.sendQueue.readAll();
277
277
  if (frames.length === 0) return;
278
- const payload = {
279
- collectionFrames: frames,
280
- appVersion: this.version,
281
- serverName: this.serverName
282
- };
283
- try {
284
- const jsonData = JSON.stringify(payload);
285
- const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));
286
- const resp = await fetch(this.apiUrl, {
287
- method: "POST",
288
- headers: {
289
- "Content-Type": "application/json",
290
- "Content-Encoding": "gzip",
291
- Authorization: `Bearer ${this.token}`
292
- },
293
- body: gzipped
294
- });
295
- if (resp.status === 200) {
296
- this.sendQueue.remove(frames);
297
- }
298
- } catch (err) {
299
- if (this.debug) {
300
- console.error("Traceway: shutdown upload failed:", err);
278
+ const uploadPromise = (async () => {
279
+ const payload = {
280
+ collectionFrames: frames,
281
+ appVersion: this.version,
282
+ serverName: this.serverName
283
+ };
284
+ try {
285
+ const jsonData = JSON.stringify(payload);
286
+ const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));
287
+ const resp = await fetch(this.apiUrl, {
288
+ method: "POST",
289
+ headers: {
290
+ "Content-Type": "application/json",
291
+ "Content-Encoding": "gzip",
292
+ Authorization: `Bearer ${this.token}`
293
+ },
294
+ body: gzipped
295
+ });
296
+ if (resp.status === 200) {
297
+ this.sendQueue.remove(frames);
298
+ }
299
+ } catch (err) {
300
+ if (this.debug) {
301
+ console.error("Traceway: shutdown upload failed:", err);
302
+ }
301
303
  }
304
+ })();
305
+ if (timeoutMs !== void 0) {
306
+ await Promise.race([
307
+ uploadPromise,
308
+ new Promise((resolve) => setTimeout(resolve, timeoutMs))
309
+ ]);
310
+ } else {
311
+ await uploadPromise;
302
312
  }
303
313
  }
304
314
  };
@@ -509,6 +519,15 @@ function captureMetric(name, value) {
509
519
  recordedAt: nowISO2()
510
520
  });
511
521
  }
522
+ function captureMetricWithTags(name, value, tags) {
523
+ if (!store) return;
524
+ store.addMetric({
525
+ name,
526
+ value,
527
+ recordedAt: nowISO2(),
528
+ tags
529
+ });
530
+ }
512
531
  function captureTrace(traceId, endpoint, durationMs, startedAt, statusCode, bodySize, clientIP, attributes, spans) {
513
532
  if (!store) return;
514
533
  store.addTrace({
@@ -640,11 +659,11 @@ function measureTask(title, fn) {
640
659
  throw err;
641
660
  }
642
661
  }
643
- async function shutdown() {
662
+ async function shutdown(timeoutMs) {
644
663
  if (!store) return;
645
664
  const s = store;
646
665
  store = null;
647
- await s.shutdown();
666
+ await s.shutdown(timeoutMs);
648
667
  }
649
668
  export {
650
669
  CollectionFrameStore,
@@ -654,6 +673,7 @@ export {
654
673
  captureExceptionWithAttributes,
655
674
  captureMessage,
656
675
  captureMetric,
676
+ captureMetricWithTags,
657
677
  captureTask,
658
678
  captureTrace,
659
679
  collectMetrics,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/traceway.ts","../src/collection-frame-store.ts","../src/typed-ring.ts","../src/metrics.ts","../src/stack-trace.ts","../src/context.ts"],"sourcesContent":["import {\n generateUUID,\n parseConnectionString,\n nowISO,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport type {\n TracewayOptions,\n ExceptionStackTrace,\n Trace,\n Span,\n} from \"@tracewayapp/core\";\nimport { CollectionFrameStore } from \"./collection-frame-store.js\";\nimport { formatErrorStackTrace } from \"./stack-trace.js\";\nimport {\n getTraceContext,\n getTraceId,\n addSpanToContext,\n type TraceContext,\n} from \"./context.js\";\nimport * as os from \"os\";\n\nlet store: CollectionFrameStore | null = null;\n\nfunction getHostname(): string {\n try {\n const hostname = os.hostname();\n const dotIdx = hostname.indexOf(\".\");\n return dotIdx >= 0 ? hostname.slice(0, dotIdx) : hostname;\n } catch {\n return \"unknown\";\n }\n}\n\nexport function init(\n connectionString: string,\n options: TracewayOptions = {},\n): void {\n if (store !== null) {\n throw new Error(\"Traceway: already initialized. Call shutdown() first.\");\n }\n\n const { token, apiUrl } = parseConnectionString(connectionString);\n\n store = new CollectionFrameStore({\n apiUrl,\n token,\n debug: options.debug ?? false,\n maxCollectionFrames: options.maxCollectionFrames ?? 12,\n collectionInterval: options.collectionInterval ?? 5000,\n uploadThrottle: options.uploadThrottle ?? 2000,\n metricsInterval: options.metricsInterval ?? 30000,\n version: options.version ?? \"\",\n serverName: options.serverName ?? getHostname(),\n sampleRate: options.sampleRate ?? 1,\n errorSampleRate: options.errorSampleRate ?? 1,\n });\n}\n\nexport function captureException(error: Error): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n captureExceptionWithAttributes(\n error,\n ctx?.attributes,\n ctx?.traceId,\n );\n}\n\nexport function captureExceptionWithAttributes(\n error: Error,\n attributes?: Record<string, string>,\n traceId?: string,\n): void {\n if (!store) return;\n // Auto-detect trace context if not explicitly provided\n const ctx = getTraceContext();\n const resolvedTraceId = traceId ?? ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: formatErrorStackTrace(error),\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: false,\n });\n}\n\nexport function captureMessage(\n msg: string,\n attributes?: Record<string, string>,\n): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n const resolvedTraceId = ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: msg,\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: true,\n });\n}\n\nexport function captureMetric(name: string, value: number): void {\n if (!store) return;\n store.addMetric({\n name,\n value,\n recordedAt: nowISO(),\n });\n}\n\nexport function captureTrace(\n traceId: string,\n endpoint: string,\n durationMs: number,\n startedAt: Date,\n statusCode: number,\n bodySize: number,\n clientIP: string,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode,\n bodySize,\n clientIP,\n attributes,\n spans,\n });\n}\n\nexport function captureTask(\n traceId: string,\n taskName: string,\n durationMs: number,\n startedAt: Date,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint: taskName,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes,\n spans,\n isTask: true,\n });\n}\n\n/** Handle returned by startSpan for tracking span timing */\nexport interface SpanHandle {\n id: string;\n name: string;\n startTime: string;\n startedAt: number;\n}\n\n/**\n * Start a new span. If within a trace context, the span will be\n * automatically added to the trace when ended.\n */\nexport function startSpan(name: string): SpanHandle {\n const now = Date.now();\n return {\n id: generateUUID(),\n name,\n startTime: new Date(now).toISOString(),\n startedAt: now,\n };\n}\n\n/**\n * End a span and get the completed Span object.\n * If within a trace context, automatically adds the span to the trace.\n *\n * @param addToContext - If true (default), adds span to current trace context\n */\nexport function endSpan(span: SpanHandle, addToContext: boolean = true): Span {\n const durationMs = Date.now() - span.startedAt;\n const completedSpan: Span = {\n id: span.id,\n name: span.name,\n startTime: span.startTime,\n duration: msToNanoseconds(durationMs),\n };\n\n // Auto-add to trace context if available\n if (addToContext) {\n addSpanToContext(completedSpan);\n }\n\n return completedSpan;\n}\n\n/**\n * Capture the current trace context as a trace.\n * Call this at the end of a request/task to record the trace.\n *\n * @example\n * ```ts\n * // In Express middleware (after response)\n * withTraceContext({ endpoint: `${req.method} ${req.path}` }, async () => {\n * await handleRequest(req, res);\n * setTraceResponseInfo(res.statusCode, contentLength);\n * captureCurrentTrace(); // Records the trace with all spans\n * });\n * ```\n */\nexport function captureCurrentTrace(): void {\n if (!store) return;\n\n const ctx = getTraceContext();\n if (!ctx) return;\n\n const durationMs = Date.now() - ctx.startedAt.getTime();\n const isError = (ctx.statusCode ?? 0) >= 500;\n\n if (!shouldSample(isError)) return;\n\n if (ctx.isTask) {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown-task\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n isTask: true,\n });\n } else {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: ctx.statusCode ?? 0,\n bodySize: ctx.bodySize ?? 0,\n clientIP: ctx.clientIP ?? \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n });\n }\n}\n\nexport function shouldSample(isError: boolean): boolean {\n if (!store) return false;\n const rate = isError ? store.errorSampleRate : store.sampleRate;\n if (rate >= 1) return true;\n if (rate <= 0) return false;\n return Math.random() < rate;\n}\n\nexport function measureTask(\n title: string,\n fn: () => void | Promise<void>,\n): void {\n const traceId = generateUUID();\n const start = Date.now();\n const startDate = new Date(start);\n\n try {\n const result = fn();\n if (result && typeof (result as Promise<void>).then === \"function\") {\n (result as Promise<void>)\n .then(() => {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n })\n .catch((err: unknown) => {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n });\n } else {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n }\n } catch (err) {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n }\n}\n\nexport async function shutdown(): Promise<void> {\n if (!store) return;\n const s = store;\n store = null;\n await s.shutdown();\n}\n","import * as zlib from \"zlib\";\nimport {\n nowISO,\n generateUUID,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport { TypedRing } from \"./typed-ring.js\";\nimport type {\n CollectionFrame,\n ExceptionStackTrace,\n MetricRecord,\n Trace,\n Span,\n ReportRequest,\n} from \"@tracewayapp/core\";\nimport { collectMetrics } from \"./metrics.js\";\n\nexport interface CollectionFrameStoreOptions {\n apiUrl: string;\n token: string;\n debug: boolean;\n maxCollectionFrames: number;\n collectionInterval: number;\n uploadThrottle: number;\n metricsInterval: number;\n version: string;\n serverName: string;\n sampleRate: number;\n errorSampleRate: number;\n}\n\nexport class CollectionFrameStore {\n private current: CollectionFrame | null = null;\n private currentSetAt: number = Date.now();\n private sendQueue: TypedRing<CollectionFrame>;\n private lastUploadStarted: number | null = null;\n\n private collectionTimer: ReturnType<typeof setInterval> | null = null;\n private metricsTimer: ReturnType<typeof setInterval> | null = null;\n\n private readonly apiUrl: string;\n private readonly token: string;\n private readonly debug: boolean;\n private readonly collectionInterval: number;\n private readonly uploadThrottle: number;\n private readonly metricsInterval: number;\n private readonly version: string;\n private readonly serverName: string;\n\n readonly sampleRate: number;\n readonly errorSampleRate: number;\n\n constructor(options: CollectionFrameStoreOptions) {\n this.apiUrl = options.apiUrl;\n this.token = options.token;\n this.debug = options.debug;\n this.collectionInterval = options.collectionInterval;\n this.uploadThrottle = options.uploadThrottle;\n this.metricsInterval = options.metricsInterval;\n this.version = options.version;\n this.serverName = options.serverName;\n this.sampleRate = options.sampleRate;\n this.errorSampleRate = options.errorSampleRate;\n this.sendQueue = new TypedRing<CollectionFrame>(\n options.maxCollectionFrames,\n );\n\n this.collectionTimer = setInterval(() => {\n this.tick();\n }, this.collectionInterval);\n if (this.collectionTimer && typeof this.collectionTimer.unref === \"function\") {\n this.collectionTimer.unref();\n }\n\n this.metricsTimer = setInterval(() => {\n this.collectSystemMetrics();\n }, this.metricsInterval);\n if (this.metricsTimer && typeof this.metricsTimer.unref === \"function\") {\n this.metricsTimer.unref();\n }\n }\n\n private tick(): void {\n if (this.current !== null) {\n if (this.currentSetAt < Date.now() - this.collectionInterval) {\n this.rotateCurrentCollectionFrame();\n this.processSendQueue();\n }\n } else if (this.sendQueue.length > 0) {\n this.processSendQueue();\n }\n }\n\n private ensureCurrent(): CollectionFrame {\n if (this.current === null) {\n this.current = { stackTraces: [], metrics: [], traces: [] };\n this.currentSetAt = Date.now();\n }\n return this.current;\n }\n\n addException(exception: ExceptionStackTrace): void {\n this.ensureCurrent().stackTraces.push(exception);\n }\n\n addMetric(metric: MetricRecord): void {\n this.ensureCurrent().metrics.push(metric);\n }\n\n addTrace(trace: Trace): void {\n this.ensureCurrent().traces.push(trace);\n }\n\n private rotateCurrentCollectionFrame(): void {\n if (this.current !== null) {\n this.sendQueue.push(this.current);\n this.current = null;\n }\n }\n\n private processSendQueue(): void {\n if (\n this.lastUploadStarted === null ||\n this.lastUploadStarted < Date.now() - this.uploadThrottle\n ) {\n this.lastUploadStarted = Date.now();\n const frames = this.sendQueue.readAll();\n if (frames.length > 0) {\n this.triggerUpload(frames);\n }\n }\n }\n\n private triggerUpload(framesToSend: CollectionFrame[]): void {\n const payload: ReportRequest = {\n collectionFrames: framesToSend,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n let jsonData: string;\n try {\n jsonData = JSON.stringify(payload);\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to serialize frames:\", err);\n }\n return;\n }\n\n let gzipped: Uint8Array;\n try {\n gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to gzip:\", err);\n }\n return;\n }\n\n fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n })\n .then((resp) => {\n if (resp.status === 200) {\n this.sendQueue.remove(framesToSend);\n } else if (this.debug) {\n console.error(`Traceway: upload returned status ${resp.status}`);\n }\n })\n .catch((err) => {\n if (this.debug) {\n console.error(\"Traceway: upload failed:\", err);\n }\n });\n }\n\n private collectSystemMetrics(): void {\n try {\n const metrics = collectMetrics();\n for (const metric of metrics) {\n this.addMetric(metric);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to collect metrics:\", err);\n }\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.collectionTimer !== null) {\n clearInterval(this.collectionTimer);\n this.collectionTimer = null;\n }\n if (this.metricsTimer !== null) {\n clearInterval(this.metricsTimer);\n this.metricsTimer = null;\n }\n\n this.rotateCurrentCollectionFrame();\n\n const frames = this.sendQueue.readAll();\n if (frames.length === 0) return;\n\n const payload: ReportRequest = {\n collectionFrames: frames,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n try {\n const jsonData = JSON.stringify(payload);\n const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n\n const resp = await fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n });\n\n if (resp.status === 200) {\n this.sendQueue.remove(frames);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: shutdown upload failed:\", err);\n }\n }\n }\n}\n","export class TypedRing<T> {\n private arr: (T | null)[];\n private head: number = 0;\n private _capacity: number;\n private _len: number = 0;\n\n constructor(capacity: number) {\n this._capacity = capacity;\n this.arr = new Array<T | null>(capacity).fill(null);\n }\n\n get length(): number {\n return this._len;\n }\n\n get capacity(): number {\n return this._capacity;\n }\n\n push(val: T): void {\n this.arr[this.head] = val;\n this.head = (this.head + 1) % this._capacity;\n if (this._len < this._capacity) {\n this._len += 1;\n }\n }\n\n readAll(): T[] {\n const result: T[] = [];\n for (let i = 0; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n result.push(this.arr[idx] as T);\n }\n return result;\n }\n\n clear(): void {\n for (let i = 0; i < this.arr.length; i++) {\n this.arr[i] = null;\n }\n this.head = 0;\n this._len = 0;\n }\n\n remove(vals: T[]): number {\n if (vals.length === 0) return 0;\n\n const toRemove = new Set<T>(vals);\n let writeIdx = 0;\n let removed = 0;\n\n for (let i = 0; i < this._len; i++) {\n const readIdx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n if (toRemove.has(this.arr[readIdx] as T)) {\n removed++;\n } else {\n if (writeIdx !== i) {\n const destIdx =\n (this.head - this._len + writeIdx + this._capacity) %\n this._capacity;\n this.arr[destIdx] = this.arr[readIdx];\n }\n writeIdx++;\n }\n }\n\n for (let i = writeIdx; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n this.arr[idx] = null;\n }\n\n this._len = writeIdx;\n this.head = (this.head - removed + this._capacity) % this._capacity;\n\n return removed;\n }\n}\n","import * as os from \"os\";\nimport { METRIC_MEM_USED, METRIC_MEM_TOTAL, METRIC_CPU_USED_PCNT } from \"@tracewayapp/core\";\nimport type { MetricRecord } from \"@tracewayapp/core\";\nimport { nowISO } from \"@tracewayapp/core\";\n\nlet prevCpuUsage: NodeJS.CpuUsage | null = null;\nlet prevCpuTime: number | null = null;\n\nexport function collectMetrics(): MetricRecord[] {\n const metrics: MetricRecord[] = [];\n const recordedAt = nowISO();\n\n const mem = process.memoryUsage();\n metrics.push({\n name: METRIC_MEM_USED,\n value: Math.round((mem.rss / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const totalMem = os.totalmem();\n metrics.push({\n name: METRIC_MEM_TOTAL,\n value: Math.round((totalMem / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const currentCpuUsage = process.cpuUsage();\n const currentTime = Date.now();\n if (prevCpuUsage !== null && prevCpuTime !== null) {\n const elapsedMs = currentTime - prevCpuTime;\n if (elapsedMs > 0) {\n const userDelta = currentCpuUsage.user - prevCpuUsage.user;\n const systemDelta = currentCpuUsage.system - prevCpuUsage.system;\n const totalDeltaMs = (userDelta + systemDelta) / 1000;\n const cpuCount = os.cpus().length || 1;\n const cpuPercent = (totalDeltaMs / elapsedMs / cpuCount) * 100;\n metrics.push({\n name: METRIC_CPU_USED_PCNT,\n value: Math.round(cpuPercent * 100) / 100,\n recordedAt,\n });\n }\n }\n prevCpuUsage = currentCpuUsage;\n prevCpuTime = currentTime;\n\n return metrics;\n}\n\nexport function resetCpuTracking(): void {\n prevCpuUsage = null;\n prevCpuTime = null;\n}\n","export function formatErrorStackTrace(error: Error): string {\n const lines: string[] = [];\n\n const typeName = error.constructor.name || \"Error\";\n lines.push(`${typeName}: ${error.message}`);\n\n if (error.stack) {\n const stackLines = error.stack.split(\"\\n\");\n for (const line of stackLines) {\n const match = line.match(/^\\s+at\\s+(.+?)\\s+\\((.+):(\\d+):\\d+\\)$/);\n if (match) {\n const funcName = shortenFunctionName(match[1]);\n const file = shortenFilePath(match[2]);\n const lineNum = match[3];\n lines.push(`${funcName}()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchNoParens = line.match(/^\\s+at\\s+(.+):(\\d+):\\d+$/);\n if (matchNoParens) {\n const file = shortenFilePath(matchNoParens[1]);\n const lineNum = matchNoParens[2];\n lines.push(`<anonymous>()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchFnOnly = line.match(/^\\s+at\\s+(.+)$/);\n if (matchFnOnly) {\n const funcName = shortenFunctionName(matchFnOnly[1]);\n lines.push(`${funcName}()`);\n lines.push(` <unknown>:0`);\n }\n }\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nfunction shortenFunctionName(fn: string): string {\n const slashIdx = fn.lastIndexOf(\"/\");\n if (slashIdx >= 0) {\n fn = fn.slice(slashIdx + 1);\n }\n const dotIdx = fn.indexOf(\".\");\n if (dotIdx >= 0) {\n fn = fn.slice(dotIdx + 1);\n }\n return fn;\n}\n\nfunction shortenFilePath(filePath: string): string {\n const parts = filePath.split(\"/\");\n return parts[parts.length - 1];\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport { generateUUID } from \"@tracewayapp/core\";\nimport type { Span } from \"@tracewayapp/core\";\n\n/**\n * Trace context stored in AsyncLocalStorage.\n * Automatically propagates through async operations.\n */\nexport interface TraceContext {\n /** Unique trace identifier (UUID v4) */\n traceId: string;\n /** Whether this is a background task (vs HTTP request) */\n isTask: boolean;\n /** When the trace started */\n startedAt: Date;\n /** Collected spans within this trace */\n spans: Span[];\n /** Key-value attributes for this trace */\n attributes: Record<string, string>;\n /** For HTTP traces: endpoint like \"GET /api/users\" */\n endpoint?: string;\n /** For HTTP traces: response status code */\n statusCode?: number;\n /** For HTTP traces: response body size */\n bodySize?: number;\n /** For HTTP traces: client IP address */\n clientIP?: string;\n}\n\n/**\n * Options for creating a new trace context.\n */\nexport interface TraceContextOptions {\n /** Custom trace ID (auto-generated if not provided) */\n traceId?: string;\n /** Mark as background task instead of HTTP trace */\n isTask?: boolean;\n /** Initial attributes */\n attributes?: Record<string, string>;\n /** HTTP endpoint (e.g., \"GET /api/users\") */\n endpoint?: string;\n /** Client IP address */\n clientIP?: string;\n}\n\n// The AsyncLocalStorage instance for trace context\nconst asyncLocalStorage = new AsyncLocalStorage<TraceContext>();\n\n/**\n * Get the current trace context, if any.\n * Returns undefined if not within a trace context.\n */\nexport function getTraceContext(): TraceContext | undefined {\n return asyncLocalStorage.getStore();\n}\n\n/**\n * Get the current trace ID, if within a trace context.\n */\nexport function getTraceId(): string | undefined {\n return asyncLocalStorage.getStore()?.traceId;\n}\n\n/**\n * Check if currently within a trace context.\n */\nexport function hasTraceContext(): boolean {\n return asyncLocalStorage.getStore() !== undefined;\n}\n\n/**\n * Run a function within a new trace context.\n * All async operations within will have access to this context.\n *\n * @example\n * ```ts\n * // HTTP request handler\n * withTraceContext({ endpoint: \"GET /api/users\", clientIP: req.ip }, async () => {\n * const users = await db.query(\"SELECT * FROM users\");\n * captureException(new Error(\"oops\")); // Auto-linked to trace\n * return users;\n * });\n *\n * // Background task\n * withTraceContext({ isTask: true, endpoint: \"process-emails\" }, async () => {\n * await processEmails();\n * });\n * ```\n */\nexport function withTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T,\n): T {\n const context: TraceContext = {\n traceId: options.traceId ?? generateUUID(),\n isTask: options.isTask ?? false,\n startedAt: new Date(),\n spans: [],\n attributes: options.attributes ?? {},\n endpoint: options.endpoint,\n clientIP: options.clientIP,\n };\n return asyncLocalStorage.run(context, fn);\n}\n\n/**\n * Run a function within a trace context, automatically capturing the trace on completion.\n * This is a convenience wrapper that handles timing and capture automatically.\n *\n * @example\n * ```ts\n * // In Express middleware\n * app.use((req, res, next) => {\n * runWithTraceContext(\n * {\n * endpoint: `${req.method} ${req.path}`,\n * clientIP: req.ip,\n * attributes: { userId: req.user?.id },\n * },\n * async () => {\n * await next();\n * // Status code and body size set via setTraceResponseInfo()\n * },\n * { captureOnEnd: true }\n * );\n * });\n * ```\n */\nexport function runWithTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return withTraceContext(options, fn);\n}\n\n/**\n * Add a completed span to the current trace context.\n * No-op if not within a trace context.\n */\nexport function addSpanToContext(span: Span): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.spans.push(span);\n }\n}\n\n/**\n * Set an attribute on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttribute(key: string, value: string): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.attributes[key] = value;\n }\n}\n\n/**\n * Set multiple attributes on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttributes(attributes: Record<string, string>): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n Object.assign(ctx.attributes, attributes);\n }\n}\n\n/**\n * Set HTTP response info on the current trace context.\n * Used by framework adapters after the response is sent.\n */\nexport function setTraceResponseInfo(\n statusCode: number,\n bodySize?: number,\n): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.statusCode = statusCode;\n ctx.bodySize = bodySize;\n }\n}\n\n/**\n * Get all spans from the current trace context.\n * Returns empty array if not within a trace context.\n */\nexport function getTraceSpans(): Span[] {\n return asyncLocalStorage.getStore()?.spans ?? [];\n}\n\n/**\n * Get the duration in milliseconds since the trace started.\n * Returns 0 if not within a trace context.\n */\nexport function getTraceDuration(): number {\n const ctx = asyncLocalStorage.getStore();\n if (!ctx) return 0;\n return Date.now() - ctx.startedAt.getTime();\n}\n\n/**\n * Fork the current trace context for a sub-operation.\n * Useful for parallel operations that should have isolated spans.\n * Returns undefined if not within a trace context.\n */\nexport function forkTraceContext<T>(fn: () => T): T | undefined {\n const parentCtx = asyncLocalStorage.getStore();\n if (!parentCtx) return undefined;\n\n const forkedContext: TraceContext = {\n ...parentCtx,\n spans: [], // Forked context gets its own spans\n attributes: { ...parentCtx.attributes },\n };\n\n return asyncLocalStorage.run(forkedContext, () => {\n const result = fn();\n // Merge spans back to parent after completion\n parentCtx.spans.push(...forkedContext.spans);\n return result;\n });\n}\n\n// Export the AsyncLocalStorage instance for advanced use cases\nexport { asyncLocalStorage as traceContextStorage };\n"],"mappings":";AAAA;AAAA,EACE,gBAAAA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA;AAAA,OACK;;;ACLP,YAAY,UAAU;;;ACAf,IAAM,YAAN,MAAmB;AAAA,EAChB;AAAA,EACA,OAAe;AAAA,EACf;AAAA,EACA,OAAe;AAAA,EAEvB,YAAY,UAAkB;AAC5B,SAAK,YAAY;AACjB,SAAK,MAAM,IAAI,MAAgB,QAAQ,EAAE,KAAK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;AACA,UAAM;AAAA,EACR;AACF;AAEA,eAAsB,WAA0B;AAC9C,MAAI,CAAC,MAAO;AACZ,QAAM,IAAI;AACV,UAAQ;AACR,QAAM,EAAE,SAAS;AACnB;","names":["generateUUID","nowISO","os","hostname","nowISO","generateUUID"]}
1
+ {"version":3,"sources":["../src/traceway.ts","../src/collection-frame-store.ts","../src/typed-ring.ts","../src/metrics.ts","../src/stack-trace.ts","../src/context.ts"],"sourcesContent":["import {\n generateUUID,\n parseConnectionString,\n nowISO,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport type {\n TracewayOptions,\n ExceptionStackTrace,\n Trace,\n Span,\n} from \"@tracewayapp/core\";\nimport { CollectionFrameStore } from \"./collection-frame-store.js\";\nimport { formatErrorStackTrace } from \"./stack-trace.js\";\nimport {\n getTraceContext,\n getTraceId,\n addSpanToContext,\n type TraceContext,\n} from \"./context.js\";\nimport * as os from \"os\";\n\nlet store: CollectionFrameStore | null = null;\n\nfunction getHostname(): string {\n try {\n const hostname = os.hostname();\n const dotIdx = hostname.indexOf(\".\");\n return dotIdx >= 0 ? hostname.slice(0, dotIdx) : hostname;\n } catch {\n return \"unknown\";\n }\n}\n\nexport function init(\n connectionString: string,\n options: TracewayOptions = {},\n): void {\n if (store !== null) {\n throw new Error(\"Traceway: already initialized. Call shutdown() first.\");\n }\n\n const { token, apiUrl } = parseConnectionString(connectionString);\n\n store = new CollectionFrameStore({\n apiUrl,\n token,\n debug: options.debug ?? false,\n maxCollectionFrames: options.maxCollectionFrames ?? 12,\n collectionInterval: options.collectionInterval ?? 5000,\n uploadThrottle: options.uploadThrottle ?? 2000,\n metricsInterval: options.metricsInterval ?? 30000,\n version: options.version ?? \"\",\n serverName: options.serverName ?? getHostname(),\n sampleRate: options.sampleRate ?? 1,\n errorSampleRate: options.errorSampleRate ?? 1,\n });\n}\n\nexport function captureException(error: Error): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n captureExceptionWithAttributes(\n error,\n ctx?.attributes,\n ctx?.traceId,\n );\n}\n\nexport function captureExceptionWithAttributes(\n error: Error,\n attributes?: Record<string, string>,\n traceId?: string,\n): void {\n if (!store) return;\n // Auto-detect trace context if not explicitly provided\n const ctx = getTraceContext();\n const resolvedTraceId = traceId ?? ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: formatErrorStackTrace(error),\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: false,\n });\n}\n\nexport function captureMessage(\n msg: string,\n attributes?: Record<string, string>,\n): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n const resolvedTraceId = ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: msg,\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: true,\n });\n}\n\nexport function captureMetric(name: string, value: number): void {\n if (!store) return;\n store.addMetric({\n name,\n value,\n recordedAt: nowISO(),\n });\n}\n\nexport function captureMetricWithTags(\n name: string,\n value: number,\n tags: Record<string, string>,\n): void {\n if (!store) return;\n store.addMetric({\n name,\n value,\n recordedAt: nowISO(),\n tags,\n });\n}\n\nexport function captureTrace(\n traceId: string,\n endpoint: string,\n durationMs: number,\n startedAt: Date,\n statusCode: number,\n bodySize: number,\n clientIP: string,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode,\n bodySize,\n clientIP,\n attributes,\n spans,\n });\n}\n\nexport function captureTask(\n traceId: string,\n taskName: string,\n durationMs: number,\n startedAt: Date,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint: taskName,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes,\n spans,\n isTask: true,\n });\n}\n\n/** Handle returned by startSpan for tracking span timing */\nexport interface SpanHandle {\n id: string;\n name: string;\n startTime: string;\n startedAt: number;\n}\n\n/**\n * Start a new span. If within a trace context, the span will be\n * automatically added to the trace when ended.\n */\nexport function startSpan(name: string): SpanHandle {\n const now = Date.now();\n return {\n id: generateUUID(),\n name,\n startTime: new Date(now).toISOString(),\n startedAt: now,\n };\n}\n\n/**\n * End a span and get the completed Span object.\n * If within a trace context, automatically adds the span to the trace.\n *\n * @param addToContext - If true (default), adds span to current trace context\n */\nexport function endSpan(span: SpanHandle, addToContext: boolean = true): Span {\n const durationMs = Date.now() - span.startedAt;\n const completedSpan: Span = {\n id: span.id,\n name: span.name,\n startTime: span.startTime,\n duration: msToNanoseconds(durationMs),\n };\n\n // Auto-add to trace context if available\n if (addToContext) {\n addSpanToContext(completedSpan);\n }\n\n return completedSpan;\n}\n\n/**\n * Capture the current trace context as a trace.\n * Call this at the end of a request/task to record the trace.\n *\n * @example\n * ```ts\n * // In Express middleware (after response)\n * withTraceContext({ endpoint: `${req.method} ${req.path}` }, async () => {\n * await handleRequest(req, res);\n * setTraceResponseInfo(res.statusCode, contentLength);\n * captureCurrentTrace(); // Records the trace with all spans\n * });\n * ```\n */\nexport function captureCurrentTrace(): void {\n if (!store) return;\n\n const ctx = getTraceContext();\n if (!ctx) return;\n\n const durationMs = Date.now() - ctx.startedAt.getTime();\n const isError = (ctx.statusCode ?? 0) >= 500;\n\n if (!shouldSample(isError)) return;\n\n if (ctx.isTask) {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown-task\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n isTask: true,\n });\n } else {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: ctx.statusCode ?? 0,\n bodySize: ctx.bodySize ?? 0,\n clientIP: ctx.clientIP ?? \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n });\n }\n}\n\nexport function shouldSample(isError: boolean): boolean {\n if (!store) return false;\n const rate = isError ? store.errorSampleRate : store.sampleRate;\n if (rate >= 1) return true;\n if (rate <= 0) return false;\n return Math.random() < rate;\n}\n\nexport function measureTask(\n title: string,\n fn: () => void | Promise<void>,\n): void {\n const traceId = generateUUID();\n const start = Date.now();\n const startDate = new Date(start);\n\n try {\n const result = fn();\n if (result && typeof (result as Promise<void>).then === \"function\") {\n (result as Promise<void>)\n .then(() => {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n })\n .catch((err: unknown) => {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n });\n } else {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n }\n } catch (err) {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n }\n}\n\nexport async function shutdown(timeoutMs?: number): Promise<void> {\n if (!store) return;\n const s = store;\n store = null;\n await s.shutdown(timeoutMs);\n}\n","import * as zlib from \"zlib\";\nimport {\n nowISO,\n generateUUID,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport { TypedRing } from \"./typed-ring.js\";\nimport type {\n CollectionFrame,\n ExceptionStackTrace,\n MetricRecord,\n Trace,\n Span,\n ReportRequest,\n} from \"@tracewayapp/core\";\nimport { collectMetrics } from \"./metrics.js\";\n\nexport interface CollectionFrameStoreOptions {\n apiUrl: string;\n token: string;\n debug: boolean;\n maxCollectionFrames: number;\n collectionInterval: number;\n uploadThrottle: number;\n metricsInterval: number;\n version: string;\n serverName: string;\n sampleRate: number;\n errorSampleRate: number;\n}\n\nexport class CollectionFrameStore {\n private current: CollectionFrame | null = null;\n private currentSetAt: number = Date.now();\n private sendQueue: TypedRing<CollectionFrame>;\n private lastUploadStarted: number | null = null;\n\n private collectionTimer: ReturnType<typeof setInterval> | null = null;\n private metricsTimer: ReturnType<typeof setInterval> | null = null;\n\n private readonly apiUrl: string;\n private readonly token: string;\n private readonly debug: boolean;\n private readonly collectionInterval: number;\n private readonly uploadThrottle: number;\n private readonly metricsInterval: number;\n private readonly version: string;\n private readonly serverName: string;\n\n readonly sampleRate: number;\n readonly errorSampleRate: number;\n\n constructor(options: CollectionFrameStoreOptions) {\n this.apiUrl = options.apiUrl;\n this.token = options.token;\n this.debug = options.debug;\n this.collectionInterval = options.collectionInterval;\n this.uploadThrottle = options.uploadThrottle;\n this.metricsInterval = options.metricsInterval;\n this.version = options.version;\n this.serverName = options.serverName;\n this.sampleRate = options.sampleRate;\n this.errorSampleRate = options.errorSampleRate;\n this.sendQueue = new TypedRing<CollectionFrame>(\n options.maxCollectionFrames,\n );\n\n this.collectionTimer = setInterval(() => {\n this.tick();\n }, this.collectionInterval);\n if (this.collectionTimer && typeof this.collectionTimer.unref === \"function\") {\n this.collectionTimer.unref();\n }\n\n this.metricsTimer = setInterval(() => {\n this.collectSystemMetrics();\n }, this.metricsInterval);\n if (this.metricsTimer && typeof this.metricsTimer.unref === \"function\") {\n this.metricsTimer.unref();\n }\n }\n\n private tick(): void {\n if (this.current !== null) {\n if (this.currentSetAt < Date.now() - this.collectionInterval) {\n this.rotateCurrentCollectionFrame();\n this.processSendQueue();\n }\n } else if (this.sendQueue.length > 0) {\n this.processSendQueue();\n }\n }\n\n private ensureCurrent(): CollectionFrame {\n if (this.current === null) {\n this.current = { stackTraces: [], metrics: [], traces: [] };\n this.currentSetAt = Date.now();\n }\n return this.current;\n }\n\n addException(exception: ExceptionStackTrace): void {\n this.ensureCurrent().stackTraces.push(exception);\n }\n\n addMetric(metric: MetricRecord): void {\n this.ensureCurrent().metrics.push(metric);\n }\n\n addTrace(trace: Trace): void {\n this.ensureCurrent().traces.push(trace);\n }\n\n private rotateCurrentCollectionFrame(): void {\n if (this.current !== null) {\n this.sendQueue.push(this.current);\n this.current = null;\n }\n }\n\n private processSendQueue(): void {\n if (\n this.lastUploadStarted === null ||\n this.lastUploadStarted < Date.now() - this.uploadThrottle\n ) {\n this.lastUploadStarted = Date.now();\n const frames = this.sendQueue.readAll();\n if (frames.length > 0) {\n this.triggerUpload(frames);\n }\n }\n }\n\n private triggerUpload(framesToSend: CollectionFrame[]): void {\n const payload: ReportRequest = {\n collectionFrames: framesToSend,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n let jsonData: string;\n try {\n jsonData = JSON.stringify(payload);\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to serialize frames:\", err);\n }\n return;\n }\n\n let gzipped: Uint8Array;\n try {\n gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to gzip:\", err);\n }\n return;\n }\n\n fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n })\n .then((resp) => {\n if (resp.status === 200) {\n this.sendQueue.remove(framesToSend);\n } else if (this.debug) {\n console.error(`Traceway: upload returned status ${resp.status}`);\n }\n })\n .catch((err) => {\n if (this.debug) {\n console.error(\"Traceway: upload failed:\", err);\n }\n });\n }\n\n private collectSystemMetrics(): void {\n try {\n const metrics = collectMetrics();\n for (const metric of metrics) {\n this.addMetric(metric);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to collect metrics:\", err);\n }\n }\n }\n\n async shutdown(timeoutMs?: number): Promise<void> {\n if (this.collectionTimer !== null) {\n clearInterval(this.collectionTimer);\n this.collectionTimer = null;\n }\n if (this.metricsTimer !== null) {\n clearInterval(this.metricsTimer);\n this.metricsTimer = null;\n }\n\n this.rotateCurrentCollectionFrame();\n\n const frames = this.sendQueue.readAll();\n if (frames.length === 0) return;\n\n const uploadPromise = (async () => {\n const payload: ReportRequest = {\n collectionFrames: frames,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n try {\n const jsonData = JSON.stringify(payload);\n const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n\n const resp = await fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n });\n\n if (resp.status === 200) {\n this.sendQueue.remove(frames);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: shutdown upload failed:\", err);\n }\n }\n })();\n\n if (timeoutMs !== undefined) {\n await Promise.race([\n uploadPromise,\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n } else {\n await uploadPromise;\n }\n }\n}\n","export class TypedRing<T> {\n private arr: (T | null)[];\n private head: number = 0;\n private _capacity: number;\n private _len: number = 0;\n\n constructor(capacity: number) {\n this._capacity = capacity;\n this.arr = new Array<T | null>(capacity).fill(null);\n }\n\n get length(): number {\n return this._len;\n }\n\n get capacity(): number {\n return this._capacity;\n }\n\n push(val: T): void {\n this.arr[this.head] = val;\n this.head = (this.head + 1) % this._capacity;\n if (this._len < this._capacity) {\n this._len += 1;\n }\n }\n\n readAll(): T[] {\n const result: T[] = [];\n for (let i = 0; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n result.push(this.arr[idx] as T);\n }\n return result;\n }\n\n clear(): void {\n for (let i = 0; i < this.arr.length; i++) {\n this.arr[i] = null;\n }\n this.head = 0;\n this._len = 0;\n }\n\n remove(vals: T[]): number {\n if (vals.length === 0) return 0;\n\n const toRemove = new Set<T>(vals);\n let writeIdx = 0;\n let removed = 0;\n\n for (let i = 0; i < this._len; i++) {\n const readIdx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n if (toRemove.has(this.arr[readIdx] as T)) {\n removed++;\n } else {\n if (writeIdx !== i) {\n const destIdx =\n (this.head - this._len + writeIdx + this._capacity) %\n this._capacity;\n this.arr[destIdx] = this.arr[readIdx];\n }\n writeIdx++;\n }\n }\n\n for (let i = writeIdx; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n this.arr[idx] = null;\n }\n\n this._len = writeIdx;\n this.head = (this.head - removed + this._capacity) % this._capacity;\n\n return removed;\n }\n}\n","import * as os from \"os\";\nimport { METRIC_MEM_USED, METRIC_MEM_TOTAL, METRIC_CPU_USED_PCNT } from \"@tracewayapp/core\";\nimport type { MetricRecord } from \"@tracewayapp/core\";\nimport { nowISO } from \"@tracewayapp/core\";\n\nlet prevCpuUsage: NodeJS.CpuUsage | null = null;\nlet prevCpuTime: number | null = null;\n\nexport function collectMetrics(): MetricRecord[] {\n const metrics: MetricRecord[] = [];\n const recordedAt = nowISO();\n\n const mem = process.memoryUsage();\n metrics.push({\n name: METRIC_MEM_USED,\n value: Math.round((mem.rss / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const totalMem = os.totalmem();\n metrics.push({\n name: METRIC_MEM_TOTAL,\n value: Math.round((totalMem / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const currentCpuUsage = process.cpuUsage();\n const currentTime = Date.now();\n if (prevCpuUsage !== null && prevCpuTime !== null) {\n const elapsedMs = currentTime - prevCpuTime;\n if (elapsedMs > 0) {\n const userDelta = currentCpuUsage.user - prevCpuUsage.user;\n const systemDelta = currentCpuUsage.system - prevCpuUsage.system;\n const totalDeltaMs = (userDelta + systemDelta) / 1000;\n const cpuCount = os.cpus().length || 1;\n const cpuPercent = (totalDeltaMs / elapsedMs / cpuCount) * 100;\n metrics.push({\n name: METRIC_CPU_USED_PCNT,\n value: Math.round(cpuPercent * 100) / 100,\n recordedAt,\n });\n }\n }\n prevCpuUsage = currentCpuUsage;\n prevCpuTime = currentTime;\n\n return metrics;\n}\n\nexport function resetCpuTracking(): void {\n prevCpuUsage = null;\n prevCpuTime = null;\n}\n","export function formatErrorStackTrace(error: Error): string {\n const lines: string[] = [];\n\n const typeName = error.constructor.name || \"Error\";\n lines.push(`${typeName}: ${error.message}`);\n\n if (error.stack) {\n const stackLines = error.stack.split(\"\\n\");\n for (const line of stackLines) {\n const match = line.match(/^\\s+at\\s+(.+?)\\s+\\((.+):(\\d+):\\d+\\)$/);\n if (match) {\n const funcName = shortenFunctionName(match[1]);\n const file = shortenFilePath(match[2]);\n const lineNum = match[3];\n lines.push(`${funcName}()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchNoParens = line.match(/^\\s+at\\s+(.+):(\\d+):\\d+$/);\n if (matchNoParens) {\n const file = shortenFilePath(matchNoParens[1]);\n const lineNum = matchNoParens[2];\n lines.push(`<anonymous>()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchFnOnly = line.match(/^\\s+at\\s+(.+)$/);\n if (matchFnOnly) {\n const funcName = shortenFunctionName(matchFnOnly[1]);\n lines.push(`${funcName}()`);\n lines.push(` <unknown>:0`);\n }\n }\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nfunction shortenFunctionName(fn: string): string {\n const slashIdx = fn.lastIndexOf(\"/\");\n if (slashIdx >= 0) {\n fn = fn.slice(slashIdx + 1);\n }\n const dotIdx = fn.indexOf(\".\");\n if (dotIdx >= 0) {\n fn = fn.slice(dotIdx + 1);\n }\n return fn;\n}\n\nfunction shortenFilePath(filePath: string): string {\n const parts = filePath.split(\"/\");\n return parts[parts.length - 1];\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport { generateUUID } from \"@tracewayapp/core\";\nimport type { Span } from \"@tracewayapp/core\";\n\n/**\n * Trace context stored in AsyncLocalStorage.\n * Automatically propagates through async operations.\n */\nexport interface TraceContext {\n /** Unique trace identifier (UUID v4) */\n traceId: string;\n /** Whether this is a background task (vs HTTP request) */\n isTask: boolean;\n /** When the trace started */\n startedAt: Date;\n /** Collected spans within this trace */\n spans: Span[];\n /** Key-value attributes for this trace */\n attributes: Record<string, string>;\n /** For HTTP traces: endpoint like \"GET /api/users\" */\n endpoint?: string;\n /** For HTTP traces: response status code */\n statusCode?: number;\n /** For HTTP traces: response body size */\n bodySize?: number;\n /** For HTTP traces: client IP address */\n clientIP?: string;\n}\n\n/**\n * Options for creating a new trace context.\n */\nexport interface TraceContextOptions {\n /** Custom trace ID (auto-generated if not provided) */\n traceId?: string;\n /** Mark as background task instead of HTTP trace */\n isTask?: boolean;\n /** Initial attributes */\n attributes?: Record<string, string>;\n /** HTTP endpoint (e.g., \"GET /api/users\") */\n endpoint?: string;\n /** Client IP address */\n clientIP?: string;\n}\n\n// The AsyncLocalStorage instance for trace context\nconst asyncLocalStorage = new AsyncLocalStorage<TraceContext>();\n\n/**\n * Get the current trace context, if any.\n * Returns undefined if not within a trace context.\n */\nexport function getTraceContext(): TraceContext | undefined {\n return asyncLocalStorage.getStore();\n}\n\n/**\n * Get the current trace ID, if within a trace context.\n */\nexport function getTraceId(): string | undefined {\n return asyncLocalStorage.getStore()?.traceId;\n}\n\n/**\n * Check if currently within a trace context.\n */\nexport function hasTraceContext(): boolean {\n return asyncLocalStorage.getStore() !== undefined;\n}\n\n/**\n * Run a function within a new trace context.\n * All async operations within will have access to this context.\n *\n * @example\n * ```ts\n * // HTTP request handler\n * withTraceContext({ endpoint: \"GET /api/users\", clientIP: req.ip }, async () => {\n * const users = await db.query(\"SELECT * FROM users\");\n * captureException(new Error(\"oops\")); // Auto-linked to trace\n * return users;\n * });\n *\n * // Background task\n * withTraceContext({ isTask: true, endpoint: \"process-emails\" }, async () => {\n * await processEmails();\n * });\n * ```\n */\nexport function withTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T,\n): T {\n const context: TraceContext = {\n traceId: options.traceId ?? generateUUID(),\n isTask: options.isTask ?? false,\n startedAt: new Date(),\n spans: [],\n attributes: options.attributes ?? {},\n endpoint: options.endpoint,\n clientIP: options.clientIP,\n };\n return asyncLocalStorage.run(context, fn);\n}\n\n/**\n * Run a function within a trace context, automatically capturing the trace on completion.\n * This is a convenience wrapper that handles timing and capture automatically.\n *\n * @example\n * ```ts\n * // In Express middleware\n * app.use((req, res, next) => {\n * runWithTraceContext(\n * {\n * endpoint: `${req.method} ${req.path}`,\n * clientIP: req.ip,\n * attributes: { userId: req.user?.id },\n * },\n * async () => {\n * await next();\n * // Status code and body size set via setTraceResponseInfo()\n * },\n * { captureOnEnd: true }\n * );\n * });\n * ```\n */\nexport function runWithTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return withTraceContext(options, fn);\n}\n\n/**\n * Add a completed span to the current trace context.\n * No-op if not within a trace context.\n */\nexport function addSpanToContext(span: Span): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.spans.push(span);\n }\n}\n\n/**\n * Set an attribute on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttribute(key: string, value: string): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.attributes[key] = value;\n }\n}\n\n/**\n * Set multiple attributes on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttributes(attributes: Record<string, string>): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n Object.assign(ctx.attributes, attributes);\n }\n}\n\n/**\n * Set HTTP response info on the current trace context.\n * Used by framework adapters after the response is sent.\n */\nexport function setTraceResponseInfo(\n statusCode: number,\n bodySize?: number,\n): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.statusCode = statusCode;\n ctx.bodySize = bodySize;\n }\n}\n\n/**\n * Get all spans from the current trace context.\n * Returns empty array if not within a trace context.\n */\nexport function getTraceSpans(): Span[] {\n return asyncLocalStorage.getStore()?.spans ?? [];\n}\n\n/**\n * Get the duration in milliseconds since the trace started.\n * Returns 0 if not within a trace context.\n */\nexport function getTraceDuration(): number {\n const ctx = asyncLocalStorage.getStore();\n if (!ctx) return 0;\n return Date.now() - ctx.startedAt.getTime();\n}\n\n/**\n * Fork the current trace context for a sub-operation.\n * Useful for parallel operations that should have isolated spans.\n * Returns undefined if not within a trace context.\n */\nexport function forkTraceContext<T>(fn: () => T): T | undefined {\n const parentCtx = asyncLocalStorage.getStore();\n if (!parentCtx) return undefined;\n\n const forkedContext: TraceContext = {\n ...parentCtx,\n spans: [], // Forked context gets its own spans\n attributes: { ...parentCtx.attributes },\n };\n\n return asyncLocalStorage.run(forkedContext, () => {\n const result = fn();\n // Merge spans back to parent after completion\n parentCtx.spans.push(...forkedContext.spans);\n return result;\n });\n}\n\n// Export the AsyncLocalStorage instance for advanced use cases\nexport { asyncLocalStorage as traceContextStorage };\n"],"mappings":";AAAA;AAAA,EACE,gBAAAA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA;AAAA,OACK;;;ACLP,YAAY,UAAU;;;ACAf,IAAM,YAAN,MAAmB;AAAA,EAChB;AAAA,EACA,OAAe;AAAA,EACf;AAAA,EACA,OAAe;AAAA,EAEvB,YAAY,UAAkB;AAC5B,SAAK,YAAY;AACjB,SAAK,MAAM,IAAI,MAAgB,QAAQ,EAAE,KAAK,IAAI;AAAA,EACpD;AAAA,EAEA,IAAI,SAAiB;AACnB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,WAAmB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,KAAK,KAAc;AACjB,SAAK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D;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,UAAM,aAAa,KAAK,IAAI,IAAI;AAChC,QAAI,aAAa,IAAI,GAAG;AACtB,kBAAY,SAAS,OAAO,YAAY,SAAS;AACjD,UAAI,eAAe,OAAO;AACxB,uCAA+B,KAAK,QAAW,OAAO;AAAA,MACxD;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACF;AAEA,eAAsB,SAAS,WAAmC;AAChE,MAAI,CAAC,MAAO;AACZ,QAAM,IAAI;AACV,UAAQ;AACR,QAAM,EAAE,SAAS,SAAS;AAC5B;","names":["generateUUID","nowISO","os","hostname","nowISO","generateUUID"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tracewayapp/backend",
3
- "version": "0.3.0",
3
+ "version": "1.0.1",
4
4
  "description": "Traceway SDK for Node.js backends",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -23,6 +23,6 @@
23
23
  "dev": "tsup --watch"
24
24
  },
25
25
  "dependencies": {
26
- "@tracewayapp/core": "0.3.0"
26
+ "@tracewayapp/core": "1.0.1"
27
27
  }
28
28
  }