@respan/tracing 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +860 -0
  3. package/dist/constants/index.d.ts +8 -0
  4. package/dist/constants/index.js +9 -0
  5. package/dist/constants/index.js.map +1 -0
  6. package/dist/contexts/index.d.ts +1 -0
  7. package/dist/contexts/index.js +2 -0
  8. package/dist/contexts/index.js.map +1 -0
  9. package/dist/contexts/span.d.ts +9 -0
  10. package/dist/contexts/span.js +39 -0
  11. package/dist/contexts/span.js.map +1 -0
  12. package/dist/decorators/base.d.ts +32 -0
  13. package/dist/decorators/base.js +242 -0
  14. package/dist/decorators/base.js.map +1 -0
  15. package/dist/decorators/index.d.ts +1 -0
  16. package/dist/decorators/index.js +2 -0
  17. package/dist/decorators/index.js.map +1 -0
  18. package/dist/index.d.ts +10 -0
  19. package/dist/index.js +8 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/instrumentation/index.d.ts +2 -0
  22. package/dist/instrumentation/index.js +3 -0
  23. package/dist/instrumentation/index.js.map +1 -0
  24. package/dist/instrumentation/loader.d.ts +5 -0
  25. package/dist/instrumentation/loader.js +104 -0
  26. package/dist/instrumentation/loader.js.map +1 -0
  27. package/dist/instrumentation/manager.d.ts +29 -0
  28. package/dist/instrumentation/manager.js +564 -0
  29. package/dist/instrumentation/manager.js.map +1 -0
  30. package/dist/main.d.ts +162 -0
  31. package/dist/main.js +212 -0
  32. package/dist/main.js.map +1 -0
  33. package/dist/processor/composite.d.ts +29 -0
  34. package/dist/processor/composite.js +106 -0
  35. package/dist/processor/composite.js.map +1 -0
  36. package/dist/processor/filtering.d.ts +19 -0
  37. package/dist/processor/filtering.js +78 -0
  38. package/dist/processor/filtering.js.map +1 -0
  39. package/dist/processor/index.d.ts +3 -0
  40. package/dist/processor/index.js +4 -0
  41. package/dist/processor/index.js.map +1 -0
  42. package/dist/processor/manager.d.ts +61 -0
  43. package/dist/processor/manager.js +111 -0
  44. package/dist/processor/manager.js.map +1 -0
  45. package/dist/types/clientTypes.d.ts +188 -0
  46. package/dist/types/clientTypes.js +22 -0
  47. package/dist/types/clientTypes.js.map +1 -0
  48. package/dist/types/decoratorTypes.d.ts +6 -0
  49. package/dist/types/decoratorTypes.js +2 -0
  50. package/dist/types/decoratorTypes.js.map +1 -0
  51. package/dist/types/index.d.ts +3 -0
  52. package/dist/types/index.js +4 -0
  53. package/dist/types/index.js.map +1 -0
  54. package/dist/types/instrumentationTypes.d.ts +25 -0
  55. package/dist/types/instrumentationTypes.js +82 -0
  56. package/dist/types/instrumentationTypes.js.map +1 -0
  57. package/dist/utils/client.d.ts +168 -0
  58. package/dist/utils/client.js +151 -0
  59. package/dist/utils/client.js.map +1 -0
  60. package/dist/utils/context.d.ts +28 -0
  61. package/dist/utils/context.js +44 -0
  62. package/dist/utils/context.js.map +1 -0
  63. package/dist/utils/index.d.ts +5 -0
  64. package/dist/utils/index.js +8 -0
  65. package/dist/utils/index.js.map +1 -0
  66. package/dist/utils/span.d.ts +65 -0
  67. package/dist/utils/span.js +269 -0
  68. package/dist/utils/span.js.map +1 -0
  69. package/dist/utils/spanBuffer.d.ts +94 -0
  70. package/dist/utils/spanBuffer.js +147 -0
  71. package/dist/utils/spanBuffer.js.map +1 -0
  72. package/dist/utils/tracing.d.ts +31 -0
  73. package/dist/utils/tracing.js +239 -0
  74. package/dist/utils/tracing.js.map +1 -0
  75. package/package.json +72 -0
@@ -0,0 +1,269 @@
1
+ import { trace, SpanStatusCode } from "@opentelemetry/api";
2
+ import { RESPAN_PACKAGE_NAME } from "../constants/index.js";
3
+ import { RespanParamsSchema, RespanSpanAttributes, RESPAN_SPAN_ATTRIBUTES_MAP, } from "@respan/respan-sdk";
4
+ // Global tracer instance (singleton)
5
+ let _tracer;
6
+ /**
7
+ * Gets the singleton tracer instance.
8
+ * The tracer is responsible for creating and managing spans.
9
+ *
10
+ * @returns The global tracer instance
11
+ */
12
+ export const getTracer = () => {
13
+ if (!_tracer) {
14
+ // Create tracer with a unique name for this SDK
15
+ _tracer = trace.getTracer(RESPAN_PACKAGE_NAME);
16
+ }
17
+ return _tracer;
18
+ };
19
+ /**
20
+ * Gets the currently active span from the context.
21
+ * This is the span that's currently being executed.
22
+ *
23
+ * @returns The active span or undefined if no span is active
24
+ */
25
+ export const getCurrentSpan = () => {
26
+ return trace.getActiveSpan();
27
+ };
28
+ /**
29
+ * Update the current active span with new information.
30
+ * This is the JavaScript equivalent of the Python update_current_span method.
31
+ *
32
+ * @param options - Configuration object for updating the span
33
+ * @returns True if the span was updated successfully, False otherwise
34
+ */
35
+ export const updateCurrentSpan = (options = {}) => {
36
+ const currentSpan = getCurrentSpan();
37
+ if (!currentSpan) {
38
+ console.debug("[Respan Debug] No active span found. Cannot update span.");
39
+ return false;
40
+ }
41
+ try {
42
+ const { respanParams, attributes, status, statusDescription, name } = options;
43
+ console.debug("[Respan Debug] Updating current span with:", {
44
+ hasRespanParams: !!respanParams,
45
+ respanParamsKeys: respanParams
46
+ ? Object.keys(respanParams)
47
+ : [],
48
+ hasAttributes: !!attributes,
49
+ attributesKeys: attributes ? Object.keys(attributes) : [],
50
+ hasStatus: status !== undefined,
51
+ status,
52
+ statusDescription,
53
+ newName: name,
54
+ });
55
+ // Update span name if provided
56
+ if (name) {
57
+ currentSpan.updateName(name);
58
+ console.debug(`[Respan Debug] Updated span name to: ${name}`);
59
+ }
60
+ // Set Respan-specific attributes
61
+ if (respanParams) {
62
+ setRespanAttributes(currentSpan, respanParams);
63
+ }
64
+ // Set generic attributes
65
+ if (attributes) {
66
+ Object.entries(attributes).forEach(([key, value]) => {
67
+ try {
68
+ currentSpan.setAttribute(key, value);
69
+ console.debug(`[Respan Debug] Set attribute: ${key}=${value}`);
70
+ }
71
+ catch (error) {
72
+ console.warn(`[Respan Debug] Failed to set attribute ${key}=${value}:`, error);
73
+ }
74
+ });
75
+ }
76
+ // Set status
77
+ if (status !== undefined) {
78
+ currentSpan.setStatus({
79
+ code: status,
80
+ message: statusDescription,
81
+ });
82
+ console.debug(`[Respan Debug] Set span status: ${status}${statusDescription ? ` (${statusDescription})` : ""}`);
83
+ }
84
+ return true;
85
+ }
86
+ catch (error) {
87
+ console.error("[Respan Debug] Failed to update span:", error);
88
+ return false;
89
+ }
90
+ };
91
+ /**
92
+ * Set Respan-specific attributes on a span.
93
+ * This is the JavaScript equivalent of the Python _set_respan_attributes method.
94
+ * Uses the imported RESPAN_SPAN_ATTRIBUTES_MAP and validates with RespanParamsSchema.
95
+ *
96
+ * @param span - The span to set attributes on
97
+ * @param respanParams - Respan parameters to set as span attributes
98
+ */
99
+ const setRespanAttributes = (span, respanParams) => {
100
+ try {
101
+ console.debug("[Respan Debug] Setting Respan attributes:", respanParams);
102
+ // Validate parameters using the imported schema
103
+ let validatedParams;
104
+ try {
105
+ validatedParams = RespanParamsSchema.parse(respanParams);
106
+ console.debug("[Respan Debug] Parameters validated successfully");
107
+ }
108
+ catch (validationError) {
109
+ console.warn("[Respan Debug] Failed to validate Respan params:", validationError);
110
+ // Use original params if validation fails, but continue processing
111
+ validatedParams = respanParams;
112
+ }
113
+ // Set attributes based on the imported mapping
114
+ Object.entries(validatedParams).forEach(([key, value]) => {
115
+ if (key in RESPAN_SPAN_ATTRIBUTES_MAP && key !== "metadata") {
116
+ try {
117
+ const attributeKey = RESPAN_SPAN_ATTRIBUTES_MAP[key];
118
+ span.setAttribute(attributeKey, value);
119
+ console.debug(`[Respan Debug] Set Respan attribute: ${attributeKey}=${value}`);
120
+ }
121
+ catch (error) {
122
+ console.warn(`[Respan Debug] Failed to set span attribute ${RESPAN_SPAN_ATTRIBUTES_MAP[key]}=${value}:`, error);
123
+ }
124
+ }
125
+ // Handle metadata specially using the proper enum
126
+ if (key === "metadata" && typeof value === "object" && value !== null) {
127
+ console.debug("[Respan Debug] Setting metadata attributes:", value);
128
+ Object.entries(value).forEach(([metadataKey, metadataValue]) => {
129
+ try {
130
+ const fullKey = `${RespanSpanAttributes.RESPAN_METADATA}.${metadataKey}`;
131
+ span.setAttribute(fullKey, metadataValue);
132
+ console.debug(`[Respan Debug] Set metadata attribute: ${fullKey}=${metadataValue}`);
133
+ }
134
+ catch (error) {
135
+ console.warn(`[Respan Debug] Failed to set metadata attribute ${metadataKey}=${metadataValue}:`, error);
136
+ }
137
+ });
138
+ }
139
+ });
140
+ }
141
+ catch (error) {
142
+ console.error("[Respan Debug] Unexpected error setting Respan attributes:", error);
143
+ }
144
+ };
145
+ /**
146
+ * Adds an event to the currently active span.
147
+ * Events are timestamped messages that provide additional context.
148
+ *
149
+ * @param name - Name of the event
150
+ * @param attributes - Optional attributes for the event
151
+ * @returns true if event was added, false if no active span
152
+ */
153
+ export const addSpanEvent = (name, attributes) => {
154
+ const currentSpan = getCurrentSpan();
155
+ if (!currentSpan) {
156
+ console.warn("No active span to add event to");
157
+ return false;
158
+ }
159
+ try {
160
+ currentSpan.addEvent(name, attributes);
161
+ return true;
162
+ }
163
+ catch (error) {
164
+ console.error("Error adding span event:", error);
165
+ return false;
166
+ }
167
+ };
168
+ /**
169
+ * Records an exception in the currently active span.
170
+ * This is useful for capturing errors that don't necessarily end the span.
171
+ *
172
+ * @param exception - The error/exception to record
173
+ * @returns true if exception was recorded, false if no active span
174
+ */
175
+ export const recordSpanException = (exception) => {
176
+ const currentSpan = getCurrentSpan();
177
+ if (!currentSpan) {
178
+ console.warn("No active span to record exception in");
179
+ return false;
180
+ }
181
+ try {
182
+ currentSpan.recordException(exception);
183
+ return true;
184
+ }
185
+ catch (error) {
186
+ console.error("Error recording span exception:", error);
187
+ return false;
188
+ }
189
+ };
190
+ /**
191
+ * Sets the status of the currently active span.
192
+ * This indicates whether the operation succeeded or failed.
193
+ *
194
+ * @param status - The status to set (OK or ERROR)
195
+ * @param message - Optional message describing the status
196
+ * @returns true if status was set, false if no active span
197
+ */
198
+ export const setSpanStatus = (status, message) => {
199
+ const currentSpan = getCurrentSpan();
200
+ if (!currentSpan) {
201
+ console.warn("No active span to set status on");
202
+ return false;
203
+ }
204
+ try {
205
+ currentSpan.setStatus({
206
+ code: status === "OK" ? SpanStatusCode.OK : SpanStatusCode.ERROR,
207
+ message,
208
+ });
209
+ return true;
210
+ }
211
+ catch (error) {
212
+ console.error("Error setting span status:", error);
213
+ return false;
214
+ }
215
+ };
216
+ /**
217
+ * Creates a manual span for custom tracing.
218
+ * This is useful when you need to trace operations that aren't wrapped by withEntity.
219
+ *
220
+ * @param name - Name of the span
221
+ * @param fn - Function to execute within the span
222
+ * @param attributes - Optional attributes for the span
223
+ * @returns The result of the function
224
+ */
225
+ export const withManualSpan = (name, fn, attributes) => {
226
+ return getTracer().startActiveSpan(name, {}, (span) => {
227
+ try {
228
+ // Add attributes if provided
229
+ if (attributes) {
230
+ Object.entries(attributes).forEach(([key, value]) => {
231
+ span.setAttribute(key, value);
232
+ });
233
+ }
234
+ const result = fn(span);
235
+ // Handle promises
236
+ if (result instanceof Promise) {
237
+ return result
238
+ .then((res) => {
239
+ span.setStatus({ code: SpanStatusCode.OK });
240
+ span.end();
241
+ return res;
242
+ })
243
+ .catch((error) => {
244
+ span.recordException(error);
245
+ span.setStatus({
246
+ code: SpanStatusCode.ERROR,
247
+ message: error.message,
248
+ });
249
+ span.end();
250
+ throw error;
251
+ });
252
+ }
253
+ // Handle synchronous results
254
+ span.setStatus({ code: SpanStatusCode.OK });
255
+ span.end();
256
+ return result;
257
+ }
258
+ catch (error) {
259
+ span.recordException(error);
260
+ span.setStatus({
261
+ code: SpanStatusCode.ERROR,
262
+ message: error.message,
263
+ });
264
+ span.end();
265
+ throw error;
266
+ }
267
+ });
268
+ };
269
+ //# sourceMappingURL=span.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"span.js","sourceRoot":"","sources":["../../src/utils/span.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAgB,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uB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C,KAAc,CAAC,CAAC;YACrC,IAAI,CAAC,SAAS,CAAC;gBACb,IAAI,EAAE,cAAc,CAAC,KAAK;gBAC1B,OAAO,EAAG,KAAe,CAAC,OAAO;aAClC,CAAC,CAAC;YACH,IAAI,CAAC,GAAG,EAAE,CAAC;YACX,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC,CAAC"}
@@ -0,0 +1,94 @@
1
+ import { SpanKind } from "@opentelemetry/api";
2
+ import { ReadableSpan } from "@opentelemetry/sdk-trace-base";
3
+ /**
4
+ * Interface for managing buffered spans.
5
+ *
6
+ * SpanBuffer provides manual control over span creation and export timing.
7
+ * Unlike automatic tracing, spans are buffered locally and only exported
8
+ * when you explicitly call processSpans().
9
+ *
10
+ * Key features:
11
+ * - Manual span creation with attributes
12
+ * - Local buffering (no automatic export)
13
+ * - Transportable spans (extract and process anywhere)
14
+ * - Context isolation
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const client = getClient();
19
+ * let collectedSpans: ReadableSpan[] = [];
20
+ *
21
+ * // Collect spans during execution
22
+ * with (client.getSpanBuffer("trace-123")) {
23
+ * buffer.createSpan("step1", { status: "completed" });
24
+ * buffer.createSpan("step2", { status: "completed" });
25
+ * collectedSpans = buffer.getAllSpans();
26
+ * }
27
+ *
28
+ * // Process later based on business logic
29
+ * if (shouldExport) {
30
+ * client.processSpans(collectedSpans);
31
+ * }
32
+ * ```
33
+ */
34
+ export interface SpanBuffer {
35
+ /**
36
+ * Create a span in the buffer
37
+ * @param name - Span name
38
+ * @param attributes - Optional span attributes
39
+ * @param kind - Optional span kind (default: INTERNAL)
40
+ */
41
+ createSpan(name: string, attributes?: Record<string, any>, kind?: SpanKind): void;
42
+ /**
43
+ * Get all buffered spans as ReadableSpan objects
44
+ * @returns Array of all buffered spans
45
+ */
46
+ getAllSpans(): ReadableSpan[];
47
+ /**
48
+ * Get the count of buffered spans
49
+ * @returns Number of spans in the buffer
50
+ */
51
+ getSpanCount(): number;
52
+ /**
53
+ * Clear all buffered spans without processing them
54
+ */
55
+ clearSpans(): void;
56
+ }
57
+ /**
58
+ * Manager for span buffers with context isolation.
59
+ *
60
+ * This class provides:
61
+ * - Context-isolated span buffering
62
+ * - Manual span processing through OTEL pipeline
63
+ * - Support for transportable spans
64
+ */
65
+ export declare class SpanBufferManager {
66
+ /**
67
+ * Create a new span buffer with the given trace ID
68
+ * @param traceId - Trace ID for all spans in this buffer
69
+ * @returns A new SpanBuffer instance
70
+ */
71
+ createBuffer(traceId: string): SpanBuffer;
72
+ /**
73
+ * Process spans through the OpenTelemetry processor pipeline.
74
+ * This sends the spans to all configured processors.
75
+ *
76
+ * @param spans - Array of ReadableSpan objects or a SpanBuffer
77
+ * @returns Promise<boolean> - True if processing succeeded
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * const manager = new SpanBufferManager();
82
+ * const buffer = manager.createBuffer("trace-123");
83
+ * buffer.createSpan("task", { result: "success" });
84
+ *
85
+ * const spans = buffer.getAllSpans();
86
+ * await manager.processSpans(spans);
87
+ * ```
88
+ */
89
+ processSpans(spans: ReadableSpan[] | SpanBuffer): Promise<boolean>;
90
+ }
91
+ /**
92
+ * Get the span buffer manager instance
93
+ */
94
+ export declare function getSpanBufferManager(): SpanBufferManager;
@@ -0,0 +1,147 @@
1
+ import { trace, SpanKind, ROOT_CONTEXT } from "@opentelemetry/api";
2
+ import { hrTime } from "@opentelemetry/core";
3
+ /**
4
+ * Context key for span buffer
5
+ */
6
+ const SPAN_BUFFER_KEY = Symbol("respan.span_buffer");
7
+ /**
8
+ * Implementation of SpanBuffer
9
+ */
10
+ class SpanBufferImpl {
11
+ spans = [];
12
+ traceId;
13
+ tracer = trace.getTracer("@respan/tracing");
14
+ constructor(traceId) {
15
+ this.traceId = traceId;
16
+ }
17
+ createSpan(name, attributes, kind = SpanKind.INTERNAL) {
18
+ // Create a span context for this buffered span
19
+ const spanContext = {
20
+ traceId: this.traceId,
21
+ spanId: this.generateSpanId(),
22
+ traceFlags: 1, // Sampled
23
+ };
24
+ // Create the span
25
+ const span = this.tracer.startSpan(name, {
26
+ kind,
27
+ startTime: hrTime(),
28
+ }, ROOT_CONTEXT);
29
+ // Set attributes
30
+ if (attributes) {
31
+ for (const [key, value] of Object.entries(attributes)) {
32
+ span.setAttribute(key, value);
33
+ }
34
+ }
35
+ // End the span immediately (we're creating historical spans)
36
+ span.end();
37
+ // Add to buffer
38
+ // @ts-ignore - Access internal span for buffering
39
+ this.spans.push(span);
40
+ console.debug(`[Respan] Buffered span: ${name} (total: ${this.spans.length})`);
41
+ }
42
+ getAllSpans() {
43
+ return [...this.spans];
44
+ }
45
+ getSpanCount() {
46
+ return this.spans.length;
47
+ }
48
+ clearSpans() {
49
+ const count = this.spans.length;
50
+ this.spans = [];
51
+ console.debug(`[Respan] Cleared ${count} buffered spans`);
52
+ }
53
+ generateSpanId() {
54
+ // Generate a random 16-character hex string for span ID
55
+ return Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
56
+ }
57
+ }
58
+ /**
59
+ * Manager for span buffers with context isolation.
60
+ *
61
+ * This class provides:
62
+ * - Context-isolated span buffering
63
+ * - Manual span processing through OTEL pipeline
64
+ * - Support for transportable spans
65
+ */
66
+ export class SpanBufferManager {
67
+ /**
68
+ * Create a new span buffer with the given trace ID
69
+ * @param traceId - Trace ID for all spans in this buffer
70
+ * @returns A new SpanBuffer instance
71
+ */
72
+ createBuffer(traceId) {
73
+ return new SpanBufferImpl(traceId);
74
+ }
75
+ /**
76
+ * Process spans through the OpenTelemetry processor pipeline.
77
+ * This sends the spans to all configured processors.
78
+ *
79
+ * @param spans - Array of ReadableSpan objects or a SpanBuffer
80
+ * @returns Promise<boolean> - True if processing succeeded
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * const manager = new SpanBufferManager();
85
+ * const buffer = manager.createBuffer("trace-123");
86
+ * buffer.createSpan("task", { result: "success" });
87
+ *
88
+ * const spans = buffer.getAllSpans();
89
+ * await manager.processSpans(spans);
90
+ * ```
91
+ */
92
+ async processSpans(spans) {
93
+ try {
94
+ const spanArray = Array.isArray(spans) ? spans : spans.getAllSpans();
95
+ if (spanArray.length === 0) {
96
+ console.debug("[Respan] No spans to process");
97
+ return true;
98
+ }
99
+ console.debug(`[Respan] Processing ${spanArray.length} buffered spans`);
100
+ // Get the SDK instance to access processors
101
+ const { getClient } = await import("./tracing.js");
102
+ const sdk = getClient();
103
+ if (!sdk) {
104
+ console.warn("[Respan] SDK not initialized, cannot process spans");
105
+ return false;
106
+ }
107
+ // Access the tracer provider and processors
108
+ // @ts-ignore - Access internal SDK structure
109
+ const tracerProvider = sdk._tracerProvider;
110
+ if (!tracerProvider) {
111
+ console.warn("[Respan] TracerProvider not found");
112
+ return false;
113
+ }
114
+ // Get active span processors
115
+ // @ts-ignore - Access internal structure
116
+ const activeSpanProcessor = tracerProvider.activeSpanProcessor;
117
+ if (!activeSpanProcessor) {
118
+ console.warn("[Respan] No active span processor found");
119
+ return false;
120
+ }
121
+ // Process each span through the pipeline
122
+ for (const span of spanArray) {
123
+ activeSpanProcessor.onEnd(span);
124
+ }
125
+ console.debug("[Respan] Successfully processed buffered spans");
126
+ return true;
127
+ }
128
+ catch (error) {
129
+ console.error("[Respan] Error processing spans:", error);
130
+ return false;
131
+ }
132
+ }
133
+ }
134
+ /**
135
+ * Global span buffer manager instance
136
+ */
137
+ let _bufferManager;
138
+ /**
139
+ * Get the span buffer manager instance
140
+ */
141
+ export function getSpanBufferManager() {
142
+ if (!_bufferManager) {
143
+ _bufferManager = new SpanBufferManager();
144
+ }
145
+ return _bufferManager;
146
+ }
147
+ //# sourceMappingURL=spanBuffer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spanBuffer.js","sourceRoot":"","sources":["../../src/utils/spanBuffer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,KAAK,EAAE,QAAQ,EAAe,YAAY,EAAW,MAAM,oBAAoB,CAAC;AAElG,OAAO,EAAE,MAAM,E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";
3
+ /**
4
+ * Helper function to resolve and clean up the base URL
5
+ */
6
+ export declare const _resolveBaseURL: (baseURL: string) => string;
7
+ /**
8
+ * Initializes the OpenTelemetry SDK with Respan-specific configuration.
9
+ * This sets up the entire tracing pipeline: collection, processing, and export.
10
+ *
11
+ * @param options - Configuration options for the tracing setup
12
+ */
13
+ export declare const startTracing: (options: RespanOptions) => Promise<void>;
14
+ /**
15
+ * Enhanced error logging for forceFlush
16
+ */
17
+ export declare const forceFlush: () => Promise<void>;
18
+ /**
19
+ * Gets the current SDK instance.
20
+ * Useful for advanced configuration or checking if tracing is initialized.
21
+ *
22
+ * @returns The NodeSDK instance or undefined if not initialized
23
+ */
24
+ export declare const getClient: () => NodeSDK | undefined;
25
+ /**
26
+ * Add a processor to the SDK for routing spans.
27
+ * This allows routing spans to different destinations based on processor names.
28
+ *
29
+ * @param config - Processor configuration
30
+ */
31
+ export declare const addProcessorToSDK: (config: ProcessorConfig) => void;