@dxos/tracing 0.8.4-main.dedc0f3 → 0.8.4-main.e250131250

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.
@@ -1,19 +1,19 @@
1
1
  // src/api.ts
2
- import { Context as Context2 } from "@dxos/context";
2
+ import { Context as Context3 } from "@dxos/context";
3
3
 
4
4
  // src/symbols.ts
5
- var symbolTracingContext = Symbol("dxos.tracing.context");
5
+ var symbolTracingContext = /* @__PURE__ */ Symbol("dxos.tracing.context");
6
6
  var getTracingContext = (target) => {
7
- var _target, _symbolTracingContext;
8
- return (_target = target)[_symbolTracingContext = symbolTracingContext] ?? (_target[_symbolTracingContext] = {
7
+ return target[symbolTracingContext] ??= {
9
8
  infoProperties: {},
10
9
  metricsProperties: {}
11
- });
10
+ };
12
11
  };
13
12
  var TRACE_SPAN_ATTRIBUTE = "dxos.trace-span";
14
13
 
15
14
  // src/trace-processor.ts
16
15
  import { unrefTimeout } from "@dxos/async";
16
+ import { Context as Context2 } from "@dxos/context";
17
17
  import { LogLevel, getContextFromEntry, log } from "@dxos/log";
18
18
  import { getPrototypeSpecificInstanceId } from "@dxos/util";
19
19
 
@@ -25,37 +25,27 @@ import { invariant } from "@dxos/invariant";
25
25
  var createId = () => Math.random().toString(36).slice(2);
26
26
 
27
27
  // src/diagnostic.ts
28
- function _define_property(obj, key, value) {
29
- if (key in obj) {
30
- Object.defineProperty(obj, key, {
31
- value,
32
- enumerable: true,
33
- configurable: true,
34
- writable: true
35
- });
36
- } else {
37
- obj[key] = value;
38
- }
39
- return obj;
40
- }
41
28
  var __dxlog_file = "/__w/dxos/dxos/packages/common/tracing/src/diagnostic.ts";
42
29
  var DIAGNOSTICS_TIMEOUT = 1e4;
43
30
  var TraceDiagnosticImpl = class {
44
- unregister() {
45
- this._onUnregister();
46
- }
31
+ id;
32
+ fetch;
33
+ name;
34
+ _onUnregister;
47
35
  constructor(id, fetch, name, _onUnregister) {
48
- _define_property(this, "id", void 0);
49
- _define_property(this, "fetch", void 0);
50
- _define_property(this, "name", void 0);
51
- _define_property(this, "_onUnregister", void 0);
52
36
  this.id = id;
53
37
  this.fetch = fetch;
54
38
  this.name = name;
55
39
  this._onUnregister = _onUnregister;
56
40
  }
41
+ unregister() {
42
+ this._onUnregister();
43
+ }
57
44
  };
58
45
  var DiagnosticsManager = class {
46
+ instanceId = createId();
47
+ registry = /* @__PURE__ */ new Map();
48
+ _instanceTag = null;
59
49
  get instanceTag() {
60
50
  return this._instanceTag;
61
51
  }
@@ -118,37 +108,34 @@ var DiagnosticsManager = class {
118
108
  };
119
109
  }
120
110
  }
121
- constructor() {
122
- _define_property(this, "instanceId", createId());
123
- _define_property(this, "registry", /* @__PURE__ */ new Map());
124
- _define_property(this, "_instanceTag", null);
125
- }
126
111
  };
127
112
 
128
113
  // src/diagnostics-channel.ts
129
114
  import { Trigger, sleep } from "@dxos/async";
130
115
  import { Context } from "@dxos/context";
131
116
  import { invariant as invariant2 } from "@dxos/invariant";
132
- function _define_property2(obj, key, value) {
133
- if (key in obj) {
134
- Object.defineProperty(obj, key, {
135
- value,
136
- enumerable: true,
137
- configurable: true,
138
- writable: true
139
- });
140
- } else {
141
- obj[key] = value;
142
- }
143
- return obj;
144
- }
145
117
  var __dxlog_file2 = "/__w/dxos/dxos/packages/common/tracing/src/diagnostics-channel.ts";
146
118
  var DEFAULT_CHANNEL_NAME = "dxos-diagnostics";
147
119
  var DISCOVER_TIME = 500;
148
120
  var DiagnosticsChannel = class _DiagnosticsChannel {
121
+ _channelName;
149
122
  static get supported() {
150
123
  return globalThis.BroadcastChannel != null;
151
124
  }
125
+ _ctx = new Context(void 0, {
126
+ F: __dxlog_file2,
127
+ L: 46
128
+ });
129
+ // Separate channels becauase the client and server may be in the same process.
130
+ _serveChannel = void 0;
131
+ _clientChannel = void 0;
132
+ constructor(_channelName = DEFAULT_CHANNEL_NAME) {
133
+ this._channelName = _channelName;
134
+ if (_DiagnosticsChannel.supported) {
135
+ this._serveChannel = new BroadcastChannel(_channelName);
136
+ this._clientChannel = new BroadcastChannel(_channelName);
137
+ }
138
+ }
152
139
  destroy() {
153
140
  void this._ctx.dispose();
154
141
  this._serveChannel?.close();
@@ -274,40 +261,11 @@ var DiagnosticsChannel = class _DiagnosticsChannel {
274
261
  this._clientChannel.removeEventListener("message", listener);
275
262
  }
276
263
  }
277
- constructor(_channelName = DEFAULT_CHANNEL_NAME) {
278
- _define_property2(this, "_channelName", void 0);
279
- _define_property2(this, "_ctx", void 0);
280
- _define_property2(this, "_serveChannel", void 0);
281
- _define_property2(this, "_clientChannel", void 0);
282
- this._channelName = _channelName;
283
- this._ctx = new Context(void 0, {
284
- F: __dxlog_file2,
285
- L: 46
286
- });
287
- this._serveChannel = void 0;
288
- this._clientChannel = void 0;
289
- if (_DiagnosticsChannel.supported) {
290
- this._serveChannel = new BroadcastChannel(_channelName);
291
- this._clientChannel = new BroadcastChannel(_channelName);
292
- }
293
- }
294
264
  };
295
265
 
296
266
  // src/remote/metrics.ts
297
- function _define_property3(obj, key, value) {
298
- if (key in obj) {
299
- Object.defineProperty(obj, key, {
300
- value,
301
- enumerable: true,
302
- configurable: true,
303
- writable: true
304
- });
305
- } else {
306
- obj[key] = value;
307
- }
308
- return obj;
309
- }
310
267
  var RemoteMetrics = class {
268
+ _metrics = /* @__PURE__ */ new Set();
311
269
  registerProcessor(processor) {
312
270
  this._metrics.add(processor);
313
271
  }
@@ -323,70 +281,146 @@ var RemoteMetrics = class {
323
281
  gauge(name, value, data) {
324
282
  return Array.from(this._metrics.values()).map((processor) => processor.gauge(name, value, data));
325
283
  }
326
- constructor() {
327
- _define_property3(this, "_metrics", /* @__PURE__ */ new Set());
328
- }
329
284
  };
330
285
 
331
286
  // src/remote/tracing.ts
332
- function _define_property4(obj, key, value) {
333
- if (key in obj) {
334
- Object.defineProperty(obj, key, {
335
- value,
336
- enumerable: true,
337
- configurable: true,
338
- writable: true
339
- });
340
- } else {
341
- obj[key] = value;
342
- }
343
- return obj;
344
- }
287
+ var MAX_ENDED_CONTEXTS = 1e4;
345
288
  var RemoteTracing = class {
289
+ _tracing;
290
+ _spanMap = /* @__PURE__ */ new Map();
291
+ _idToSpan = /* @__PURE__ */ new Map();
292
+ /**
293
+ * Retains OTEL span contexts after spans end so that periodic/background
294
+ * operations referencing a completed parent (via `this._ctx`) still produce
295
+ * correlated child spans instead of orphaned root traces.
296
+ */
297
+ _endedSpanContexts = /* @__PURE__ */ new Map();
298
+ /**
299
+ * Buffers flushSpan calls that arrive before a processor is registered,
300
+ * so early startup spans are not silently dropped.
301
+ */
302
+ _pendingFlushes = [];
346
303
  registerProcessor(processor) {
347
304
  this._tracing = processor;
305
+ const pending = this._pendingFlushes;
306
+ this._pendingFlushes = null;
307
+ if (pending) {
308
+ for (const { span: span2, isEnd } of pending) {
309
+ this._replayFlush(span2, isEnd);
310
+ }
311
+ }
312
+ }
313
+ /** Returns the opaque OTEL context for the given DXOS span ID, if one exists. */
314
+ getSpanContext(spanId) {
315
+ const tracingSpan = this._idToSpan.get(spanId);
316
+ if (tracingSpan) {
317
+ return this._spanMap.get(tracingSpan)?.spanContext;
318
+ }
319
+ return this._endedSpanContexts.get(spanId);
320
+ }
321
+ /** Wraps execution so that the remote span is active as parent context. */
322
+ wrapExecution(span2, fn) {
323
+ const remoteSpan = this._spanMap.get(span2);
324
+ if (remoteSpan?.wrapExecution) {
325
+ return remoteSpan.wrapExecution(fn);
326
+ }
327
+ return fn();
348
328
  }
349
329
  flushSpan(span2) {
330
+ if (!span2.showInRemoteTracing) {
331
+ return;
332
+ }
350
333
  if (!this._tracing) {
334
+ this._pendingFlushes?.push({
335
+ span: span2,
336
+ isEnd: !!span2.endTs
337
+ });
351
338
  return;
352
339
  }
353
340
  if (!span2.endTs) {
354
- const remoteSpan = this._tracing.startSpan({
355
- name: span2.methodName,
356
- op: span2.op ?? "function",
357
- attributes: span2.attributes
358
- });
359
- this._spanMap.set(span2, remoteSpan);
341
+ this._startRemoteSpan(span2);
360
342
  } else {
361
- const remoteSpan = this._spanMap.get(span2);
362
- if (remoteSpan) {
363
- remoteSpan.end();
364
- this._spanMap.delete(span2);
343
+ this._endRemoteSpan(span2);
344
+ }
345
+ }
346
+ _startRemoteSpan(span2) {
347
+ let parentContext;
348
+ if (span2.parentId != null) {
349
+ const parentTracingSpan = this._idToSpan.get(span2.parentId);
350
+ if (parentTracingSpan) {
351
+ parentContext = this._spanMap.get(parentTracingSpan)?.spanContext;
352
+ }
353
+ if (parentContext == null) {
354
+ parentContext = this._endedSpanContexts.get(span2.parentId);
365
355
  }
366
356
  }
357
+ const attributes = {};
358
+ if (span2.sanitizedClassName) {
359
+ attributes.entryPoint = span2.sanitizedClassName;
360
+ }
361
+ for (const [key, value] of Object.entries(span2.attributes)) {
362
+ attributes[key.startsWith("ctx.") ? key : `ctx.${key}`] = value;
363
+ }
364
+ const remoteSpan = this._tracing.startSpan({
365
+ name: span2.name,
366
+ op: span2.op ?? "function",
367
+ attributes,
368
+ parentContext
369
+ });
370
+ this._spanMap.set(span2, remoteSpan);
371
+ this._idToSpan.set(span2.id, span2);
372
+ }
373
+ _endRemoteSpan(span2) {
374
+ const remoteSpan = this._spanMap.get(span2);
375
+ if (remoteSpan) {
376
+ if (remoteSpan.spanContext != null) {
377
+ this._endedSpanContexts.set(span2.id, remoteSpan.spanContext);
378
+ this._evictEndedContexts();
379
+ }
380
+ remoteSpan.end();
381
+ this._spanMap.delete(span2);
382
+ this._idToSpan.delete(span2.id);
383
+ }
367
384
  }
368
- constructor() {
369
- _define_property4(this, "_tracing", void 0);
370
- _define_property4(this, "_spanMap", /* @__PURE__ */ new Map());
385
+ /**
386
+ * Replays a buffered flush that was queued before the processor was registered.
387
+ * For spans that started AND ended before registration, replays both events.
388
+ */
389
+ _replayFlush(span2, isEnd) {
390
+ if (!isEnd) {
391
+ this._startRemoteSpan(span2);
392
+ if (span2.endTs != null) {
393
+ this._endRemoteSpan(span2);
394
+ }
395
+ } else {
396
+ if (!this._spanMap.has(span2)) {
397
+ this._startRemoteSpan(span2);
398
+ }
399
+ this._endRemoteSpan(span2);
400
+ }
401
+ }
402
+ _evictEndedContexts() {
403
+ if (this._endedSpanContexts.size <= MAX_ENDED_CONTEXTS) {
404
+ return;
405
+ }
406
+ const iterator = this._endedSpanContexts.keys();
407
+ while (this._endedSpanContexts.size > MAX_ENDED_CONTEXTS) {
408
+ const oldest = iterator.next();
409
+ if (oldest.done) {
410
+ break;
411
+ }
412
+ this._endedSpanContexts.delete(oldest.value);
413
+ }
371
414
  }
372
415
  };
373
416
 
374
417
  // src/trace-sender.ts
375
418
  import { Stream } from "@dxos/codec-protobuf/stream";
376
- function _define_property5(obj, key, value) {
377
- if (key in obj) {
378
- Object.defineProperty(obj, key, {
379
- value,
380
- enumerable: true,
381
- configurable: true,
382
- writable: true
383
- });
384
- } else {
385
- obj[key] = value;
386
- }
387
- return obj;
388
- }
389
419
  var TraceSender = class {
420
+ _traceProcessor;
421
+ constructor(_traceProcessor) {
422
+ this._traceProcessor = _traceProcessor;
423
+ }
390
424
  streamTrace(request) {
391
425
  return new Stream(({ ctx, next }) => {
392
426
  const flushEvents = (resources, spans2, logs) => {
@@ -468,53 +502,40 @@ var TraceSender = class {
468
502
  flushEvents(null, null, null);
469
503
  });
470
504
  }
471
- constructor(_traceProcessor) {
472
- _define_property5(this, "_traceProcessor", void 0);
473
- this._traceProcessor = _traceProcessor;
474
- }
475
505
  };
476
506
 
477
507
  // src/weak-ref.ts
478
508
  var WeakRefMock = class {
479
- deref() {
480
- return void 0;
481
- }
482
509
  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
483
510
  constructor(target) {
484
511
  }
512
+ deref() {
513
+ return void 0;
514
+ }
485
515
  };
486
516
  var WeakRef = globalThis.WeakRef ?? WeakRefMock;
487
517
 
488
518
  // src/trace-processor.ts
489
- function _define_property6(obj, key, value) {
490
- if (key in obj) {
491
- Object.defineProperty(obj, key, {
492
- value,
493
- enumerable: true,
494
- configurable: true,
495
- writable: true
496
- });
497
- } else {
498
- obj[key] = value;
499
- }
500
- return obj;
501
- }
502
- var _globalThis;
503
519
  var __dxlog_file3 = "/__w/dxos/dxos/packages/common/tracing/src/trace-processor.ts";
504
520
  var ResourceEntry = class {
505
- getMetric(name) {
506
- return this.data.metrics?.find((metric) => metric.name === name);
507
- }
521
+ data;
522
+ instance;
523
+ annotation;
524
+ /**
525
+ * Sometimes bundlers mangle class names: WebFile -> WebFile2.
526
+ *
527
+ * We use a heuristic to remove the suffix.
528
+ */
529
+ sanitizedClassName;
508
530
  constructor(data, instance, annotation) {
509
- _define_property6(this, "data", void 0);
510
- _define_property6(this, "instance", void 0);
511
- _define_property6(this, "annotation", void 0);
512
- _define_property6(this, "sanitizedClassName", void 0);
513
531
  this.data = data;
514
532
  this.instance = instance;
515
533
  this.annotation = annotation;
516
534
  this.sanitizedClassName = sanitizeClassName(data.className);
517
535
  }
536
+ getMetric(name) {
537
+ return this.data.metrics?.find((metric) => metric.name === name);
538
+ }
518
539
  };
519
540
  var MAX_RESOURCE_RECORDS = 2e3;
520
541
  var MAX_SPAN_RECORDS = 1e3;
@@ -523,6 +544,34 @@ var REFRESH_INTERVAL = 1e3;
523
544
  var MAX_INFO_OBJECT_DEPTH = 8;
524
545
  var IS_CLOUDFLARE_WORKERS = !!globalThis?.navigator?.userAgent?.includes("Cloudflare-Workers");
525
546
  var TraceProcessor = class {
547
+ diagnostics = new DiagnosticsManager();
548
+ diagnosticsChannel = new DiagnosticsChannel();
549
+ remoteMetrics = new RemoteMetrics();
550
+ remoteTracing = new RemoteTracing();
551
+ subscriptions = /* @__PURE__ */ new Set();
552
+ resources = /* @__PURE__ */ new Map();
553
+ resourceInstanceIndex = /* @__PURE__ */ new WeakMap();
554
+ resourceIdList = [];
555
+ spans = /* @__PURE__ */ new Map();
556
+ spanIdList = [];
557
+ logs = [];
558
+ _instanceTag = null;
559
+ constructor() {
560
+ log.addProcessor(this._logProcessor.bind(this), void 0, {
561
+ F: __dxlog_file3,
562
+ L: 104,
563
+ S: this,
564
+ C: (f, a) => f(...a)
565
+ });
566
+ if (!IS_CLOUDFLARE_WORKERS) {
567
+ const refreshInterval = setInterval(this.refresh.bind(this), REFRESH_INTERVAL);
568
+ unrefTimeout(refreshInterval);
569
+ }
570
+ if (DiagnosticsChannel.supported) {
571
+ this.diagnosticsChannel.serve(this.diagnostics);
572
+ }
573
+ this.diagnosticsChannel.unref();
574
+ }
526
575
  setInstanceTag(tag) {
527
576
  this._instanceTag = tag;
528
577
  this.diagnostics.setInstanceTag(tag);
@@ -634,10 +683,10 @@ var TraceProcessor = class {
634
683
  let _changed = false;
635
684
  const oldInfo = resource2.data.info;
636
685
  resource2.data.info = this.getResourceInfo(instance);
637
- _changed || (_changed = !areEqualShallow(oldInfo, resource2.data.info));
686
+ _changed ||= !areEqualShallow(oldInfo, resource2.data.info);
638
687
  const oldMetrics = resource2.data.metrics;
639
688
  resource2.data.metrics = this.getResourceMetrics(instance);
640
- _changed || (_changed = !areEqualShallow(oldMetrics, resource2.data.metrics));
689
+ _changed ||= !areEqualShallow(oldMetrics, resource2.data.metrics);
641
690
  this._markResourceDirty(resource2.data.id);
642
691
  }
643
692
  for (const subscription of this.subscriptions) {
@@ -691,74 +740,94 @@ var TraceProcessor = class {
691
740
  subscription.newLogs.push(log2);
692
741
  }
693
742
  }
694
- constructor() {
695
- _define_property6(this, "diagnostics", new DiagnosticsManager());
696
- _define_property6(this, "diagnosticsChannel", new DiagnosticsChannel());
697
- _define_property6(this, "remoteMetrics", new RemoteMetrics());
698
- _define_property6(this, "remoteTracing", new RemoteTracing());
699
- _define_property6(this, "subscriptions", /* @__PURE__ */ new Set());
700
- _define_property6(this, "resources", /* @__PURE__ */ new Map());
701
- _define_property6(this, "resourceInstanceIndex", /* @__PURE__ */ new WeakMap());
702
- _define_property6(this, "resourceIdList", []);
703
- _define_property6(this, "spans", /* @__PURE__ */ new Map());
704
- _define_property6(this, "spanIdList", []);
705
- _define_property6(this, "logs", []);
706
- _define_property6(this, "_instanceTag", null);
707
- _define_property6(this, "_logProcessor", (config, entry) => {
708
- switch (entry.level) {
709
- case LogLevel.ERROR:
710
- case LogLevel.WARN:
711
- case LogLevel.TRACE: {
712
- const scope = entry.meta?.S;
713
- const resource2 = this.resourceInstanceIndex.get(scope);
714
- if (!resource2) {
715
- return;
716
- }
717
- const context = getContextFromEntry(entry) ?? {};
718
- for (const key of Object.keys(context)) {
719
- context[key] = sanitizeValue(context[key], 0, this);
720
- }
721
- const entryToPush = {
722
- level: entry.level,
723
- message: entry.message ?? (entry.error ? entry.error.message ?? String(entry.error) : ""),
724
- context,
725
- timestamp: /* @__PURE__ */ new Date(),
726
- meta: {
727
- file: entry.meta?.F ?? "",
728
- line: entry.meta?.L ?? 0,
729
- resourceId: resource2.data.id
730
- }
731
- };
732
- this._pushLog(entryToPush);
733
- break;
743
+ _logProcessor = (config, entry) => {
744
+ switch (entry.level) {
745
+ case LogLevel.ERROR:
746
+ case LogLevel.WARN:
747
+ case LogLevel.TRACE: {
748
+ const scope = entry.meta?.S;
749
+ const resource2 = this.resourceInstanceIndex.get(scope);
750
+ if (!resource2) {
751
+ return;
752
+ }
753
+ const context = getContextFromEntry(entry) ?? {};
754
+ for (const key of Object.keys(context)) {
755
+ context[key] = sanitizeValue(context[key], 0, this);
734
756
  }
735
- default:
757
+ const entryToPush = {
758
+ level: entry.level,
759
+ message: entry.message ?? (entry.error ? entry.error.message ?? String(entry.error) : ""),
760
+ context,
761
+ timestamp: /* @__PURE__ */ new Date(),
762
+ meta: {
763
+ file: entry.meta?.F ?? "",
764
+ line: entry.meta?.L ?? 0,
765
+ resourceId: resource2.data.id
766
+ }
767
+ };
768
+ this._pushLog(entryToPush);
769
+ break;
736
770
  }
737
- });
738
- log.addProcessor(this._logProcessor.bind(this), void 0, {
771
+ default:
772
+ }
773
+ };
774
+ };
775
+ var TracingSpan = class _TracingSpan {
776
+ _traceProcessor;
777
+ static nextId = 0;
778
+ id;
779
+ parentId = null;
780
+ methodName;
781
+ resourceId = null;
782
+ op;
783
+ attributes;
784
+ startTs;
785
+ endTs = null;
786
+ error = null;
787
+ _showInBrowserTimeline;
788
+ _showInRemoteTracing;
789
+ _ctx;
790
+ constructor(_traceProcessor, params) {
791
+ this._traceProcessor = _traceProcessor;
792
+ this.id = _TracingSpan.nextId++;
793
+ this.methodName = params.methodName;
794
+ this.resourceId = _traceProcessor.getResourceId(params.instance);
795
+ this.startTs = performance.now();
796
+ this._showInBrowserTimeline = params.showInBrowserTimeline;
797
+ this._showInRemoteTracing = params.showInRemoteTracing ?? true;
798
+ this.op = params.op;
799
+ this.attributes = params.attributes ?? {};
800
+ const baseCtx = params.parentCtx ?? new Context2(void 0, {
739
801
  F: __dxlog_file3,
740
- L: 103,
741
- S: this,
742
- C: (f, a) => f(...a)
802
+ L: 397
743
803
  });
744
- if (!IS_CLOUDFLARE_WORKERS) {
745
- const refreshInterval = setInterval(this.refresh.bind(this), REFRESH_INTERVAL);
746
- unrefTimeout(refreshInterval);
747
- }
748
- if (DiagnosticsChannel.supported) {
749
- this.diagnosticsChannel.serve(this.diagnostics);
804
+ this._ctx = this._showInRemoteTracing ? baseCtx.derive({
805
+ attributes: {
806
+ [TRACE_SPAN_ATTRIBUTE]: this.id
807
+ }
808
+ }) : baseCtx.derive();
809
+ if (params.parentCtx) {
810
+ const parentId = params.parentCtx.getAttribute(TRACE_SPAN_ATTRIBUTE);
811
+ if (typeof parentId === "number") {
812
+ this.parentId = parentId;
813
+ }
750
814
  }
751
- this.diagnosticsChannel.unref();
752
815
  }
753
- };
754
- var TracingSpan = class _TracingSpan {
755
816
  get name() {
756
817
  const resource2 = this._traceProcessor.resources.get(this.resourceId);
757
818
  return resource2 ? `${resource2.sanitizedClassName}#${resource2.data.instanceId}.${this.methodName}` : this.methodName;
758
819
  }
820
+ /** Sanitized class name of the owning resource, if available. */
821
+ get sanitizedClassName() {
822
+ const resource2 = this.resourceId != null ? this._traceProcessor.resources.get(this.resourceId) : void 0;
823
+ return resource2?.sanitizedClassName;
824
+ }
759
825
  get ctx() {
760
826
  return this._ctx;
761
827
  }
828
+ get showInRemoteTracing() {
829
+ return this._showInRemoteTracing;
830
+ }
762
831
  markSuccess() {
763
832
  this.endTs = performance.now();
764
833
  this._traceProcessor._flushSpan(this);
@@ -793,46 +862,7 @@ var TracingSpan = class _TracingSpan {
793
862
  });
794
863
  }
795
864
  }
796
- constructor(_traceProcessor, params) {
797
- _define_property6(this, "_traceProcessor", void 0);
798
- _define_property6(this, "id", void 0);
799
- _define_property6(this, "parentId", void 0);
800
- _define_property6(this, "methodName", void 0);
801
- _define_property6(this, "resourceId", void 0);
802
- _define_property6(this, "op", void 0);
803
- _define_property6(this, "attributes", void 0);
804
- _define_property6(this, "startTs", void 0);
805
- _define_property6(this, "endTs", void 0);
806
- _define_property6(this, "error", void 0);
807
- _define_property6(this, "_showInBrowserTimeline", void 0);
808
- _define_property6(this, "_ctx", void 0);
809
- this._traceProcessor = _traceProcessor;
810
- this.parentId = null;
811
- this.resourceId = null;
812
- this.endTs = null;
813
- this.error = null;
814
- this._ctx = null;
815
- this.id = _TracingSpan.nextId++;
816
- this.methodName = params.methodName;
817
- this.resourceId = _traceProcessor.getResourceId(params.instance);
818
- this.startTs = performance.now();
819
- this._showInBrowserTimeline = params.showInBrowserTimeline;
820
- this.op = params.op;
821
- this.attributes = params.attributes ?? {};
822
- if (params.parentCtx) {
823
- this._ctx = params.parentCtx.derive({
824
- attributes: {
825
- [TRACE_SPAN_ATTRIBUTE]: this.id
826
- }
827
- });
828
- const parentId = params.parentCtx.getAttribute(TRACE_SPAN_ATTRIBUTE);
829
- if (typeof parentId === "number") {
830
- this.parentId = parentId;
831
- }
832
- }
833
- }
834
865
  };
835
- _define_property6(TracingSpan, "nextId", 0);
836
866
  var serializeError = (err) => {
837
867
  if (err instanceof Error) {
838
868
  return {
@@ -844,7 +874,7 @@ var serializeError = (err) => {
844
874
  message: String(err)
845
875
  };
846
876
  };
847
- var TRACE_PROCESSOR = (_globalThis = globalThis).TRACE_PROCESSOR ?? (_globalThis.TRACE_PROCESSOR = new TraceProcessor());
877
+ var TRACE_PROCESSOR = globalThis.TRACE_PROCESSOR ??= new TraceProcessor();
848
878
  var sanitizeValue = (value, depth, traceProcessor) => {
849
879
  switch (typeof value) {
850
880
  case "string":
@@ -904,31 +934,28 @@ var areEqualShallow = (a, b) => {
904
934
  return true;
905
935
  };
906
936
  var sanitizeClassName = (className) => {
937
+ let name = className.replace(/^_+/, "");
907
938
  const SANITIZE_REGEX = /[^_](\d+)$/;
908
- const m = className.match(SANITIZE_REGEX);
909
- if (!m) {
910
- return className;
911
- } else {
912
- return className.slice(0, -m[1].length);
939
+ const m = name.match(SANITIZE_REGEX);
940
+ if (m) {
941
+ name = name.slice(0, -m[1].length);
913
942
  }
943
+ return name;
914
944
  };
915
945
  var isSetLike = (value) => value instanceof Set || typeof value === "object" && value !== null && Object.getPrototypeOf(value).constructor.name === "ComplexSet";
916
946
  var isMapLike = (value) => value instanceof Map || typeof value === "object" && value !== null && Object.getPrototypeOf(value).constructor.name === "ComplexMap";
917
947
 
918
948
  // src/api.ts
919
949
  var resource = (options) => (constructor) => {
920
- const klass = /* @__PURE__ */ (() => {
921
- class _class extends constructor {
922
- constructor(...rest) {
923
- super(...rest);
924
- TRACE_PROCESSOR.createTraceResource({
925
- constructor,
926
- annotation: options?.annotation,
927
- instance: this
928
- });
929
- }
950
+ const klass = /* @__PURE__ */ (() => class extends constructor {
951
+ constructor(...rest) {
952
+ super(...rest);
953
+ TRACE_PROCESSOR.createTraceResource({
954
+ constructor,
955
+ annotation: options?.annotation,
956
+ instance: this
957
+ });
930
958
  }
931
- return _class;
932
959
  })();
933
960
  Object.defineProperty(klass, "name", {
934
961
  value: constructor.name
@@ -943,30 +970,33 @@ var info = (opts = {}) => (target, propertyKey, descriptor) => {
943
970
  var mark = (name) => {
944
971
  performance.mark(name);
945
972
  };
946
- var span = ({ showInBrowserTimeline = false, op, attributes } = {}) => (target, propertyKey, descriptor) => {
973
+ var span = ({ showInBrowserTimeline = false, showInRemoteTracing = true, op, attributes } = {}) => (target, propertyKey, descriptor) => {
947
974
  const method = descriptor.value;
948
975
  descriptor.value = async function(...args) {
949
- const parentCtx = args[0] instanceof Context2 ? args[0] : null;
976
+ const explicitCtx = args[0] instanceof Context3 ? args[0] : null;
950
977
  const span2 = TRACE_PROCESSOR.traceSpan({
951
- parentCtx,
978
+ parentCtx: explicitCtx,
952
979
  methodName: propertyKey,
953
980
  instance: this,
954
981
  showInBrowserTimeline,
982
+ showInRemoteTracing,
955
983
  op,
956
984
  attributes
957
985
  });
958
- const callArgs = span2.ctx ? [
986
+ const callArgs = explicitCtx ? [
959
987
  span2.ctx,
960
988
  ...args.slice(1)
961
989
  ] : args;
962
- try {
963
- return await method.apply(this, callArgs);
964
- } catch (err) {
965
- span2.markError(err);
966
- throw err;
967
- } finally {
968
- span2.markSuccess();
969
- }
990
+ return TRACE_PROCESSOR.remoteTracing.wrapExecution(span2, async () => {
991
+ try {
992
+ return await method.apply(this, callArgs);
993
+ } catch (err) {
994
+ span2.markError(err);
995
+ throw err;
996
+ } finally {
997
+ span2.markSuccess();
998
+ }
999
+ });
970
1000
  };
971
1001
  };
972
1002
  var spans = /* @__PURE__ */ new Map();
@@ -1007,20 +1037,12 @@ var trace = {
1007
1037
  };
1008
1038
 
1009
1039
  // src/metrics/base.ts
1010
- function _define_property7(obj, key, value) {
1011
- if (key in obj) {
1012
- Object.defineProperty(obj, key, {
1013
- value,
1014
- enumerable: true,
1015
- configurable: true,
1016
- writable: true
1017
- });
1018
- } else {
1019
- obj[key] = value;
1020
- }
1021
- return obj;
1022
- }
1023
1040
  var BaseCounter = class {
1041
+ /**
1042
+ * @internal
1043
+ */
1044
+ _instance;
1045
+ name;
1024
1046
  /**
1025
1047
  * @internal
1026
1048
  */
@@ -1030,27 +1052,16 @@ var BaseCounter = class {
1030
1052
  }
1031
1053
  _tick(time) {
1032
1054
  }
1033
- constructor() {
1034
- _define_property7(this, "_instance", void 0);
1035
- _define_property7(this, "name", void 0);
1036
- }
1037
1055
  };
1038
1056
 
1039
1057
  // src/metrics/unary-counter.ts
1040
- function _define_property8(obj, key, value) {
1041
- if (key in obj) {
1042
- Object.defineProperty(obj, key, {
1043
- value,
1044
- enumerable: true,
1045
- configurable: true,
1046
- writable: true
1047
- });
1048
- } else {
1049
- obj[key] = value;
1050
- }
1051
- return obj;
1052
- }
1053
1058
  var UnaryCounter = class extends BaseCounter {
1059
+ value = 0;
1060
+ units;
1061
+ constructor({ units } = {}) {
1062
+ super();
1063
+ this.units = units;
1064
+ }
1054
1065
  inc(by = 1) {
1055
1066
  this.value += by;
1056
1067
  }
@@ -1063,28 +1074,19 @@ var UnaryCounter = class extends BaseCounter {
1063
1074
  }
1064
1075
  };
1065
1076
  }
1066
- constructor({ units } = {}) {
1067
- super(), _define_property8(this, "value", 0), _define_property8(this, "units", void 0);
1068
- this.units = units;
1069
- }
1070
1077
  };
1071
1078
 
1072
1079
  // src/metrics/time-series-counter.ts
1073
- function _define_property9(obj, key, value) {
1074
- if (key in obj) {
1075
- Object.defineProperty(obj, key, {
1076
- value,
1077
- enumerable: true,
1078
- configurable: true,
1079
- writable: true
1080
- });
1081
- } else {
1082
- obj[key] = value;
1083
- }
1084
- return obj;
1085
- }
1086
1080
  var MAX_BUCKETS = 60;
1087
1081
  var TimeSeriesCounter = class extends BaseCounter {
1082
+ _currentValue = 0;
1083
+ _totalValue = 0;
1084
+ _buckets = [];
1085
+ units;
1086
+ constructor({ units } = {}) {
1087
+ super();
1088
+ this.units = units;
1089
+ }
1088
1090
  inc(by = 1) {
1089
1091
  this._currentValue += by;
1090
1092
  this._totalValue += by;
@@ -1113,28 +1115,15 @@ var TimeSeriesCounter = class extends BaseCounter {
1113
1115
  }
1114
1116
  };
1115
1117
  }
1116
- constructor({ units } = {}) {
1117
- super(), _define_property9(this, "_currentValue", 0), _define_property9(this, "_totalValue", 0), _define_property9(this, "_buckets", []), _define_property9(this, "units", void 0);
1118
- this.units = units;
1119
- }
1120
1118
  };
1121
1119
 
1122
1120
  // src/metrics/time-usage-counter.ts
1123
- function _define_property10(obj, key, value) {
1124
- if (key in obj) {
1125
- Object.defineProperty(obj, key, {
1126
- value,
1127
- enumerable: true,
1128
- configurable: true,
1129
- writable: true
1130
- });
1131
- } else {
1132
- obj[key] = value;
1133
- }
1134
- return obj;
1135
- }
1136
1121
  var MAX_BUCKETS2 = 60;
1137
1122
  var TimeUsageCounter = class extends BaseCounter {
1123
+ _currentValue = 0;
1124
+ _totalValue = 0;
1125
+ _buckets = [];
1126
+ _lastTickTime = performance.now();
1138
1127
  record(time) {
1139
1128
  this._currentValue += time;
1140
1129
  this._totalValue += time;
@@ -1175,26 +1164,16 @@ var TimeUsageCounter = class extends BaseCounter {
1175
1164
  }
1176
1165
  };
1177
1166
  }
1178
- constructor(...args) {
1179
- super(...args), _define_property10(this, "_currentValue", 0), _define_property10(this, "_totalValue", 0), _define_property10(this, "_buckets", []), _define_property10(this, "_lastTickTime", performance.now());
1180
- }
1181
1167
  };
1182
1168
 
1183
1169
  // src/metrics/map-counter.ts
1184
- function _define_property11(obj, key, value) {
1185
- if (key in obj) {
1186
- Object.defineProperty(obj, key, {
1187
- value,
1188
- enumerable: true,
1189
- configurable: true,
1190
- writable: true
1191
- });
1192
- } else {
1193
- obj[key] = value;
1194
- }
1195
- return obj;
1196
- }
1197
1170
  var MapCounter = class extends BaseCounter {
1171
+ values = /* @__PURE__ */ new Map();
1172
+ units;
1173
+ constructor({ units } = {}) {
1174
+ super();
1175
+ this.units = units;
1176
+ }
1198
1177
  inc(key, by = 1) {
1199
1178
  const prev = this.values.get(key) ?? 0;
1200
1179
  this.values.set(key, prev + by);
@@ -1211,27 +1190,14 @@ var MapCounter = class extends BaseCounter {
1211
1190
  }
1212
1191
  };
1213
1192
  }
1214
- constructor({ units } = {}) {
1215
- super(), _define_property11(this, "values", /* @__PURE__ */ new Map()), _define_property11(this, "units", void 0);
1216
- this.units = units;
1217
- }
1218
1193
  };
1219
1194
 
1220
1195
  // src/metrics/custom-counter.ts
1221
- function _define_property12(obj, key, value) {
1222
- if (key in obj) {
1223
- Object.defineProperty(obj, key, {
1224
- value,
1225
- enumerable: true,
1226
- configurable: true,
1227
- writable: true
1228
- });
1229
- } else {
1230
- obj[key] = value;
1231
- }
1232
- return obj;
1233
- }
1234
1196
  var CustomCounter = class extends BaseCounter {
1197
+ _getData;
1198
+ constructor(_getData) {
1199
+ super(), this._getData = _getData;
1200
+ }
1235
1201
  getData() {
1236
1202
  return {
1237
1203
  name: this.name,
@@ -1240,9 +1206,6 @@ var CustomCounter = class extends BaseCounter {
1240
1206
  }
1241
1207
  };
1242
1208
  }
1243
- constructor(_getData) {
1244
- super(), _define_property12(this, "_getData", void 0), this._getData = _getData;
1245
- }
1246
1209
  };
1247
1210
 
1248
1211
  // src/index.ts