@glasstrace/sdk 0.4.1 → 0.4.2

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/env-detection.ts","../src/session.ts","../src/fetch-classifier.ts","../src/init-client.ts","../src/span-processor.ts","../src/enriching-exporter.ts","../src/discovery-endpoint.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/OTLPExporterBase.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/types.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/bounded-queue-export-promise-handler.ts","../../../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../../../node_modules/@opentelemetry/core/src/baggage/constants.ts","../../../node_modules/@opentelemetry/core/src/baggage/utils.ts","../../../node_modules/@opentelemetry/core/src/common/attributes.ts","../../../node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../../../node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../../../node_modules/@opentelemetry/core/src/platform/node/environment.ts","../../../node_modules/@opentelemetry/core/src/version.ts","../../../node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts","../../../node_modules/@opentelemetry/core/src/semconv.ts","../../../node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../../../node_modules/@opentelemetry/core/src/platform/node/index.ts","../../../node_modules/@opentelemetry/core/src/common/time.ts","../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../../../node_modules/@opentelemetry/core/src/utils/lodash.merge.ts","../../../node_modules/@opentelemetry/core/src/utils/merge.ts","../../../node_modules/@opentelemetry/core/src/utils/promise.ts","../../../node_modules/@opentelemetry/core/src/utils/callback.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/logging-response-handler.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/utils.ts","../../../node_modules/@opentelemetry/resources/src/default-service-name.ts","../../../node_modules/@opentelemetry/resources/src/utils.ts","../../../node_modules/@opentelemetry/resources/src/ResourceImpl.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/json/trace.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/util.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-transport-utils.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/is-export-retryable.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/version.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-exporter-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/retrying-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-http-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-http-options.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-node-http-options.ts","../../../node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/node/OTLPTraceExporter.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/enums.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Span.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/config.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/utility.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/RandomIdGenerator.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/semconv.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/TracerMetrics.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/version.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts","../src/otel-config.ts","../src/console-capture.ts","../src/register.ts","../src/source-map-uploader.ts","../src/config-wrapper.ts","../src/nudge/error-nudge.ts","../src/capture-error.ts"],"sourcesContent":["import type { SdkDiagnosticCode } from \"@glasstrace/protocol\";\n\n/**\n * Internal SDK error class with a typed diagnostic code.\n * Caught at the boundary and converted to a log message + diagnostic entry.\n * Never thrown to the developer.\n */\nexport class SdkError extends Error {\n readonly code: SdkDiagnosticCode;\n\n constructor(code: SdkDiagnosticCode, message: string, cause?: Error) {\n super(message, { cause });\n this.name = \"SdkError\";\n this.code = code;\n }\n}\n","import type { GlasstraceEnvVars, GlasstraceOptions } from \"@glasstrace/protocol\";\n\n/**\n * Resolved configuration after merging explicit options with environment variables.\n */\nexport interface ResolvedConfig {\n apiKey: string | undefined;\n endpoint: string;\n forceEnable: boolean;\n verbose: boolean;\n environment: string | undefined;\n coverageMapEnabled: boolean;\n nodeEnv: string | undefined;\n vercelEnv: string | undefined;\n}\n\nconst DEFAULT_ENDPOINT = \"https://api.glasstrace.dev\";\n\n/**\n * Reads all recognized Glasstrace environment variables from process.env.\n * Returns undefined for any variable not set. Never throws.\n */\nexport function readEnvVars(): GlasstraceEnvVars {\n return {\n GLASSTRACE_API_KEY: process.env.GLASSTRACE_API_KEY?.trim() || undefined,\n GLASSTRACE_FORCE_ENABLE: process.env.GLASSTRACE_FORCE_ENABLE,\n GLASSTRACE_ENV: process.env.GLASSTRACE_ENV,\n GLASSTRACE_COVERAGE_MAP: process.env.GLASSTRACE_COVERAGE_MAP,\n NODE_ENV: process.env.NODE_ENV,\n VERCEL_ENV: process.env.VERCEL_ENV,\n };\n}\n\n/**\n * Merges explicit GlasstraceOptions with environment variables.\n * Explicit options take precedence over environment variables.\n */\nexport function resolveConfig(options?: GlasstraceOptions): ResolvedConfig {\n const env = readEnvVars();\n\n return {\n apiKey: options?.apiKey ?? env.GLASSTRACE_API_KEY,\n endpoint: options?.endpoint ?? DEFAULT_ENDPOINT,\n forceEnable: options?.forceEnable ?? env.GLASSTRACE_FORCE_ENABLE === \"true\",\n verbose: options?.verbose ?? false,\n environment: env.GLASSTRACE_ENV,\n coverageMapEnabled: env.GLASSTRACE_COVERAGE_MAP === \"true\",\n nodeEnv: env.NODE_ENV,\n vercelEnv: env.VERCEL_ENV,\n };\n}\n\n/**\n * Returns true when the SDK should be inactive (production detected without force-enable).\n * Logic order:\n * 1. forceEnable === true → return false (override)\n * 2. NODE_ENV === 'production' → return true\n * 3. VERCEL_ENV === 'production' → return true\n * 4. Otherwise → return false\n */\nexport function isProductionDisabled(config: ResolvedConfig): boolean {\n if (config.forceEnable) {\n return false;\n }\n if (config.nodeEnv === \"production\") {\n return true;\n }\n if (config.vercelEnv === \"production\") {\n return true;\n }\n return false;\n}\n\n/**\n * Returns true when no API key is configured (anonymous mode).\n * Treats undefined, empty string, whitespace-only, and gt_anon_* keys as anonymous.\n */\nexport function isAnonymousMode(config: ResolvedConfig): boolean {\n if (config.apiKey === undefined) {\n return true;\n }\n if (config.apiKey.trim() === \"\") {\n return true;\n }\n if (config.apiKey.startsWith(\"gt_anon_\")) {\n return true;\n }\n return false;\n}\n","import { createHash } from \"node:crypto\";\nimport { SessionIdSchema } from \"@glasstrace/protocol\";\nimport type { SessionId } from \"@glasstrace/protocol\";\n\nconst FOUR_HOURS_MS = 4 * 60 * 60 * 1000;\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedGlasstraceEnv: string | undefined = process.env.GLASSTRACE_ENV;\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedGlasstraceEnv = process.env.GLASSTRACE_ENV;\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Derives a deterministic session ID from the given inputs using SHA-256.\n * The hash is truncated to 16 hex characters and parsed through SessionIdSchema.\n *\n * @param apiKey - The project's API key (or anonymous placeholder).\n * @param origin - The origin string identifying the deployment environment.\n * @param date - UTC date as YYYY-MM-DD.\n * @param windowIndex - Zero-based index of the 4-hour activity window within the day.\n * @returns A 16-character hex SessionId.\n */\nexport function deriveSessionId(\n apiKey: string,\n origin: string,\n date: string,\n windowIndex: number,\n): SessionId {\n const input = JSON.stringify([apiKey, origin, date, windowIndex]);\n const hash = createHash(\"sha256\").update(input).digest(\"hex\").slice(0, 16);\n return SessionIdSchema.parse(hash);\n}\n\n/**\n * Returns the origin string for the current process.\n * If GLASSTRACE_ENV is set, returns that value.\n * Otherwise returns `localhost:{PORT}` (PORT defaults to 3000).\n *\n * @returns The origin string used as a session derivation input.\n */\nexport function getOrigin(): string {\n if (cachedGlasstraceEnv) {\n return cachedGlasstraceEnv;\n }\n return `localhost:${cachedPort}`;\n}\n\n/**\n * Returns the current UTC date as a YYYY-MM-DD string.\n *\n * @returns The UTC date formatted as \"YYYY-MM-DD\".\n */\nexport function getDateString(): string {\n const now = new Date();\n const year = now.getUTCFullYear();\n const month = String(now.getUTCMonth() + 1).padStart(2, \"0\");\n const day = String(now.getUTCDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n}\n\n/**\n * Tracks the current session state with 4-hour window tracking.\n * Instantiated once by the orchestrator.\n */\nexport class SessionManager {\n private windowIndex: number = 0;\n private lastActivityTimestamp: number = 0;\n private lastDate: string = \"\";\n private lastApiKey: string = \"\";\n private currentSessionId: SessionId | null = null;\n\n /**\n * Returns the current session ID, deriving a new one if:\n * - More than 4 hours have elapsed since last activity\n * - The UTC date has changed (resets window index to 0)\n * - The API key has changed (e.g., deferred anonymous key swap)\n * - This is the first call\n *\n * @param apiKey - The project's API key used in session derivation.\n * @returns The current or newly derived SessionId.\n */\n getSessionId(apiKey: string): SessionId {\n const now = Date.now();\n const currentDate = getDateString();\n const origin = getOrigin();\n\n const elapsed = now - this.lastActivityTimestamp;\n const dateChanged = currentDate !== this.lastDate;\n const apiKeyChanged = apiKey !== this.lastApiKey;\n\n if (dateChanged) {\n // New UTC day: reset window index\n this.windowIndex = 0;\n this.lastDate = currentDate;\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (apiKeyChanged) {\n // API key changed (e.g., anonymous key resolved): re-derive with same window\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (this.currentSessionId === null || elapsed > FOUR_HOURS_MS) {\n // First call or gap exceeding 4 hours: increment window\n if (this.currentSessionId !== null) {\n this.windowIndex++;\n }\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n this.lastDate = currentDate;\n }\n\n this.lastActivityTimestamp = now;\n return this.currentSessionId;\n }\n}\n","/**\n * The set of recognized fetch target categories.\n */\nexport type FetchTarget = \"supabase\" | \"stripe\" | \"internal\" | \"unknown\";\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Classifies an outbound fetch target URL into a known category.\n * Classification is case-insensitive and based on the URL hostname.\n * Uses dot-boundary matching to avoid false positives (e.g. evilstripe.com).\n *\n * Returns one of: 'supabase', 'stripe', 'internal', or 'unknown'.\n */\nexport function classifyFetchTarget(url: string): FetchTarget {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return \"unknown\";\n }\n\n const hostname = parsed.hostname.toLowerCase();\n\n if (\n hostname === \"supabase.co\" ||\n hostname.endsWith(\".supabase.co\") ||\n hostname === \"supabase.in\" ||\n hostname.endsWith(\".supabase.in\")\n ) {\n return \"supabase\";\n }\n\n if (hostname === \"stripe.com\" || hostname.endsWith(\".stripe.com\")) {\n return \"stripe\";\n }\n\n const internalOrigin = `localhost:${cachedPort}`;\n const parsedPort = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n const urlOrigin = `${hostname}:${parsedPort}`;\n\n if (urlOrigin === internalOrigin) {\n return \"internal\";\n }\n\n return \"unknown\";\n}\n","import { readFileSync } from \"node:fs\";\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n SdkInitResponseSchema,\n SdkCachedConfigSchema,\n DEFAULT_CAPTURE_CONFIG,\n} from \"@glasstrace/protocol\";\nimport type {\n SdkInitResponse,\n CaptureConfig,\n AnonApiKey,\n ImportGraphPayload,\n SdkHealthReport,\n SdkDiagnosticCode,\n} from \"@glasstrace/protocol\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\n\nconst GLASSTRACE_DIR = \".glasstrace\";\nconst CONFIG_FILE = \"config\";\nconst TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;\nconst INIT_TIMEOUT_MS = 10_000;\n\n/** In-memory config from the latest successful init response. */\nlet currentConfig: SdkInitResponse | null = null;\n\n/** Whether the next init call should be skipped (rate-limit backoff). */\nlet rateLimitBackoff = false;\n\n/**\n * Reads and validates a cached config file from `.glasstrace/config`.\n * Returns the parsed `SdkInitResponse` or `null` on any failure.\n */\nexport function loadCachedConfig(projectRoot?: string): SdkInitResponse | null {\n const root = projectRoot ?? process.cwd();\n const configPath = join(root, GLASSTRACE_DIR, CONFIG_FILE);\n\n try {\n // Use synchronous read for startup performance (this is called during init)\n const content = readFileSync(configPath, \"utf-8\");\n const parsed = JSON.parse(content);\n const cached = SdkCachedConfigSchema.parse(parsed);\n\n // Warn if cache is stale\n const age = Date.now() - cached.cachedAt;\n if (age > TWENTY_FOUR_HOURS_MS) {\n console.warn(\n `[glasstrace] Cached config is ${Math.round(age / 3600000)}h old. Will refresh on next init.`,\n );\n }\n\n // Parse the response through the schema\n const result = SdkInitResponseSchema.safeParse(cached.response);\n if (result.success) {\n return result.data;\n }\n\n console.warn(\"[glasstrace] Cached config failed validation. Using defaults.\");\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Persists the init response to `.glasstrace/config`.\n * On failure, logs a warning and continues.\n */\nexport async function saveCachedConfig(\n response: SdkInitResponse,\n projectRoot?: string,\n): Promise<void> {\n const root = projectRoot ?? process.cwd();\n const dirPath = join(root, GLASSTRACE_DIR);\n const configPath = join(dirPath, CONFIG_FILE);\n\n try {\n await mkdir(dirPath, { recursive: true });\n const cached = {\n response,\n cachedAt: Date.now(),\n };\n await writeFile(configPath, JSON.stringify(cached), \"utf-8\");\n } catch (err) {\n console.warn(\n `[glasstrace] Failed to cache config to ${configPath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Sends a POST request to `/v1/sdk/init`.\n * Validates the response against `SdkInitResponseSchema`.\n */\nexport async function sendInitRequest(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n importGraph?: ImportGraphPayload,\n healthReport?: SdkHealthReport,\n diagnostics?: Array<{ code: SdkDiagnosticCode; message: string; timestamp: number }>,\n signal?: AbortSignal,\n): Promise<SdkInitResponse> {\n // Determine the API key for auth. Use || (not ??) so empty strings\n // fall through to the anonymous key — defense in depth for DISC-467.\n const effectiveKey = config.apiKey || anonKey;\n if (!effectiveKey) {\n throw new Error(\"No API key available for init request\");\n }\n\n // Build the request payload\n const payload: Record<string, unknown> = {\n apiKey: effectiveKey,\n sdkVersion,\n };\n\n // Straggler linking: if dev key is set AND anonKey is provided\n if (config.apiKey && anonKey) {\n payload.anonKey = anonKey;\n }\n\n if (config.environment) {\n payload.environment = config.environment;\n }\n if (importGraph) {\n payload.importGraph = importGraph;\n }\n if (healthReport) {\n payload.healthReport = healthReport;\n }\n if (diagnostics) {\n payload.diagnostics = diagnostics;\n }\n\n const url = `${config.endpoint}/v1/sdk/init`;\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${effectiveKey}`,\n },\n body: JSON.stringify(payload),\n signal,\n });\n\n if (!response.ok) {\n // Consume the response body to release the connection back to the pool.\n // Without this, the underlying TCP socket stays allocated until GC, which\n // causes connection pool exhaustion under sustained error conditions.\n // Wrapped in try-catch so a stream error doesn't mask the HTTP status error.\n try { await response.text(); } catch { /* body drain is best-effort */ }\n const error = new Error(`Init request failed with status ${response.status}`);\n (error as unknown as Record<string, unknown>).status = response.status;\n throw error;\n }\n\n const body = await response.json();\n return SdkInitResponseSchema.parse(body);\n}\n\n/**\n * Orchestrates the full init flow: send request, update config, cache result.\n * This function MUST NOT throw.\n */\nexport async function performInit(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n): Promise<void> {\n // Skip if in rate-limit backoff\n if (rateLimitBackoff) {\n rateLimitBackoff = false; // Reset for next call\n return;\n }\n\n try {\n const effectiveKey = config.apiKey || anonKey;\n if (!effectiveKey) {\n console.warn(\"[glasstrace] No API key available for init request.\");\n return;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), INIT_TIMEOUT_MS);\n\n try {\n // Delegate to sendInitRequest to avoid duplicating fetch logic\n const result = await sendInitRequest(\n config,\n anonKey,\n sdkVersion,\n undefined,\n undefined,\n undefined,\n controller.signal,\n );\n\n clearTimeout(timeoutId);\n\n // Update in-memory config\n currentConfig = result;\n\n // Persist to disk\n await saveCachedConfig(result);\n } catch (err) {\n clearTimeout(timeoutId);\n\n if (err instanceof DOMException && err.name === \"AbortError\") {\n console.warn(\"[glasstrace] ingestion_unreachable: Init request timed out.\");\n return;\n }\n\n // Check for HTTP status errors attached by sendInitRequest\n const status = (err as Record<string, unknown>).status;\n if (status === 401) {\n console.warn(\n \"[glasstrace] ingestion_auth_failed: Check your GLASSTRACE_API_KEY.\",\n );\n return;\n }\n\n if (status === 429) {\n console.warn(\"[glasstrace] ingestion_rate_limited: Backing off.\");\n rateLimitBackoff = true;\n return;\n }\n\n if (typeof status === \"number\" && status >= 400) {\n console.warn(\n `[glasstrace] Init request failed with status ${status}. Using cached config.`,\n );\n return;\n }\n\n // Schema validation failure from sendInitRequest.parse\n if (err instanceof Error && err.name === \"ZodError\") {\n console.warn(\n \"[glasstrace] Init response failed validation (schema version mismatch?). Using cached config.\",\n );\n return;\n }\n\n // Network error or other fetch failure\n console.warn(\n `[glasstrace] ingestion_unreachable: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n } catch (err) {\n // Outermost catch -- should never reach here, but safety net\n console.warn(\n `[glasstrace] Unexpected init error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Returns the current capture config from the three-tier fallback chain:\n * 1. In-memory config from latest init response\n * 2. File cache\n * 3. DEFAULT_CAPTURE_CONFIG\n */\nexport function getActiveConfig(): CaptureConfig {\n // Tier 1: in-memory\n if (currentConfig) {\n return currentConfig.config;\n }\n\n // Tier 2: file cache\n const cached = loadCachedConfig();\n if (cached) {\n return cached.config;\n }\n\n // Tier 3: defaults\n return { ...DEFAULT_CAPTURE_CONFIG };\n}\n\n/**\n * Resets the in-memory config store. For testing only.\n */\nexport function _resetConfigForTesting(): void {\n currentConfig = null;\n rateLimitBackoff = false;\n}\n\n/**\n * Sets the in-memory config directly. Used by performInit and the orchestrator.\n */\nexport function _setCurrentConfig(config: SdkInitResponse): void {\n currentConfig = config;\n}\n\n/**\n * Returns whether rate-limit backoff is active. For testing only.\n */\nexport function _isRateLimitBackoff(): boolean {\n return rateLimitBackoff;\n}\n","import type { SpanProcessor, ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\nimport type { Span } from \"@opentelemetry/sdk-trace-base\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\n\n/**\n * Lightweight SpanProcessor that delegates to a wrapped processor.\n *\n * All glasstrace.* attribute enrichment has been moved to {@link GlasstraceExporter}\n * (see enriching-exporter.ts), which enriches spans at export time. This resolves:\n * - Cold-start spans are buffered in the exporter, not dropped\n * - Vercel's CompositeSpanProcessor skips onEnding(); the exporter doesn't need it\n * - Session ID is computed at export time with the resolved API key\n *\n * This class is retained for backward compatibility. New code should use\n * GlasstraceExporter directly.\n *\n * @deprecated Use GlasstraceExporter for span enrichment. This processor is now a pass-through.\n */\nexport class GlasstraceSpanProcessor implements SpanProcessor {\n private readonly wrappedProcessor: SpanProcessor;\n\n /* eslint-disable @typescript-eslint/no-unused-vars -- backward compat signature */\n constructor(\n wrappedProcessor: SpanProcessor,\n _sessionManager?: SessionManager,\n _apiKey?: string | (() => string),\n _getConfig?: () => CaptureConfig,\n _environment?: string,\n ) {\n /* eslint-enable @typescript-eslint/no-unused-vars */\n this.wrappedProcessor = wrappedProcessor;\n }\n\n onStart(span: Span, parentContext: Parameters<SpanProcessor[\"onStart\"]>[1]): void {\n this.wrappedProcessor.onStart(span, parentContext);\n }\n\n onEnd(readableSpan: ReadableSpan): void {\n this.wrappedProcessor.onEnd(readableSpan);\n }\n\n async shutdown(): Promise<void> {\n return this.wrappedProcessor.shutdown();\n }\n\n async forceFlush(): Promise<void> {\n return this.wrappedProcessor.forceFlush();\n }\n}\n","import { SpanKind } from \"@opentelemetry/api\";\nimport type { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport type { ExportResult } from \"@opentelemetry/core\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\nimport { classifyFetchTarget } from \"./fetch-classifier.js\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\n\n/**\n * Sentinel value indicating the API key has not yet been resolved.\n */\nexport const API_KEY_PENDING = \"pending\" as const;\n\n/**\n * Maximum number of spans to buffer while waiting for key resolution.\n * Prevents unbounded memory growth if the key never resolves.\n */\nconst MAX_PENDING_SPANS = 1024;\n\n\n/**\n * Options for constructing a {@link GlasstraceExporter}.\n */\nexport interface GlasstraceExporterOptions {\n getApiKey: () => string;\n sessionManager: SessionManager;\n getConfig: () => CaptureConfig;\n environment: string | undefined;\n endpointUrl: string;\n createDelegate: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n}\n\ninterface PendingBatch {\n spans: ReadableSpan[];\n resultCallback: (result: ExportResult) => void;\n}\n\n/**\n * A SpanExporter that enriches spans with glasstrace.* attributes at export\n * time, then delegates to a real OTLP exporter.\n *\n * This design resolves three issues:\n * - Spans emitted before the API key resolves are buffered (not dropped)\n * and flushed once the key is available.\n * - Enrichment happens in the exporter (not onEnding), so it works\n * on Vercel where CompositeSpanProcessor does not forward onEnding().\n * - Session ID is computed at export time using the resolved API key,\n * not the \"pending\" placeholder.\n */\nexport class GlasstraceExporter implements SpanExporter {\n private readonly getApiKey: () => string;\n private readonly sessionManager: SessionManager;\n private readonly getConfig: () => CaptureConfig;\n private readonly environment: string | undefined;\n private readonly endpointUrl: string;\n private readonly createDelegateFn: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n\n private delegate: SpanExporter | null = null;\n private delegateKey: string | null = null;\n private pendingBatches: PendingBatch[] = [];\n private pendingSpanCount = 0;\n private overflowLogged = false;\n\n constructor(options: GlasstraceExporterOptions) {\n this.getApiKey = options.getApiKey;\n this.sessionManager = options.sessionManager;\n this.getConfig = options.getConfig;\n this.environment = options.environment;\n this.endpointUrl = options.endpointUrl;\n this.createDelegateFn = options.createDelegate;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) {\n // Buffer raw (unenriched) spans — enrichment deferred to flush time\n // so session IDs are computed with the resolved key, not \"pending\".\n this.bufferSpans(spans, resultCallback);\n return;\n }\n\n // Key is available — enrich and export\n const enrichedSpans = spans.map((span) => this.enrichSpan(span));\n const exporter = this.ensureDelegate();\n if (exporter) {\n exporter.export(enrichedSpans, resultCallback);\n } else {\n // No delegate factory — report success so the pipeline does not stall\n resultCallback({ code: 0 });\n }\n }\n\n /**\n * Called when the API key transitions from \"pending\" to a resolved value.\n * Creates the delegate exporter and flushes all buffered spans.\n */\n notifyKeyResolved(): void {\n this.flushPending();\n }\n\n async shutdown(): Promise<void> {\n const currentKey = this.getApiKey();\n if (currentKey !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n this.flushPending();\n } else if (this.pendingBatches.length > 0) {\n console.warn(\n `[glasstrace] Shutdown with ${this.pendingSpanCount} buffered spans — API key never resolved, spans lost.`,\n );\n // Complete pending callbacks so pipeline doesn't hang\n for (const batch of this.pendingBatches) {\n batch.resultCallback({ code: 0 });\n }\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n }\n\n if (this.delegate) {\n return this.delegate.shutdown();\n }\n }\n\n forceFlush(): Promise<void> {\n if (this.delegate?.forceFlush) {\n return this.delegate.forceFlush();\n }\n return Promise.resolve();\n }\n\n /**\n * Enriches a ReadableSpan with all glasstrace.* attributes.\n * Returns a new ReadableSpan wrapper; the original span is not mutated.\n *\n * External function calls (getSessionId, deriveErrorCategory,\n * deriveOrmProvider, classifyFetchTarget) are individually guarded so a\n * failure in one does not prevent the remaining attributes from being set.\n * On total failure, returns the original span unchanged.\n */\n private enrichSpan(span: ReadableSpan): ReadableSpan {\n try {\n const attrs = span.attributes ?? {};\n const name = span.name ?? \"\";\n const extra: Record<string, string | number> = {};\n\n // glasstrace.trace.type\n extra[ATTR.TRACE_TYPE] = \"server\";\n\n // glasstrace.session.id — calls external code (crypto, schema validation)\n try {\n const sessionId = this.sessionManager.getSessionId(this.getApiKey());\n extra[ATTR.SESSION_ID] = sessionId;\n } catch { /* session ID omitted */ }\n\n // glasstrace.environment\n const env = this.environment ?? process.env.GLASSTRACE_ENV;\n if (env) {\n extra[ATTR.ENVIRONMENT] = env;\n }\n\n // glasstrace.correlation.id\n const existingCid = attrs[\"glasstrace.correlation.id\"];\n if (typeof existingCid === \"string\") {\n extra[ATTR.CORRELATION_ID] = existingCid;\n }\n\n // glasstrace.route\n const route =\n (attrs[\"http.route\"] as string | undefined) ?? name;\n if (route) {\n extra[ATTR.ROUTE] = route;\n }\n\n // glasstrace.http.method\n const method =\n (attrs[\"http.method\"] as string | undefined) ??\n (attrs[\"http.request.method\"] as string | undefined);\n if (method) {\n extra[ATTR.HTTP_METHOD] = method;\n }\n\n // glasstrace.http.status_code\n const statusCode =\n (attrs[\"http.status_code\"] as number | undefined) ??\n (attrs[\"http.response.status_code\"] as number | undefined);\n if (statusCode !== undefined) {\n extra[ATTR.HTTP_STATUS_CODE] = statusCode;\n }\n\n // glasstrace.http.duration_ms\n if (span.startTime && span.endTime) {\n const [startSec, startNano] = span.startTime;\n const [endSec, endNano] = span.endTime;\n const durationMs =\n (endSec - startSec) * 1000 + (endNano - startNano) / 1_000_000;\n if (durationMs >= 0) {\n extra[ATTR.HTTP_DURATION_MS] = durationMs;\n }\n }\n\n // glasstrace.error.message\n const errorMessage = attrs[\"exception.message\"] as string | undefined;\n if (errorMessage) {\n extra[ATTR.ERROR_MESSAGE] = errorMessage;\n }\n\n // glasstrace.error.code + glasstrace.error.category — calls deriveErrorCategory\n try {\n const errorType = attrs[\"exception.type\"] as string | undefined;\n if (errorType) {\n extra[ATTR.ERROR_CODE] = errorType;\n extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(errorType);\n }\n } catch { /* error category omitted */ }\n\n // glasstrace.error.field\n const errorField = attrs[\"error.field\"] as string | undefined;\n if (errorField) {\n extra[ATTR.ERROR_FIELD] = errorField;\n }\n\n // glasstrace.orm.* — calls deriveOrmProvider\n try {\n const spanAny = span as unknown as Record<string, { name?: string } | undefined>;\n const instrumentationName =\n (spanAny.instrumentationScope?.name ?? spanAny.instrumentationLibrary?.name) ?? \"\";\n const ormProvider = deriveOrmProvider(instrumentationName);\n if (ormProvider) {\n extra[ATTR.ORM_PROVIDER] = ormProvider;\n\n const model =\n (attrs[\"db.sql.table\"] as string | undefined) ??\n (attrs[\"db.prisma.model\"] as string | undefined);\n if (model) {\n extra[ATTR.ORM_MODEL] = model;\n }\n\n const operation = attrs[\"db.operation\"] as string | undefined;\n if (operation) {\n extra[ATTR.ORM_OPERATION] = operation;\n }\n }\n } catch { /* ORM attributes omitted */ }\n\n // glasstrace.fetch.target — calls classifyFetchTarget\n try {\n const url =\n (attrs[\"http.url\"] as string | undefined) ??\n (attrs[\"url.full\"] as string | undefined);\n if (url && span.kind === SpanKind.CLIENT) {\n extra[ATTR.FETCH_TARGET] = classifyFetchTarget(url);\n }\n } catch { /* fetch target omitted */ }\n\n return createEnrichedSpan(span, extra);\n } catch {\n // Return original span unchanged so the export pipeline is never blocked\n return span;\n }\n }\n\n /**\n * Lazily creates the delegate OTLP exporter once the API key is resolved.\n * Recreates the delegate if the key has changed (e.g., after key rotation)\n * so the Authorization header stays current.\n */\n private ensureDelegate(): SpanExporter | null {\n if (!this.createDelegateFn) return null;\n\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) return null;\n\n // Recreate delegate if the key has changed since last creation\n if (this.delegate && this.delegateKey === currentKey) {\n return this.delegate;\n }\n\n // Shut down old delegate if key rotated. Catch errors to prevent\n // unhandled rejections from crashing the process during rotation.\n if (this.delegate) {\n void this.delegate.shutdown?.().catch(() => {});\n }\n\n this.delegate = this.createDelegateFn(this.endpointUrl, {\n Authorization: `Bearer ${currentKey}`,\n });\n this.delegateKey = currentKey;\n return this.delegate;\n }\n\n /**\n * Buffers raw (unenriched) spans while the API key is pending.\n * Evicts oldest batches if the buffer exceeds MAX_PENDING_SPANS.\n * Re-checks the key after buffering to close the race window where\n * the key resolves between the caller's check and this buffer call.\n */\n private bufferSpans(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n this.pendingBatches.push({ spans, resultCallback });\n this.pendingSpanCount += spans.length;\n\n // Evict oldest batches if over limit\n while (this.pendingSpanCount > MAX_PENDING_SPANS && this.pendingBatches.length > 1) {\n const evicted = this.pendingBatches.shift()!;\n this.pendingSpanCount -= evicted.spans.length;\n // Complete callback so pipeline doesn't hang\n evicted.resultCallback({ code: 0 });\n\n if (!this.overflowLogged) {\n this.overflowLogged = true;\n console.warn(\n \"[glasstrace] Pending span buffer overflow — oldest spans evicted. \" +\n \"This usually means the API key is taking too long to resolve.\",\n );\n }\n }\n\n // Re-check: if the key resolved between the caller's check and now,\n // flush immediately to avoid spans stuck in the buffer.\n if (this.getApiKey() !== API_KEY_PENDING) {\n this.flushPending();\n }\n }\n\n /**\n * Flushes all buffered spans through the delegate exporter.\n * Enriches spans at flush time (not buffer time) so that session IDs\n * are computed with the resolved API key instead of the \"pending\" sentinel.\n */\n private flushPending(): void {\n if (this.pendingBatches.length === 0) return;\n\n const exporter = this.ensureDelegate();\n if (!exporter) {\n // No delegate factory — complete callbacks and discard\n for (const batch of this.pendingBatches) {\n batch.resultCallback({ code: 0 });\n }\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n return;\n }\n\n const batches = this.pendingBatches;\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n\n for (const batch of batches) {\n // Enrich at flush time with the now-resolved key\n const enriched = batch.spans.map((span) => this.enrichSpan(span));\n exporter.export(enriched, batch.resultCallback);\n }\n }\n\n}\n\n/**\n * Creates a ReadableSpan wrapper that inherits all properties from the\n * original span but overrides `attributes` to include additional entries.\n * The original span is not mutated.\n */\nfunction createEnrichedSpan(\n span: ReadableSpan,\n extra: Record<string, string | number>,\n): ReadableSpan {\n const enrichedAttributes = { ...span.attributes, ...extra };\n return Object.create(span, {\n attributes: {\n value: enrichedAttributes,\n enumerable: true,\n },\n }) as ReadableSpan;\n}\n\n/**\n * Derives ORM provider from the instrumentation library name.\n */\nexport function deriveOrmProvider(instrumentationName: string): string | null {\n const lower = instrumentationName.toLowerCase();\n if (lower.includes(\"prisma\")) {\n return \"prisma\";\n }\n if (lower.includes(\"drizzle\")) {\n return \"drizzle\";\n }\n return null;\n}\n\n/**\n * Derives error category from error type string.\n */\nexport function deriveErrorCategory(errorType: string): string {\n const lower = errorType.toLowerCase();\n if (lower.includes(\"validation\") || lower.includes(\"zod\")) {\n return \"validation\";\n }\n if (\n lower.includes(\"network\") ||\n lower.includes(\"econnrefused\") ||\n lower.includes(\"fetch\") ||\n lower.includes(\"timeout\")\n ) {\n return \"network\";\n }\n if (lower.includes(\"auth\") || lower.includes(\"unauthorized\") || lower.includes(\"forbidden\")) {\n return \"auth\";\n }\n if (lower.includes(\"notfound\") || lower.includes(\"not_found\")) {\n return \"not-found\";\n }\n return \"internal\";\n}\n","import type { AnonApiKey, SessionId } from \"@glasstrace/protocol\";\n\n/**\n * Checks whether the given Origin header is allowed for CORS access.\n *\n * Allowed origins:\n * - `chrome-extension://*` — any Chrome extension\n * - `moz-extension://*` — any Firefox extension\n * - `safari-web-extension://*` — any Safari extension\n * - Absent origin (same-origin / non-browser request)\n *\n * Replaced wildcard `*` to prevent arbitrary websites from\n * reading the anonymous API key from localhost.\n */\nfunction isAllowedOrigin(origin: string | null): boolean {\n if (origin === null) return true;\n if (origin.startsWith(\"chrome-extension://\")) return true;\n if (origin.startsWith(\"moz-extension://\")) return true;\n if (origin.startsWith(\"safari-web-extension://\")) return true;\n return false;\n}\n\n/**\n * Builds CORS headers for a given request origin.\n * Returns headers with `Access-Control-Allow-Origin` set to the origin\n * if allowed, otherwise omits that header entirely.\n */\nfunction buildCorsHeaders(origin: string | null): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Vary: \"Origin\",\n };\n\n if (origin && isAllowedOrigin(origin)) {\n headers[\"Access-Control-Allow-Origin\"] = origin;\n }\n\n return headers;\n}\n\n/**\n * Creates a request handler for the `/__glasstrace/config` discovery endpoint.\n *\n * The returned handler checks if the request URL path is `/__glasstrace/config`.\n * If not, returns `null` (pass-through). If it matches, returns a `DiscoveryResponse`\n * with the anonymous key and current session ID.\n *\n * The triple guard (anonymous + dev + active) is enforced by the caller,\n * not by this module. If the handler is registered, it serves.\n */\nexport function createDiscoveryHandler(\n getAnonKey: () => Promise<AnonApiKey | null>,\n getSessionId: () => SessionId,\n): (request: Request) => Promise<Response | null> {\n return async (request: Request): Promise<Response | null> => {\n // Check path match\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n\n if (url.pathname !== \"/__glasstrace/config\") {\n return null;\n }\n\n // Restrict CORS to known extension origins instead of wildcard\n const origin = request.headers.get(\"Origin\");\n const corsHeaders = buildCorsHeaders(origin);\n\n // Handle CORS preflight\n if (request.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n ...corsHeaders,\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n },\n });\n }\n\n // Only allow GET requests\n if (request.method !== \"GET\") {\n return new Response(\n JSON.stringify({ error: \"method_not_allowed\" }),\n {\n status: 405,\n headers: corsHeaders,\n },\n );\n }\n\n try {\n // Get the anonymous key\n const anonKey = await getAnonKey();\n\n if (anonKey === null) {\n return new Response(\n JSON.stringify({ error: \"not_ready\" }),\n {\n status: 503,\n headers: corsHeaders,\n },\n );\n }\n\n // Get the current session ID\n const sessionId = getSessionId();\n\n return new Response(\n JSON.stringify({ key: anonKey, sessionId }),\n {\n status: 200,\n headers: corsHeaders,\n },\n );\n } catch {\n return new Response(\n JSON.stringify({ error: \"internal_error\" }),\n {\n status: 500,\n headers: corsHeaders,\n },\n );\n }\n };\n}\n\n// Exported for testing\nexport { isAllowedOrigin, buildCorsHeaders };\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\n\nexport class OTLPExporterBase<Internal> {\n private _delegate: IOtlpExportDelegate<Internal>;\n constructor(delegate: IOtlpExportDelegate<Internal>) {\n this._delegate = delegate;\n }\n\n /**\n * Export items.\n * @param items\n * @param resultCallback\n */\n export(\n items: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._delegate.export(items, resultCallback);\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n readonly code?: number;\n override readonly name: string = 'OTLPExporterError';\n readonly data?: string;\n\n constructor(message?: string, code?: number, data?: string) {\n super(message);\n this.data = data;\n this.code = code;\n }\n}\n\n/**\n * Interface for handling export service errors\n */\nexport interface ExportServiceError {\n name: string;\n code: number;\n details: string;\n metadata: { [key: string]: unknown };\n message: string;\n stack: string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HeadersFactory } from './otlp-http-configuration';\n\n/**\n * Configuration shared across all OTLP exporters\n *\n * Implementation note: anything added here MUST be\n * - platform-agnostic\n * - signal-agnostic\n * - transport-agnostic\n */\nexport interface OtlpSharedConfiguration {\n timeoutMillis: number;\n concurrencyLimit: number;\n compression: 'gzip' | 'none';\n}\n\nexport function validateTimeoutMillis(timeoutMillis: number) {\n if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {\n return timeoutMillis;\n }\n throw new Error(\n `Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`\n );\n}\n\nexport function wrapStaticHeadersInFunction(\n headers: Record<string, string> | undefined\n): HeadersFactory | undefined {\n if (headers == null) {\n return undefined;\n }\n\n return async () => headers;\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpSharedConfiguration>,\n fallbackConfiguration: Partial<OtlpSharedConfiguration>,\n defaultConfiguration: OtlpSharedConfiguration\n): OtlpSharedConfiguration {\n return {\n timeoutMillis: validateTimeoutMillis(\n userProvidedConfiguration.timeoutMillis ??\n fallbackConfiguration.timeoutMillis ??\n defaultConfiguration.timeoutMillis\n ),\n concurrencyLimit:\n userProvidedConfiguration.concurrencyLimit ??\n fallbackConfiguration.concurrencyLimit ??\n defaultConfiguration.concurrencyLimit,\n compression:\n userProvidedConfiguration.compression ??\n fallbackConfiguration.compression ??\n defaultConfiguration.compression,\n };\n}\n\nexport function getSharedConfigurationDefaults(): OtlpSharedConfiguration {\n return {\n timeoutMillis: 10000,\n concurrencyLimit: 30,\n compression: 'none',\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface IExportPromiseHandler {\n pushPromise(promise: Promise<void>): void;\n hasReachedLimit(): boolean;\n awaitAll(): Promise<void>;\n}\n\nclass BoundedQueueExportPromiseHandler implements IExportPromiseHandler {\n private readonly _concurrencyLimit: number;\n private _sendingPromises: Promise<unknown>[] = [];\n\n /**\n * @param concurrencyLimit maximum promises allowed in a queue at the same time.\n */\n constructor(concurrencyLimit: number) {\n this._concurrencyLimit = concurrencyLimit;\n }\n\n public pushPromise(promise: Promise<void>): void {\n if (this.hasReachedLimit()) {\n throw new Error('Concurrency Limit reached');\n }\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n void this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n\n public hasReachedLimit(): boolean {\n return this._sendingPromises.length >= this._concurrencyLimit;\n }\n\n public async awaitAll(): Promise<void> {\n await Promise.all(this._sendingPromises);\n }\n}\n\n/**\n * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued.\n * Allows for awaiting all promises in the queue.\n */\nexport function createBoundedQueueExportPromiseHandler(options: {\n concurrencyLimit: number;\n}): IExportPromiseHandler {\n return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Baggage, BaggageEntryMetadata } from '@opentelemetry/api';\nimport { baggageEntryMetadataFromString } from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n if (!entry) return;\n const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);\n const keyPairPart =\n metadataSeparatorIndex === -1\n ? entry\n : entry.substring(0, metadataSeparatorIndex);\n\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n\n const rawKey = keyPairPart.substring(0, separatorIndex).trim();\n const rawValue = keyPairPart.substring(separatorIndex + 1).trim();\n\n if (!rawKey || !rawValue) return;\n let key: string;\n let value: string;\n try {\n key = decodeURIComponent(rawKey);\n value = decodeURIComponent(rawValue);\n } catch {\n return;\n }\n\n let metadata;\n if (\n metadataSeparatorIndex !== -1 &&\n metadataSeparatorIndex < entry.length - 1\n ) {\n const metadataString = entry.substring(metadataSeparatorIndex + 1);\n metadata = baggageEntryMetadataFromString(metadataString);\n }\n\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n if (typeof value === 'string' && value.length > 0) {\n value.split(BAGGAGE_ITEMS_SEPARATOR).forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n\n if (keyPair !== undefined && keyPair.value.length > 0) {\n result[keyPair.key] = keyPair.value;\n }\n });\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AttributeValue, Attributes } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): Attributes {\n const out: Attributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const key in attributes) {\n if (!Object.prototype.hasOwnProperty.call(attributes, key)) {\n continue;\n }\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n const val = (attributes as Record<string, unknown>)[key];\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key !== '';\n}\n\nexport function isAttributeValue(val: unknown): val is AttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValueType(typeof val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n const elementType = typeof element;\n\n if (elementType === type) {\n continue;\n }\n\n if (!type) {\n if (isValidPrimitiveAttributeValueType(elementType)) {\n type = elementType;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValueType(valType: string): boolean {\n switch (valType) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport type { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { inspect } from 'util';\n\n/**\n * Retrieves a number from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number.\n * - Returns a number in all other cases.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {number | undefined} - The number value or `undefined`.\n */\nexport function getNumberFromEnv(key: string): number | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n\n const value = Number(raw);\n if (isNaN(value)) {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`\n );\n return undefined;\n }\n\n return value;\n}\n\n/**\n * Retrieves a string from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string | undefined} - The string value or `undefined`.\n */\nexport function getStringFromEnv(key: string): string | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n return raw;\n}\n\n/**\n * Retrieves a boolean value from an environment variable.\n * - Trims leading and trailing whitespace and ignores casing.\n * - Returns `false` if the environment variable is empty, unset, or contains only whitespace.\n * - Returns `false` for strings that cannot be mapped to a boolean.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace.\n */\nexport function getBooleanFromEnv(key: string): boolean {\n const raw = process.env[key]?.trim().toLowerCase();\n if (raw == null || raw === '') {\n // NOTE: falling back to `false` instead of `undefined` as required by the specification.\n // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary\n // normalizations in the consuming code.\n return false;\n }\n if (raw === 'true') {\n return true;\n } else if (raw === 'false') {\n return false;\n } else {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`\n );\n return false;\n }\n}\n\n/**\n * Retrieves a list of strings from an environment variable.\n * - Uses ',' as the delimiter.\n * - Trims leading and trailing whitespace from each entry.\n * - Excludes empty entries.\n * - Returns `undefined` if the environment variable is empty or contains only whitespace.\n * - Returns an empty array if all entries are empty or whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string[] | undefined} - The list of strings or `undefined`.\n */\nexport function getStringListFromEnv(key: string): string[] | undefined {\n return getStringFromEnv(key)\n ?.split(',')\n .map(v => v.trim())\n .filter(s => s !== '');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\n\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../../version';\nimport {\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport {\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance: { now(): number; readonly timeOrigin: number } =\n performance;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < performance.timeOrigin) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototypeOf = Object.getPrototypeOf;\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (\n typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString\n );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n tag = value[symToStringTag as any];\n let unmasked = false;\n\n try {\n value[symToStringTag as any] = undefined;\n unmasked = true;\n } catch {\n // silence\n }\n\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag as any] = tag;\n } else {\n delete value[symToStringTag as any];\n }\n }\n return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n return nativeObjectToString.call(value);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n private _callback: T;\n private _that: This;\n\n constructor(callback: T, that: This) {\n this._callback = callback;\n this._that = that;\n }\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport type { IOtlpResponseHandler } from './response-handler';\n\nfunction isPartialSuccessResponse(\n response: unknown\n): response is { partialSuccess: never } {\n return Object.prototype.hasOwnProperty.call(response, 'partialSuccess');\n}\n\n/**\n * Default response handler that logs a partial success to the console.\n */\nexport function createLoggingPartialSuccessResponseHandler<\n T,\n>(): IOtlpResponseHandler<T> {\n return {\n handleResponse(response: T) {\n // Partial success MUST never be an empty object according the specification\n // see https://opentelemetry.io/docs/specs/otlp/#partial-success\n if (\n response == null ||\n !isPartialSuccessResponse(response) ||\n response.partialSuccess == null ||\n Object.keys(response.partialSuccess).length === 0\n ) {\n return;\n }\n diag.warn(\n 'Received Partial Success response:',\n JSON.stringify(response.partialSuccess)\n );\n },\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport type { IExporterTransport } from './exporter-transport';\nimport type { IExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { OTLPExporterError } from './types';\nimport type { IOtlpResponseHandler } from './response-handler';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport type { DiagLogger } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Internally shared export logic for OTLP.\n */\nexport interface IOtlpExportDelegate<Internal> {\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void;\n forceFlush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nclass OTLPExportDelegate<Internal, Response>\n implements IOtlpExportDelegate<Internal>\n{\n private _diagLogger: DiagLogger;\n private _transport: IExporterTransport;\n private _serializer: ISerializer<Internal, Response>;\n private _responseHandler: IOtlpResponseHandler<Response>;\n private _promiseQueue: IExportPromiseHandler;\n private _timeout: number;\n\n constructor(\n transport: IExporterTransport,\n serializer: ISerializer<Internal, Response>,\n responseHandler: IOtlpResponseHandler<Response>,\n promiseQueue: IExportPromiseHandler,\n timeout: number\n ) {\n this._transport = transport;\n this._serializer = serializer;\n this._responseHandler = responseHandler;\n this._promiseQueue = promiseQueue;\n this._timeout = timeout;\n this._diagLogger = diag.createComponentLogger({\n namespace: 'OTLPExportDelegate',\n });\n }\n\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._diagLogger.debug('items to be sent', internalRepresentation);\n\n // don't do any work if too many exports are in progress.\n if (this._promiseQueue.hasReachedLimit()) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Concurrent export limit reached'),\n });\n return;\n }\n\n const serializedRequest = this._serializer.serializeRequest(\n internalRepresentation\n );\n\n if (serializedRequest == null) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Nothing to send'),\n });\n return;\n }\n\n this._promiseQueue.pushPromise(\n this._transport.send(serializedRequest, this._timeout).then(\n response => {\n if (response.status === 'success') {\n if (response.data != null) {\n try {\n this._responseHandler.handleResponse(\n this._serializer.deserializeResponse(response.data)\n );\n } catch (e) {\n this._diagLogger.warn(\n 'Export succeeded but could not deserialize response - is the response specification compliant?',\n e,\n response.data\n );\n }\n }\n // No matter the response, we can consider the export still successful.\n resultCallback({\n code: ExportResultCode.SUCCESS,\n });\n return;\n } else if (response.status === 'failure' && response.error) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: response.error,\n });\n return;\n } else if (response.status === 'retryable') {\n resultCallback({\n code: ExportResultCode.FAILED,\n error:\n response.error ??\n new OTLPExporterError('Export failed with retryable status'),\n });\n } else {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new OTLPExporterError('Export failed with unknown error'),\n });\n }\n },\n reason =>\n resultCallback({\n code: ExportResultCode.FAILED,\n error: reason,\n })\n )\n );\n }\n\n forceFlush(): Promise<void> {\n return this._promiseQueue.awaitAll();\n }\n\n async shutdown(): Promise<void> {\n this._diagLogger.debug('shutdown started');\n await this.forceFlush();\n this._transport.shutdown();\n }\n}\n\n/**\n * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all\n * signals.\n */\nexport function createOtlpExportDelegate<Internal, Response>(\n components: {\n transport: IExporterTransport;\n serializer: ISerializer<Internal, Response>;\n promiseHandler: IExportPromiseHandler;\n },\n settings: { timeout: number }\n): IOtlpExportDelegate<Internal> {\n return new OTLPExportDelegate(\n components.transport,\n components.serializer,\n createLoggingPartialSuccessResponseHandler(),\n components.promiseHandler,\n settings.timeout\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n IAnyValue,\n IInstrumentationScope,\n IKeyValue,\n Resource,\n} from './internal-types';\nimport type { Attributes } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource as ISdkResource } from '@opentelemetry/resources';\nimport type { Encoder } from './utils';\n\nexport function createResource(\n resource: ISdkResource,\n encoder: Encoder\n): Resource {\n const result: Resource = {\n attributes: toAttributes(resource.attributes, encoder),\n droppedAttributesCount: 0,\n };\n\n const schemaUrl = resource.schemaUrl;\n if (schemaUrl && schemaUrl !== '') result.schemaUrl = schemaUrl;\n\n return result;\n}\n\nexport function createInstrumentationScope(\n scope: InstrumentationScope\n): IInstrumentationScope {\n return {\n name: scope.name,\n version: scope.version,\n };\n}\n\nexport function toAttributes(\n attributes: Attributes,\n encoder: Encoder\n): IKeyValue[] {\n return Object.keys(attributes).map(key =>\n toKeyValue(key, attributes[key], encoder)\n );\n}\n\nexport function toKeyValue(\n key: string,\n value: unknown,\n encoder: Encoder\n): IKeyValue {\n return {\n key: key,\n value: toAnyValue(value, encoder),\n };\n}\n\nexport function toAnyValue(value: unknown, encoder: Encoder): IAnyValue {\n const t = typeof value;\n if (t === 'string') return { stringValue: value as string };\n if (t === 'number') {\n if (!Number.isInteger(value)) return { doubleValue: value as number };\n return { intValue: value as number };\n }\n if (t === 'boolean') return { boolValue: value as boolean };\n if (value instanceof Uint8Array)\n return { bytesValue: encoder.encodeUint8Array(value) };\n if (Array.isArray(value)) {\n const values: IAnyValue[] = new Array(value.length);\n for (let i = 0; i < value.length; i++) {\n values[i] = toAnyValue(value[i], encoder);\n }\n return { arrayValue: { values } };\n }\n if (t === 'object' && value != null) {\n const keys = Object.keys(value);\n const values: IKeyValue[] = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n values[i] = {\n key: keys[i],\n value: toAnyValue((value as Record<string, unknown>)[keys[i]], encoder),\n };\n }\n return { kvlistValue: { values } };\n }\n\n return {};\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Fixed64, LongBits } from './internal-types';\nimport type { HrTime } from '@opentelemetry/api';\nimport { hrTimeToNanoseconds } from '@opentelemetry/core';\nimport { hexToBinary } from './hex-to-binary';\n\nexport function hrTimeToNanos(hrTime: HrTime): bigint {\n const NANOSECONDS = BigInt(1_000_000_000);\n return (\n BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))\n );\n}\n\nexport function toLongBits(value: bigint): LongBits {\n const low = Number(BigInt.asUintN(32, value));\n const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n return { low, high };\n}\n\nexport function encodeAsLongBits(hrTime: HrTime): LongBits {\n const nanos = hrTimeToNanos(hrTime);\n return toLongBits(nanos);\n}\n\nexport function encodeAsString(hrTime: HrTime): string {\n const nanos = hrTimeToNanos(hrTime);\n return nanos.toString();\n}\n\nconst encodeTimestamp =\n typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\n\nexport type HrTimeEncodeFunction = (hrTime: HrTime) => Fixed64;\nexport type SpanContextEncodeFunction = (\n spanContext: string\n) => string | Uint8Array;\nexport type OptionalSpanContextEncodeFunction = (\n spanContext: string | undefined\n) => string | Uint8Array | undefined;\nexport type Uint8ArrayEncodeFunction = (\n value: Uint8Array\n) => string | Uint8Array;\n\nexport interface Encoder {\n encodeHrTime: HrTimeEncodeFunction;\n encodeSpanContext: SpanContextEncodeFunction;\n encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\n encodeUint8Array: Uint8ArrayEncodeFunction;\n}\n\nfunction identity<T>(value: T): T {\n return value;\n}\n\nfunction optionalHexToBinary(str: string | undefined): Uint8Array | undefined {\n if (str === undefined) return undefined;\n return hexToBinary(str);\n}\n\n/**\n * Encoder for protobuf format.\n * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is.\n */\nexport const PROTOBUF_ENCODER: Encoder = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n encodeUint8Array: identity,\n};\n\n/**\n * Encoder for JSON format.\n * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array.\n */\nexport const JSON_ENCODER: Encoder = {\n encodeHrTime: encodeTimestamp,\n encodeSpanContext: identity,\n encodeOptionalSpanContext: identity,\n encodeUint8Array: (bytes: Uint8Array): string => {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n\n // implementation note: not using spread operator and passing to\n // btoa to avoid stack overflow on large Uint8Arrays\n const chars = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n chars[i] = String.fromCharCode(bytes[i]);\n }\n return btoa(chars.join(''));\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nlet serviceName: string | undefined;\n\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName(): string {\n if (serviceName === undefined) {\n try {\n const argv0 = globalThis.process.argv0;\n serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n } catch {\n serviceName = 'unknown_service';\n }\n }\n return serviceName;\n}\n\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache(): void {\n serviceName = undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n return (\n val !== null &&\n typeof val === 'object' &&\n typeof (val as Partial<PromiseLike<R>>).then === 'function'\n );\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport type {\n DetectedResource,\n DetectedResourceAttributes,\n MaybePromise,\n RawResourceAttribute,\n ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n private _rawAttributes: RawResourceAttribute[];\n private _asyncAttributesPending = false;\n private _schemaUrl?: string;\n\n private _memoizedAttributes?: Attributes;\n\n static FromAttributeList(\n attributes: [string, MaybePromise<AttributeValue | undefined>][],\n options?: ResourceOptions\n ): Resource {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource: DetectedResource,\n options?: ResourceOptions\n ) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n\n return [k, v];\n });\n\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n\n public get asyncAttributesPending(): boolean {\n return this._asyncAttributesPending;\n }\n\n public async waitForAsyncAttributes(): Promise<void> {\n if (!this.asyncAttributesPending) {\n return;\n }\n\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n\n this._asyncAttributesPending = false;\n }\n\n public get attributes(): Attributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n\n const attrs: Attributes = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n\n return attrs;\n }\n\n public getRawAttributes(): RawResourceAttribute[] {\n return this._rawAttributes;\n }\n\n public get schemaUrl(): string | undefined {\n return this._schemaUrl;\n }\n\n public merge(resource: Resource | null): Resource {\n if (resource == null) return this;\n\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n\n return ResourceImpl.FromAttributeList(\n [...resource.getRawAttributes(), ...this.getRawAttributes()],\n mergedOptions\n );\n }\n}\n\nexport function resourceFromAttributes(\n attributes: DetectedResourceAttributes,\n options?: ResourceOptions\n): Resource {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n detectedResource: DetectedResource,\n options?: ResourceOptions\n): Resource {\n return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\n\nfunction guardedRawAttributes(\n attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug(\n 'promise rejection for resource attribute: %s - %s',\n k,\n err\n );\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n\n diag.warn(\n 'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n schemaUrl\n );\n\n return undefined;\n}\n\nfunction mergeSchemaUrl(\n old: Resource,\n updating: Resource | null\n): string | undefined {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty =\n updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n\n diag.warn(\n 'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n oldSchemaUrl,\n updatingSchemaUrl\n );\n\n return undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Link } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport type { Encoder } from '../common/utils';\nimport {\n createInstrumentationScope,\n createResource,\n toAttributes,\n} from '../common/internal';\nimport type {\n EStatusCode,\n IEvent,\n IExportTraceServiceRequest,\n ILink,\n IResourceSpans,\n IScopeSpans,\n ISpan,\n} from './internal-types';\n\n// Span flags constants matching the OTLP specification\nconst SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100;\nconst SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200;\n\n/**\n * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags\n * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.\n */\nfunction buildSpanFlagsFrom(traceFlags: number, isRemote?: boolean): number {\n // low 8 bits are W3C TraceFlags (e.g., sampled)\n let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;\n if (isRemote) {\n flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;\n }\n return flags;\n}\n\nexport function sdkSpanToOtlpSpan(span: ReadableSpan, encoder: Encoder): ISpan {\n const ctx = span.spanContext();\n const status = span.status;\n const parentSpanId = span.parentSpanContext?.spanId\n ? encoder.encodeSpanContext(span.parentSpanContext?.spanId)\n : undefined;\n return {\n traceId: encoder.encodeSpanContext(ctx.traceId),\n spanId: encoder.encodeSpanContext(ctx.spanId),\n parentSpanId: parentSpanId,\n traceState: ctx.traceState?.serialize(),\n name: span.name,\n // Span kind is offset by 1 because the API does not define a value for unset\n kind: span.kind == null ? 0 : span.kind + 1,\n startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n attributes: toAttributes(span.attributes, encoder),\n droppedAttributesCount: span.droppedAttributesCount,\n events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n droppedEventsCount: span.droppedEventsCount,\n status: {\n // API and proto enums share the same values\n code: status.code as unknown as EStatusCode,\n message: status.message,\n },\n links: span.links.map(link => toOtlpLink(link, encoder)),\n droppedLinksCount: span.droppedLinksCount,\n flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote),\n };\n}\n\nexport function toOtlpLink(link: Link, encoder: Encoder): ILink {\n return {\n attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],\n spanId: encoder.encodeSpanContext(link.context.spanId),\n traceId: encoder.encodeSpanContext(link.context.traceId),\n traceState: link.context.traceState?.serialize(),\n droppedAttributesCount: link.droppedAttributesCount || 0,\n flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote),\n };\n}\n\nexport function toOtlpSpanEvent(\n timedEvent: TimedEvent,\n encoder: Encoder\n): IEvent {\n return {\n attributes: timedEvent.attributes\n ? toAttributes(timedEvent.attributes, encoder)\n : [],\n name: timedEvent.name,\n timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n };\n}\n\nexport function createExportTraceServiceRequest(\n spans: ReadableSpan[],\n encoder: Encoder\n): IExportTraceServiceRequest {\n return {\n resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n };\n}\n\nfunction createResourceMap(readableSpans: ReadableSpan[]) {\n const resourceMap: Map<Resource, Map<string, ReadableSpan[]>> = new Map();\n for (const record of readableSpans) {\n let ilsMap = resourceMap.get(record.resource);\n\n if (!ilsMap) {\n ilsMap = new Map();\n resourceMap.set(record.resource, ilsMap);\n }\n\n // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n const instrumentationScopeKey = `${record.instrumentationScope.name}@${\n record.instrumentationScope.version || ''\n }:${record.instrumentationScope.schemaUrl || ''}`;\n let records = ilsMap.get(instrumentationScopeKey);\n\n if (!records) {\n records = [];\n ilsMap.set(instrumentationScopeKey, records);\n }\n\n records.push(record);\n }\n\n return resourceMap;\n}\n\nfunction spanRecordsToResourceSpans(\n readableSpans: ReadableSpan[],\n encoder: Encoder\n): IResourceSpans[] {\n const resourceMap = createResourceMap(readableSpans);\n const out: IResourceSpans[] = [];\n\n const entryIterator = resourceMap.entries();\n let entry = entryIterator.next();\n while (!entry.done) {\n const [resource, ilmMap] = entry.value;\n const scopeResourceSpans: IScopeSpans[] = [];\n const ilmIterator = ilmMap.values();\n let ilmEntry = ilmIterator.next();\n while (!ilmEntry.done) {\n const scopeSpans = ilmEntry.value;\n if (scopeSpans.length > 0) {\n const spans = scopeSpans.map(readableSpan =>\n sdkSpanToOtlpSpan(readableSpan, encoder)\n );\n\n scopeResourceSpans.push({\n scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),\n spans: spans,\n schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl,\n });\n }\n ilmEntry = ilmIterator.next();\n }\n const processedResource = createResource(resource, encoder);\n const transformedSpans: IResourceSpans = {\n resource: processedResource,\n scopeSpans: scopeResourceSpans,\n schemaUrl: processedResource.schemaUrl,\n };\n\n out.push(transformedSpans);\n entry = entryIterator.next();\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { ISerializer } from '../../i-serializer';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport type { IExportTraceServiceResponse } from '../export-response';\nimport { createExportTraceServiceRequest } from '../internal';\nimport { JSON_ENCODER } from '../../common/utils';\n\nexport const JsonTraceSerializer: ISerializer<\n ReadableSpan[],\n IExportTraceServiceResponse\n> = {\n serializeRequest: (arg: ReadableSpan[]) => {\n const request = createExportTraceServiceRequest(arg, JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportTraceServiceResponse;\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Parses headers from config leaving only those that have defined values\n * @param partialHeaders\n */\nexport function validateAndNormalizeHeaders(\n partialHeaders: Record<string, string> | undefined\n): Record<string, string> {\n const headers: Record<string, string> = {};\n Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {\n if (typeof value !== 'undefined') {\n headers[key] = String(value);\n } else {\n diag.warn(\n `Header \"${key}\" has invalid value (${value}) and will be ignored`\n );\n }\n });\n return headers;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport {\n getSharedConfigurationDefaults,\n mergeOtlpSharedConfigurationWithDefaults,\n} from './shared-configuration';\nimport { validateAndNormalizeHeaders } from '../util';\n\nexport type HeadersFactory = () => Promise<Record<string, string>>;\n\nexport interface OtlpHttpConfiguration extends OtlpSharedConfiguration {\n url: string;\n headers: HeadersFactory;\n}\n\nfunction mergeHeaders(\n userProvidedHeaders: HeadersFactory | undefined | null,\n fallbackHeaders: HeadersFactory | undefined | null,\n defaultHeaders: HeadersFactory\n): HeadersFactory {\n return async () => {\n const requiredHeaders = {\n ...(await defaultHeaders()),\n };\n const headers = {};\n\n // add fallback ones first\n if (fallbackHeaders != null) {\n Object.assign(headers, await fallbackHeaders());\n }\n\n // override with user-provided ones\n if (userProvidedHeaders != null) {\n Object.assign(\n headers,\n validateAndNormalizeHeaders(await userProvidedHeaders())\n );\n }\n\n // override required ones.\n return Object.assign(headers, requiredHeaders);\n };\n}\n\nfunction validateUserProvidedUrl(url: string | undefined): string | undefined {\n if (url == null) {\n return undefined;\n }\n try {\n // NOTE: In non-browser environments, `globalThis.location` will be `undefined`.\n const base = globalThis.location?.href;\n return new URL(url, base).href;\n } catch {\n throw new Error(\n `Configuration: Could not parse user-provided export URL: '${url}'`\n );\n }\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpHttpConfiguration>,\n defaultConfiguration: OtlpHttpConfiguration\n): OtlpHttpConfiguration {\n return {\n ...mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n headers: mergeHeaders(\n userProvidedConfiguration.headers,\n fallbackConfiguration.headers,\n defaultConfiguration.headers\n ),\n url:\n validateUserProvidedUrl(userProvidedConfiguration.url) ??\n fallbackConfiguration.url ??\n defaultConfiguration.url,\n };\n}\n\nexport function getHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpHttpConfiguration {\n return {\n ...getSharedConfigurationDefaults(),\n headers: async () => requiredHeaders,\n url: 'http://localhost:4318/' + signalResourcePath,\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OtlpHttpConfiguration } from './otlp-http-configuration';\nimport {\n getHttpConfigurationDefaults,\n mergeOtlpHttpConfigurationWithDefaults,\n} from './otlp-http-configuration';\n\n// NOTE: do not change these imports to be actual imports, otherwise they WILL break `@opentelemetry/instrumentation-http`\nimport type * as http from 'http';\nimport type * as https from 'https';\n\nexport type HttpAgentFactory = (\n protocol: string\n) => http.Agent | https.Agent | Promise<http.Agent> | Promise<https.Agent>;\n\nexport interface OtlpNodeHttpConfiguration extends OtlpHttpConfiguration {\n /**\n * Factory function for creating agents.\n *\n * @remarks\n * Prefer using {@link httpAgentFactoryFromOptions} over manually writing a factory function wherever possible.\n * If using a factory function (`HttpAgentFactory`), **do not import `http.Agent` or `https.Agent`\n * statically at the top of the file**.\n * Instead, use dynamic `import()` or `require()` to load the module. This ensures that the `http` or `https`\n * module is not loaded before `@opentelemetry/instrumentation-http` can instrument it.\n */\n agentFactory: HttpAgentFactory;\n /**\n * User agent header string to be appended to the exporter's value as a prefix.\n * Availablie since v1.49.0 of the spec.\n * Ref: https://opentelemetry.io/docs/specs/otel/protocol/exporter/#user-agent\n */\n userAgent?: string;\n}\n\nexport function httpAgentFactoryFromOptions(\n options: http.AgentOptions | https.AgentOptions\n): HttpAgentFactory {\n return async protocol => {\n const isInsecure = protocol === 'http:';\n const module = isInsecure ? import('http') : import('https');\n const { Agent } = await module;\n\n if (isInsecure) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options\n const { ca, cert, key, ...insecureOptions } =\n options as https.AgentOptions;\n return new Agent(insecureOptions);\n }\n return new Agent(options);\n };\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpNodeHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpNodeHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpNodeHttpConfiguration>,\n defaultConfiguration: OtlpNodeHttpConfiguration\n): OtlpNodeHttpConfiguration {\n return {\n ...mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n agentFactory:\n userProvidedConfiguration.agentFactory ??\n fallbackConfiguration.agentFactory ??\n defaultConfiguration.agentFactory,\n userAgent: userProvidedConfiguration.userAgent,\n };\n}\n\nexport function getNodeHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpNodeHttpConfiguration {\n return {\n ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),\n agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport * as zlib from 'zlib';\nimport { Readable } from 'stream';\nimport type { ExportResponse } from '../export-response';\nimport {\n isExportHTTPErrorRetryable,\n parseRetryAfterToMills,\n} from '../is-export-retryable';\nimport { OTLPExporterError } from '../types';\nimport { VERSION } from '../version';\n\nconst DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION}`;\n\n/**\n * Sends data using http\n * @param request\n * @param url\n * @param headers\n * @param compression\n * @param userAgent\n * @param agent\n * @param data\n * @param timeoutMillis\n */\nexport function sendWithHttp(\n request: typeof https.request | typeof http.request,\n url: string,\n headers: Record<string, string>,\n compression: 'gzip' | 'none',\n userAgent: string | undefined,\n agent: http.Agent | https.Agent,\n data: Uint8Array,\n timeoutMillis: number\n): Promise<ExportResponse> {\n return new Promise<ExportResponse>(resolve => {\n const parsedUrl = new URL(url);\n\n if (userAgent) {\n headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`;\n } else {\n headers['User-Agent'] = DEFAULT_USER_AGENT;\n }\n\n const options: http.RequestOptions | https.RequestOptions = {\n hostname: parsedUrl.hostname,\n port: parsedUrl.port,\n path: parsedUrl.pathname,\n method: 'POST',\n headers,\n agent,\n };\n\n const req = request(options, (res: http.IncomingMessage) => {\n const responseData: Buffer[] = [];\n res.on('data', chunk => responseData.push(chunk));\n\n res.on('end', () => {\n if (res.statusCode && res.statusCode <= 299) {\n resolve({\n status: 'success',\n data: Buffer.concat(responseData),\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n const error = new OTLPExporterError(\n res.statusMessage,\n res.statusCode,\n Buffer.concat(responseData).toString()\n );\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n res.on('error', (error: Error) => {\n // Note: 'end' may still be emitted after 'error' on the same response object, since we're resolving a promise,\n // the first call to resolve() will determine the final state.\n if (res.statusCode && res.statusCode <= 299) {\n // If the response is successful but an error occurs while reading the response,\n // we consider it a success since the data has been sent successfully.\n resolve({\n status: 'success',\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n error: error,\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n });\n\n req.setTimeout(timeoutMillis, () => {\n req.destroy();\n resolve({\n status: 'retryable',\n error: new Error('Request timed out'),\n });\n });\n\n req.on('error', (error: Error) => {\n if (isHttpTransportNetworkErrorRetryable(error)) {\n resolve({\n status: 'retryable',\n error,\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n compressAndSend(req, compression, data, (error: Error) => {\n resolve({\n status: 'failure',\n error,\n });\n });\n });\n}\n\nexport function compressAndSend(\n req: http.ClientRequest,\n compression: 'gzip' | 'none',\n data: Uint8Array,\n onError: (error: Error) => void\n) {\n let dataStream = readableFromUint8Array(data);\n\n if (compression === 'gzip') {\n req.setHeader('Content-Encoding', 'gzip');\n dataStream = dataStream\n .on('error', onError)\n .pipe(zlib.createGzip())\n .on('error', onError);\n }\n\n dataStream.pipe(req).on('error', onError);\n}\n\nfunction readableFromUint8Array(buff: string | Uint8Array): Readable {\n const readable = new Readable();\n readable.push(buff);\n readable.push(null);\n\n return readable;\n}\n\nfunction isHttpTransportNetworkErrorRetryable(error: Error): boolean {\n const RETRYABLE_NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]);\n\n if ('code' in error && typeof error.code === 'string') {\n return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function isExportHTTPErrorRetryable(statusCode: number): boolean {\n return (\n statusCode === 429 ||\n statusCode === 502 ||\n statusCode === 503 ||\n statusCode === 504\n );\n}\n\nexport function parseRetryAfterToMills(\n retryAfter?: string | undefined | null\n): number | undefined {\n if (retryAfter == null) {\n return undefined;\n }\n\n const seconds = Number.parseInt(retryAfter, 10);\n if (Number.isInteger(seconds)) {\n return seconds > 0 ? seconds * 1000 : -1;\n }\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n const delay = new Date(retryAfter).getTime() - Date.now();\n\n if (delay >= 0) {\n return delay;\n }\n return 0;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.214.0';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type * as https from 'https';\nimport type * as http from 'http';\nimport type { ExportResponse } from '../export-response';\nimport type { IExporterTransport } from '../exporter-transport';\nimport { sendWithHttp } from './http-transport-utils';\nimport type { NodeHttpRequestParameters } from './node-http-transport-types';\n\ninterface Utils {\n agent: http.Agent | https.Agent;\n request: typeof http.request | typeof https.request;\n}\n\nclass HttpExporterTransport implements IExporterTransport {\n private _utils: Utils | null = null;\n private _parameters: NodeHttpRequestParameters;\n\n constructor(parameters: NodeHttpRequestParameters) {\n this._parameters = parameters;\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n const { agent, request } = await this._loadUtils();\n const headers = await this._parameters.headers();\n\n return sendWithHttp(\n request,\n this._parameters.url,\n headers,\n this._parameters.compression,\n this._parameters.userAgent,\n agent,\n data,\n timeoutMillis\n );\n }\n\n shutdown() {\n // intentionally left empty, nothing to do.\n }\n\n private async _loadUtils(): Promise<Utils> {\n let utils = this._utils;\n\n if (utils === null) {\n const protocol = new URL(this._parameters.url).protocol;\n const [agent, request] = await Promise.all([\n this._parameters.agentFactory(protocol),\n requestFunctionFactory(protocol),\n ]);\n utils = this._utils = { agent, request };\n }\n\n return utils;\n }\n}\n\nasync function requestFunctionFactory(\n protocol: string\n): Promise<typeof http.request | typeof https.request> {\n const module = protocol === 'http:' ? import('http') : import('https');\n const { request } = await module;\n return request;\n}\n\nexport function createHttpExporterTransport(\n parameters: NodeHttpRequestParameters\n): IExporterTransport {\n return new HttpExporterTransport(parameters);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IExporterTransport } from './exporter-transport';\nimport type { ExportResponse } from './export-response';\nimport { diag } from '@opentelemetry/api';\n\nconst MAX_ATTEMPTS = 5;\nconst INITIAL_BACKOFF = 1000;\nconst MAX_BACKOFF = 5000;\nconst BACKOFF_MULTIPLIER = 1.5;\nconst JITTER = 0.2;\n\n/**\n * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER]\n */\nfunction getJitter() {\n return Math.random() * (2 * JITTER) - JITTER;\n}\n\nclass RetryingTransport implements IExporterTransport {\n private _transport: IExporterTransport;\n\n constructor(transport: IExporterTransport) {\n this._transport = transport;\n }\n\n private retry(\n data: Uint8Array,\n timeoutMillis: number,\n inMillis: number\n ): Promise<ExportResponse> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n this._transport.send(data, timeoutMillis).then(resolve, reject);\n }, inMillis);\n });\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n let attempts = MAX_ATTEMPTS;\n let nextBackoff = INITIAL_BACKOFF;\n\n const deadline = Date.now() + timeoutMillis;\n let result = await this._transport.send(data, timeoutMillis);\n\n while (result.status === 'retryable' && attempts > 0) {\n attempts--;\n\n // use maximum of computed backoff and 0 to avoid negative timeouts\n const backoff = Math.max(\n Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF),\n 0\n );\n nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;\n const retryInMillis = result.retryInMillis ?? backoff;\n\n // return when expected retry time is after the export deadline.\n const remainingTimeoutMillis = deadline - Date.now();\n if (retryInMillis > remainingTimeoutMillis) {\n diag.info(\n `Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(\n remainingTimeoutMillis\n )}ms, not retrying further.`\n );\n return result;\n }\n\n diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);\n result = await this.retry(data, remainingTimeoutMillis, retryInMillis);\n }\n\n if (result.status === 'success') {\n diag.verbose(\n `Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`\n );\n } else if (result.status === 'retryable') {\n diag.info(\n `Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`\n );\n } else {\n diag.info(`Export failed with non-retryable error: ${result.error}`);\n }\n\n return result;\n }\n\n shutdown() {\n return this._transport.shutdown();\n }\n}\n\n/**\n * Creates an Exporter Transport that retries on 'retryable' response.\n */\nexport function createRetryingTransport(options: {\n // Underlying transport to wrap.\n transport: IExporterTransport;\n}): IExporterTransport {\n return new RetryingTransport(options.transport);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\nimport { createOtlpExportDelegate } from './otlp-export-delegate';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { createHttpExporterTransport } from './transport/http-exporter-transport';\nimport { createBoundedQueueExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { createRetryingTransport } from './retrying-transport';\nimport type { OtlpNodeHttpConfiguration } from './configuration/otlp-node-http-configuration';\n\nexport function createOtlpHttpExportDelegate<Internal, Response>(\n options: OtlpNodeHttpConfiguration,\n serializer: ISerializer<Internal, Response>\n): IOtlpExportDelegate<Internal> {\n return createOtlpExportDelegate(\n {\n transport: createRetryingTransport({\n transport: createHttpExporterTransport(options),\n }),\n serializer: serializer,\n promiseHandler: createBoundedQueueExportPromiseHandler(options),\n },\n { timeout: options.timeoutMillis }\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport { diag } from '@opentelemetry/api';\n\nfunction parseAndValidateTimeoutFromEnv(\n timeoutEnvVar: string\n): number | undefined {\n const envTimeout = getNumberFromEnv(timeoutEnvVar);\n if (envTimeout != null) {\n if (Number.isFinite(envTimeout) && envTimeout > 0) {\n return envTimeout;\n }\n diag.warn(\n `Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`\n );\n }\n\n return undefined;\n}\n\nfunction getTimeoutFromEnv(signalIdentifier: string) {\n const specificTimeout = parseAndValidateTimeoutFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`\n );\n const nonSpecificTimeout = parseAndValidateTimeoutFromEnv(\n 'OTEL_EXPORTER_OTLP_TIMEOUT'\n );\n\n return specificTimeout ?? nonSpecificTimeout;\n}\n\nfunction parseAndValidateCompressionFromEnv(\n compressionEnvVar: string\n): 'none' | 'gzip' | undefined {\n const compression = getStringFromEnv(compressionEnvVar)?.trim();\n\n if (compression == null || compression === 'none' || compression === 'gzip') {\n return compression;\n }\n\n diag.warn(\n `Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`\n );\n return undefined;\n}\n\nfunction getCompressionFromEnv(\n signalIdentifier: string\n): 'none' | 'gzip' | undefined {\n const specificCompression = parseAndValidateCompressionFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`\n );\n const nonSpecificCompression = parseAndValidateCompressionFromEnv(\n 'OTEL_EXPORTER_OTLP_COMPRESSION'\n );\n\n return specificCompression ?? nonSpecificCompression;\n}\n\nexport function getSharedConfigurationFromEnvironment(\n signalIdentifier: string\n): Partial<OtlpSharedConfiguration> {\n return {\n timeoutMillis: getTimeoutFromEnv(signalIdentifier),\n compression: getCompressionFromEnv(signalIdentifier),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getStringFromEnv, parseKeyPairsIntoRecord } from '@opentelemetry/core';\nimport { diag } from '@opentelemetry/api';\nimport { getSharedConfigurationFromEnvironment } from './shared-env-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { OtlpNodeHttpConfiguration } from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from './otlp-node-http-configuration';\n\nfunction getStaticHeadersFromEnv(\n signalIdentifier: string\n): Record<string, string> | undefined {\n const signalSpecificRawHeaders = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`\n );\n const nonSignalSpecificRawHeaders = getStringFromEnv(\n 'OTEL_EXPORTER_OTLP_HEADERS'\n );\n\n const signalSpecificHeaders = parseKeyPairsIntoRecord(\n signalSpecificRawHeaders\n );\n const nonSignalSpecificHeaders = parseKeyPairsIntoRecord(\n nonSignalSpecificRawHeaders\n );\n\n if (\n Object.keys(signalSpecificHeaders).length === 0 &&\n Object.keys(nonSignalSpecificHeaders).length === 0\n ) {\n return undefined;\n }\n\n // headers are combined instead of overwritten, with the specific headers taking precedence over\n // the non-specific ones.\n return Object.assign(\n {},\n parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders),\n parseKeyPairsIntoRecord(signalSpecificRawHeaders)\n );\n}\n\nfunction appendRootPathToUrlIfNeeded(url: string): string | undefined {\n try {\n const parsedUrl = new URL(url);\n // This will automatically append '/' if there's no root path.\n return parsedUrl.toString();\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n}\n\nfunction appendResourcePathToUrl(\n url: string,\n path: string\n): string | undefined {\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n\n if (!url.endsWith('/')) {\n url = url + '/';\n }\n url += path;\n\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`\n );\n return undefined;\n }\n\n return url;\n}\n\nfunction getNonSpecificUrlFromEnv(\n signalResourcePath: string\n): string | undefined {\n const envUrl = getStringFromEnv('OTEL_EXPORTER_OTLP_ENDPOINT');\n if (envUrl === undefined) {\n return undefined;\n }\n return appendResourcePathToUrl(envUrl, signalResourcePath);\n}\n\nfunction getSpecificUrlFromEnv(signalIdentifier: string): string | undefined {\n const envUrl = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`\n );\n if (envUrl === undefined) {\n return undefined;\n }\n return appendRootPathToUrlIfNeeded(envUrl);\n}\n\nfunction readFileFromEnv(\n signalSpecificEnvVar: string,\n nonSignalSpecificEnvVar: string,\n warningMessage: string\n): Buffer | undefined {\n const signalSpecificPath = getStringFromEnv(signalSpecificEnvVar);\n const nonSignalSpecificPath = getStringFromEnv(nonSignalSpecificEnvVar);\n const filePath = signalSpecificPath ?? nonSignalSpecificPath;\n\n if (filePath != null) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), filePath));\n } catch {\n diag.warn(warningMessage);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nfunction getClientCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE',\n 'Failed to read client certificate chain file'\n );\n}\n\nfunction getClientKeyFromEnv(signalIdentifier: string): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`,\n 'OTEL_EXPORTER_OTLP_CLIENT_KEY',\n 'Failed to read client certificate private key file'\n );\n}\n\nfunction getRootCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CERTIFICATE',\n 'Failed to read root certificate file'\n );\n}\n\n/**\n * Reads and returns configuration from the environment\n *\n * @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS)\n * @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs)\n */\nexport function getNodeHttpConfigurationFromEnvironment(\n signalIdentifier: string,\n signalResourcePath: string\n): Partial<OtlpNodeHttpConfiguration> {\n return {\n ...getSharedConfigurationFromEnvironment(signalIdentifier),\n url:\n getSpecificUrlFromEnv(signalIdentifier) ??\n getNonSpecificUrlFromEnv(signalResourcePath),\n headers: wrapStaticHeadersInFunction(\n getStaticHeadersFromEnv(signalIdentifier)\n ),\n agentFactory: httpAgentFactoryFromOptions({\n keepAlive: true,\n ca: getRootCertificateFromEnv(signalIdentifier),\n cert: getClientCertificateFromEnv(signalIdentifier),\n key: getClientKeyFromEnv(signalIdentifier),\n }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OTLPExporterConfigBase } from './legacy-base-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { HeadersFactory } from './otlp-http-configuration';\n\nexport function convertLegacyHeaders(\n config: OTLPExporterConfigBase\n): HeadersFactory | undefined {\n if (typeof config.headers === 'function') {\n return config.headers;\n }\n return wrapStaticHeadersInFunction(config.headers);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OTLPExporterNodeConfigBase } from './legacy-node-configuration';\nimport { diag } from '@opentelemetry/api';\nimport type {\n HttpAgentFactory,\n OtlpNodeHttpConfiguration,\n} from './otlp-node-http-configuration';\nimport {\n getNodeHttpConfigurationDefaults,\n mergeOtlpNodeHttpConfigurationWithDefaults,\n} from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from '../index-node-http';\nimport { getNodeHttpConfigurationFromEnvironment } from './otlp-node-http-env-configuration';\nimport { convertLegacyHeaders } from './convert-legacy-http-options';\n\nfunction convertLegacyAgentOptions(\n config: OTLPExporterNodeConfigBase\n): HttpAgentFactory | undefined {\n if (typeof config.httpAgentOptions === 'function') {\n return config.httpAgentOptions;\n }\n\n let legacy = config.httpAgentOptions;\n if (config.keepAlive != null) {\n legacy = { keepAlive: config.keepAlive, ...legacy };\n }\n\n if (legacy != null) {\n return httpAgentFactoryFromOptions(legacy);\n } else {\n return undefined;\n }\n}\n\n/**\n * @deprecated this will be removed in 2.0\n * @param config\n * @param signalIdentifier\n * @param signalResourcePath\n * @param requiredHeaders\n */\nexport function convertLegacyHttpOptions(\n config: OTLPExporterNodeConfigBase,\n signalIdentifier: string,\n signalResourcePath: string,\n requiredHeaders: Record<string, string>\n): OtlpNodeHttpConfiguration {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if ((config as any).metadata) {\n diag.warn('Metadata cannot be set when using http');\n }\n\n return mergeOtlpNodeHttpConfigurationWithDefaults(\n {\n url: config.url,\n headers: convertLegacyHeaders(config),\n concurrencyLimit: config.concurrencyLimit,\n timeoutMillis: config.timeoutMillis,\n compression: config.compression,\n agentFactory: convertLegacyAgentOptions(config),\n userAgent: config.userAgent,\n },\n getNodeHttpConfigurationFromEnvironment(\n signalIdentifier,\n signalResourcePath\n ),\n getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport { OTLPExporterBase } from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport {\n convertLegacyHttpOptions,\n createOtlpHttpExportDelegate,\n} from '@opentelemetry/otlp-exporter-base/node-http';\n\n/**\n * Collector Trace Exporter for Node\n */\nexport class OTLPTraceExporter\n extends OTLPExporterBase<ReadableSpan[]>\n implements SpanExporter\n{\n constructor(config: OTLPExporterNodeConfigBase = {}) {\n super(\n createOtlpHttpExportDelegate(\n convertLegacyHttpOptions(config, 'TRACES', 'v1/traces', {\n 'Content-Type': 'application/json',\n }),\n JsonTraceSerializer\n )\n );\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n}\n","import type { ResolvedConfig } from \"./env-detection.js\";\nimport type { SessionManager } from \"./session.js\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { BasicTracerProvider, BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { GlasstraceExporter, API_KEY_PENDING } from \"./enriching-exporter.js\";\nimport { getActiveConfig } from \"./init-client.js\";\n\n/** Module-level resolved API key, updated when the anon key resolves. */\nlet _resolvedApiKey: string = API_KEY_PENDING;\n\n/** Module-level reference to the active exporter for key-resolution notification. */\nlet _activeExporter: GlasstraceExporter | null = null;\n\n/** Registered shutdown handler, tracked so it can be removed on reset. */\nlet _shutdownHandler: ((signal: NodeJS.Signals) => void) | null = null;\n\n/**\n * Sets the resolved API key for OTel export authentication.\n * Called once the anonymous key or dev key is available.\n * @param key - The resolved API key (anonymous or developer).\n */\nexport function setResolvedApiKey(key: string): void {\n _resolvedApiKey = key;\n}\n\n/**\n * Returns the current resolved API key.\n * Returns the {@link API_KEY_PENDING} sentinel if the key has not yet resolved.\n */\nexport function getResolvedApiKey(): string {\n return _resolvedApiKey;\n}\n\n/**\n * Notifies the active exporter that the API key has transitioned from\n * \"pending\" to a resolved value. This triggers flushing of any buffered spans.\n */\nexport function notifyApiKeyResolved(): void {\n _activeExporter?.notifyKeyResolved();\n}\n\n/**\n * Resets OTel configuration state to initial values. For testing only.\n */\nexport function resetOtelConfigForTesting(): void {\n _resolvedApiKey = API_KEY_PENDING;\n _activeExporter = null;\n if (_shutdownHandler && typeof process !== \"undefined\") {\n process.removeListener(\"SIGTERM\", _shutdownHandler);\n process.removeListener(\"SIGINT\", _shutdownHandler);\n _shutdownHandler = null;\n }\n}\n\n/**\n * Dynamically imports an optional peer dependency at runtime.\n *\n * Uses `Function()` constructor to build the `import()` expression so that\n * bundlers (webpack, esbuild, turbopack) do not attempt to resolve the module\n * at compile time. This is intentional -- the SDK's peer dependencies are\n * optional, and static analysis would cause missing-module build errors for\n * users who have not installed them.\n *\n * **CSP note:** The `Function()` constructor is semantically equivalent to\n * `eval()` and will trigger Content Security Policy violations in environments\n * that disallow `unsafe-eval`. If your CSP blocks this, install the OTel peer\n * dependencies explicitly so they resolve via normal `import` statements, or\n * use the `@vercel/otel` path which does not rely on `tryImport` for its own\n * module.\n *\n * @param moduleId - The npm package name to import (e.g. \"@vercel/otel\").\n * @returns The module namespace object, or `null` if the module is not installed.\n */\nasync function tryImport(moduleId: string): Promise<Record<string, unknown> | null> {\n try {\n return await (Function(\"id\", \"return import(id)\")(moduleId) as Promise<Record<string, unknown>>);\n } catch {\n return null;\n }\n}\n\n/**\n * Registers process shutdown hooks that flush and shut down the OTel provider.\n * Uses `process.once()` to avoid stacking handlers on repeated calls.\n * Guarded for non-Node environments where `process` may not exist.\n */\nfunction registerShutdownHooks(provider: { shutdown: () => Promise<void> }): void {\n if (typeof process === \"undefined\" || typeof process.once !== \"function\") {\n return;\n }\n\n // Remove any previously registered handler before adding a new one\n if (_shutdownHandler) {\n process.removeListener(\"SIGTERM\", _shutdownHandler);\n process.removeListener(\"SIGINT\", _shutdownHandler);\n }\n\n let shutdownCalled = false;\n\n const shutdown = (signal: string) => {\n if (shutdownCalled) return;\n shutdownCalled = true;\n\n void provider.shutdown()\n .catch((err: unknown) => {\n console.warn(\n `[glasstrace] Error during OTel shutdown: ${err instanceof Error ? err.message : String(err)}`,\n );\n })\n .finally(() => {\n // Re-raise the signal so Node's default termination behavior proceeds.\n // Remove our listeners first to avoid re-entering this handler.\n process.removeListener(\"SIGTERM\", _shutdownHandler!);\n process.removeListener(\"SIGINT\", _shutdownHandler!);\n process.kill(process.pid, signal);\n });\n };\n\n const handler = (signal: NodeJS.Signals) => shutdown(signal);\n _shutdownHandler = handler;\n process.once(\"SIGTERM\", handler);\n process.once(\"SIGINT\", handler);\n}\n\n/**\n * Configures OpenTelemetry with the GlasstraceExporter.\n * The exporter handles all span enrichment (glasstrace.* attributes) at\n * export time, solving buffering, no-onEnding,\n * and session-ID-uses-resolved-key concerns.\n *\n * Attempts to use `@vercel/otel` first, falls back to bare OTel SDK.\n *\n * @param config - The resolved SDK configuration (endpoint, environment, etc.).\n * @param sessionManager - Provides session IDs for span enrichment.\n */\nexport async function configureOtel(\n config: ResolvedConfig,\n sessionManager: SessionManager,\n): Promise<void> {\n // Build OTLP exporter configuration\n const exporterUrl = `${config.endpoint}/v1/traces`;\n\n // OTLP exporter factory — always available since OTel is bundled.\n const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n new OTLPTraceExporter({ url, headers });\n\n // Create the GlasstraceExporter that enriches + buffers + delegates\n const glasstraceExporter = new GlasstraceExporter({\n getApiKey: getResolvedApiKey,\n sessionManager,\n getConfig: () => getActiveConfig(),\n environment: config.environment,\n endpointUrl: exporterUrl,\n createDelegate: createOtlpExporter,\n });\n _activeExporter = glasstraceExporter;\n\n // Try @vercel/otel first\n const vercelOtel = await tryImport(\"@vercel/otel\");\n if (vercelOtel && typeof vercelOtel.registerOTel === \"function\") {\n const otelConfig: Record<string, unknown> = {\n serviceName: \"glasstrace-sdk\",\n traceExporter: glasstraceExporter,\n };\n\n // Try @prisma/instrumentation\n const prismaModule = await tryImport(\"@prisma/instrumentation\");\n if (prismaModule) {\n const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n (new () => unknown) | undefined;\n if (PrismaInstrumentation) {\n otelConfig.instrumentations = [new PrismaInstrumentation()];\n }\n }\n\n (vercelOtel.registerOTel as (opts: Record<string, unknown>) => void)(otelConfig);\n return;\n }\n\n // Fallback: bare OTel SDK with BasicTracerProvider\n // Check for an existing OTel provider before registering.\n // If another tool (Datadog, Sentry, New Relic) already registered a provider,\n // skip Glasstrace registration to avoid silently breaking their tracing.\n // OTel wraps the global provider in a ProxyTracerProvider, so we probe for a\n // real provider by requesting a tracer and checking if it's a \"ProxyTracer\"\n // (the no-op default) or a real Tracer from a registered provider.\n const existingProvider = otelApi.trace.getTracerProvider();\n const probeTracer = existingProvider.getTracer(\"glasstrace-probe\");\n if (probeTracer.constructor.name !== \"ProxyTracer\") {\n console.warn(\n \"[glasstrace] An existing OpenTelemetry TracerProvider is already registered. \" +\n \"Glasstrace will not overwrite it. To use Glasstrace alongside another \" +\n \"tracing tool, add GlasstraceExporter as an additional span processor \" +\n \"on your existing provider.\",\n );\n _activeExporter = null;\n return;\n }\n\n // Use BatchSpanProcessor for production OTLP exports to avoid blocking\n // the event loop on every span.end() call.\n const processor = new BatchSpanProcessor(glasstraceExporter);\n const provider = new BasicTracerProvider({\n spanProcessors: [processor],\n });\n\n otelApi.trace.setGlobalTracerProvider(provider);\n registerShutdownHooks(provider);\n}\n","/**\n * Console error/warn capture module.\n *\n * When enabled, monkey-patches `console.error` and `console.warn` to record\n * their output as OTel span events on the currently active span. SDK-internal\n * log messages (prefixed with \"[glasstrace]\") are never captured.\n */\n\n/**\n * Module-level flag to suppress capture of SDK-internal log messages.\n * Set to `true` before calling `console.warn`/`console.error` from SDK code,\n * then reset to `false` immediately after.\n */\nexport let isGlasstraceLog = false;\n\n/** Saved reference to the original `console.error`. */\nlet originalError: typeof console.error | null = null;\n\n/** Saved reference to the original `console.warn`. */\nlet originalWarn: typeof console.warn | null = null;\n\n/** Whether the console capture is currently installed. */\nlet installed = false;\n\n/** Cached OTel API module reference, resolved at install time. */\nlet otelApi: typeof import(\"@opentelemetry/api\") | null = null;\n\n/**\n * Formats console arguments into a single string for span event attributes.\n * Uses best-effort serialization: strings pass through, Errors preserve their\n * stack trace, and other values are JSON-stringified with a String() fallback.\n */\nfunction formatArgs(args: unknown[]): string {\n return args\n .map((arg) => {\n if (typeof arg === \"string\") return arg;\n if (arg instanceof Error) return arg.stack ?? arg.message;\n try {\n return JSON.stringify(arg);\n } catch {\n return String(arg);\n }\n })\n .join(\" \");\n}\n\n/**\n * Returns `true` if the first argument is a string starting with \"[glasstrace]\".\n * Used to skip capture of SDK-internal log messages without requiring every\n * call site to set the `isGlasstraceLog` flag.\n */\nfunction isSdkMessage(args: unknown[]): boolean {\n return typeof args[0] === \"string\" && args[0].startsWith(\"[glasstrace]\");\n}\n\n/**\n * Installs console capture by replacing `console.error` and `console.warn`\n * with wrappers that record span events on the active OTel span.\n *\n * Must be called after OTel is configured so the API module is available.\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport async function installConsoleCapture(): Promise<void> {\n if (installed) return;\n\n // Resolve OTel API at install time via dynamic import so that:\n // 1. tsup inlines @opentelemetry/api into the bundle (it's in noExternal)\n // 2. vitest's vi.doMock can intercept this import for testing\n try {\n otelApi = await import(\"@opentelemetry/api\");\n } catch {\n otelApi = null;\n }\n\n originalError = console.error;\n originalWarn = console.warn;\n installed = true;\n\n console.error = (...args: unknown[]) => {\n // Always call the original first to preserve developer experience\n originalError!.apply(console, args);\n\n // Skip SDK-internal messages and flagged messages\n if (isGlasstraceLog || isSdkMessage(args)) return;\n\n if (otelApi) {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (span) {\n span.addEvent(\"console.error\", {\n \"console.message\": formatArgs(args),\n });\n }\n }\n };\n\n console.warn = (...args: unknown[]) => {\n originalWarn!.apply(console, args);\n\n if (isGlasstraceLog || isSdkMessage(args)) return;\n\n if (otelApi) {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (span) {\n span.addEvent(\"console.warn\", {\n \"console.message\": formatArgs(args),\n });\n }\n }\n };\n}\n\n/**\n * Restores the original `console.error` and `console.warn` methods.\n * Primarily intended for use in tests.\n */\nexport function uninstallConsoleCapture(): void {\n if (!installed) return;\n\n if (originalError) console.error = originalError;\n if (originalWarn) console.warn = originalWarn;\n\n originalError = null;\n originalWarn = null;\n otelApi = null;\n installed = false;\n}\n\n/**\n * Logs a message from SDK-internal code without triggering console capture.\n *\n * Use this helper in new SDK code instead of bare `console.warn(...)` calls\n * to prevent SDK log messages from being recorded as user-facing span events.\n *\n * @param level - The console log level to use.\n * @param message - The message to log.\n */\nexport function sdkLog(level: \"warn\" | \"info\" | \"error\", message: string): void {\n isGlasstraceLog = true;\n try {\n console[level](message);\n } finally {\n isGlasstraceLog = false;\n }\n}\n","declare const __SDK_VERSION__: string;\n\nimport type { GlasstraceOptions, AnonApiKey } from \"@glasstrace/protocol\";\nimport { resolveConfig, isProductionDisabled, isAnonymousMode } from \"./env-detection.js\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { SessionManager } from \"./session.js\";\nimport { getOrCreateAnonKey, readAnonKey } from \"./anon-key.js\";\nimport { loadCachedConfig, performInit, _setCurrentConfig, getActiveConfig } from \"./init-client.js\";\nimport { createDiscoveryHandler } from \"./discovery-endpoint.js\";\nimport { configureOtel, setResolvedApiKey, getResolvedApiKey, notifyApiKeyResolved, resetOtelConfigForTesting } from \"./otel-config.js\";\nimport { installConsoleCapture, uninstallConsoleCapture } from \"./console-capture.js\";\n\n/** Whether console capture has been installed in this registration cycle. */\nlet consoleCaptureInstalled = false;\n\n/** Module-level state tracking for the registered discovery handler. */\nlet discoveryHandler: ((request: Request) => Promise<Response | null>) | null = null;\n\n/** Module-level flag to prevent double registration. */\nlet isRegistered = false;\n\n/** Generation counter to invalidate stale background promises after reset. */\nlet registrationGeneration = 0;\n\n/**\n * The primary SDK entry point called by developers in their `instrumentation.ts`.\n * Orchestrates OTel setup, span processor, init client, anon key, and discovery endpoint.\n *\n * This function is synchronous and MUST NOT throw. The developer's server is never blocked.\n * Background work (key resolution, init call) happens via fire-and-forget promises.\n *\n * @param options - Optional SDK configuration. Environment variables are used as fallbacks.\n *\n * @example\n * ```ts\n * // instrumentation.ts\n * import { registerGlasstrace } from \"@glasstrace/sdk\";\n * registerGlasstrace(); // uses env vars\n * ```\n */\nexport function registerGlasstrace(options?: GlasstraceOptions): void {\n try {\n // Prevent double registration\n if (isRegistered) {\n return;\n }\n\n // Resolve config\n const config = resolveConfig(options);\n if (config.verbose) {\n console.info(\"[glasstrace] Config resolved.\");\n }\n\n // Production check\n if (isProductionDisabled(config)) {\n console.warn(\n \"[glasstrace] Disabled in production. Set GLASSTRACE_FORCE_ENABLE=true to override.\",\n );\n return;\n }\n if (config.verbose) {\n console.info(\"[glasstrace] Not production-disabled.\");\n }\n\n // Determine auth mode\n const anonymous = isAnonymousMode(config);\n let effectiveKey: string | undefined = config.apiKey;\n\n if (effectiveKey) {\n setResolvedApiKey(effectiveKey);\n }\n\n if (config.verbose) {\n console.info(\n `[glasstrace] Auth mode = ${anonymous ? \"anonymous\" : \"dev-key\"}.`,\n );\n }\n\n // Load cached config and apply to in-memory store\n const cachedInitResponse = loadCachedConfig();\n if (cachedInitResponse) {\n _setCurrentConfig(cachedInitResponse);\n }\n if (config.verbose) {\n console.info(\n `[glasstrace] Cached config ${cachedInitResponse ? \"loaded and applied\" : \"not found\"}.`,\n );\n }\n\n // Create SessionManager\n const sessionManager = new SessionManager();\n if (config.verbose) {\n console.info(\"[glasstrace] SessionManager created.\");\n }\n\n isRegistered = true;\n const currentGeneration = registrationGeneration;\n\n // Configure OTel IMMEDIATELY in all modes.\n // OTel is registered before the anon key resolves so that\n // spans are captured from cold start. GlasstraceExporter buffers spans\n // while the key is \"pending\" and flushes them once notifyApiKeyResolved()\n // is called after anonymous key resolution.\n // This is fire-and-forget -- OTel failure must not block init.\n void configureOtel(config, sessionManager).then(\n () => {\n // Check cached config for consoleErrors (may be stale or absent).\n // Re-checked after performInit completes with the authoritative config.\n maybeInstallConsoleCapture();\n\n if (config.verbose) {\n console.info(\"[glasstrace] OTel configured.\");\n }\n },\n (err: unknown) => {\n console.warn(\n `[glasstrace] Failed to configure OTel: ${err instanceof Error ? err.message : String(err)}`,\n );\n },\n );\n\n // Background work: anonymous key resolution, discovery endpoint, init\n if (anonymous) {\n // Register discovery endpoint IMMEDIATELY with async key resolution\n if (isDiscoveryEnabled(config)) {\n let resolvedAnonKey: AnonApiKey | null = null;\n const anonKeyPromise = getOrCreateAnonKey();\n\n // Use getResolvedApiKey() for session ID instead of\n // capturing the mutable effectiveKey closure variable.\n discoveryHandler = createDiscoveryHandler(\n async () => resolvedAnonKey,\n () => sessionManager.getSessionId(getResolvedApiKey()),\n );\n\n if (config.verbose) {\n console.info(\"[glasstrace] Discovery endpoint registered (key pending).\");\n }\n\n // Background: resolve key, update API key, then init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await anonKeyPromise;\n resolvedAnonKey = anonKey;\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n // Update the discovery handler to serve the resolved key\n // Use getResolvedApiKey() for canonical key state\n discoveryHandler = createDiscoveryHandler(\n () => Promise.resolve(anonKey),\n () => sessionManager.getSessionId(getResolvedApiKey()),\n );\n\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n\n await performInit(config, anonKey, __SDK_VERSION__);\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n } else {\n // Anonymous + non-dev: no discovery endpoint, just background init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await getOrCreateAnonKey();\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n\n await performInit(config, anonKey, __SDK_VERSION__);\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n } else {\n // Dev key mode: read straggler anon key, then fire init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n let anonKeyForInit: AnonApiKey | null = null;\n try {\n anonKeyForInit = await readAnonKey();\n } catch {\n // Expected when no prior anon key file exists on disk (first run).\n }\n\n if (currentGeneration !== registrationGeneration) return;\n\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n await performInit(config, anonKeyForInit, __SDK_VERSION__);\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n\n // Import graph (coverageMapEnabled) -- placeholder\n if (config.coverageMapEnabled && config.verbose) {\n console.info(\"[glasstrace] Import graph building skipped.\");\n }\n } catch (err) {\n console.warn(\n `[glasstrace] Registration failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Returns the registered discovery handler, or null if not registered.\n */\nexport function getDiscoveryHandler(): ((request: Request) => Promise<Response | null>) | null {\n return discoveryHandler;\n}\n\n/**\n * Checks the active config and installs console capture if enabled.\n * Idempotent — safe to call multiple times (after OTel config, after init).\n * This ensures console capture is installed whenever authoritative config\n * becomes available, whether from the file cache or the init response.\n */\nfunction maybeInstallConsoleCapture(): void {\n if (consoleCaptureInstalled) return;\n if (getActiveConfig().consoleErrors) {\n consoleCaptureInstalled = true;\n void installConsoleCapture();\n }\n}\n\n/**\n * Returns `true` if the discovery endpoint should be enabled for this environment.\n *\n * Tightened from \"not production\" to explicit development conditions:\n * 1. `GLASSTRACE_DISCOVERY_ENABLED=true` -- explicit override (highest priority)\n * 2. `GLASSTRACE_DISCOVERY_ENABLED=false` -- explicit disable (highest priority)\n * 3. `NODE_ENV` is `\"development\"` or unset, AND `VERCEL_ENV` is not `\"production\"`\n *\n * Environments like `staging`, `test`, and `ci` do not expose the discovery\n * endpoint by default, since it serves the anonymous API key over CORS.\n *\n * @param config - The resolved SDK configuration.\n * @returns Whether the discovery endpoint should be registered.\n */\nfunction isDiscoveryEnabled(config: ResolvedConfig): boolean {\n // Explicit flag takes precedence\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"true\") return true;\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"false\") return false;\n\n // Block production environments\n if (config.nodeEnv === \"production\") return false;\n if (config.vercelEnv === \"production\") return false;\n\n // Only allow in development or when NODE_ENV is unset\n if (config.nodeEnv === \"development\" || config.nodeEnv === undefined) return true;\n\n return false;\n}\n\n/**\n * Resets registration state. For testing only.\n */\nexport function _resetRegistrationForTesting(): void {\n isRegistered = false;\n discoveryHandler = null;\n consoleCaptureInstalled = false;\n registrationGeneration++;\n uninstallConsoleCapture();\n resetOtelConfigForTesting();\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as crypto from \"node:crypto\";\nimport { execSync } from \"node:child_process\";\nimport {\n SourceMapUploadResponseSchema,\n type SourceMapUploadResponse,\n} from \"@glasstrace/protocol\";\n\nexport interface SourceMapEntry {\n filePath: string;\n content: string;\n}\n\n/**\n * Recursively finds all .map files in the given build directory.\n * Returns relative paths and file contents.\n */\nexport async function collectSourceMaps(\n buildDir: string,\n): Promise<SourceMapEntry[]> {\n const results: SourceMapEntry[] = [];\n\n try {\n await walkDir(buildDir, buildDir, results);\n } catch {\n // Directory doesn't exist or is unreadable — return empty\n return [];\n }\n\n return results;\n}\n\nasync function walkDir(\n baseDir: string,\n currentDir: string,\n results: SourceMapEntry[],\n): Promise<void> {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(currentDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = path.join(currentDir, entry.name);\n\n if (entry.isDirectory()) {\n await walkDir(baseDir, fullPath, results);\n } else if (entry.isFile() && entry.name.endsWith(\".map\")) {\n try {\n const content = await fs.readFile(fullPath, \"utf-8\");\n const relativePath = path.relative(baseDir, fullPath).replace(/\\\\/g, \"/\");\n // Strip the trailing .map extension so the key matches the compiled\n // JS path that the runtime uses for stack-frame lookups (e.g.\n // \"static/chunks/main.js\" instead of \"static/chunks/main.js.map\").\n const compiledPath = relativePath.replace(/\\.map$/, \"\");\n results.push({ filePath: compiledPath, content });\n } catch {\n // Skip unreadable files\n }\n }\n }\n}\n\n/**\n * Computes a build hash for source map uploads.\n *\n * First tries `git rev-parse HEAD` to get the git commit SHA.\n * On failure, falls back to a deterministic content hash:\n * sort source map file paths alphabetically, concatenate each as\n * `{relativePath}\\n{fileLength}\\n{fileContent}`, then SHA-256 the result.\n */\nexport async function computeBuildHash(\n maps?: SourceMapEntry[],\n): Promise<string> {\n // Try git first\n try {\n const sha = execSync(\"git rev-parse HEAD\", { encoding: \"utf-8\" }).trim();\n if (sha) {\n return sha;\n }\n } catch {\n // Git not available, fall through to content hash\n }\n\n // Fallback: content-based hash\n const sortedMaps = [...(maps ?? [])].sort((a, b) =>\n a.filePath.localeCompare(b.filePath),\n );\n\n const hashInput = sortedMaps\n .map((m) => `${m.filePath}\\n${m.content.length}\\n${m.content}`)\n .join(\"\");\n\n const hash = crypto.createHash(\"sha256\").update(hashInput).digest(\"hex\");\n return hash;\n}\n\n/**\n * Uploads source maps to the ingestion API.\n *\n * POSTs to `{endpoint}/v1/source-maps` with the API key, build hash,\n * and file entries. Validates the response against SourceMapUploadResponseSchema.\n */\nexport async function uploadSourceMaps(\n apiKey: string,\n endpoint: string,\n buildHash: string,\n maps: SourceMapEntry[],\n): Promise<SourceMapUploadResponse> {\n const body = {\n apiKey,\n buildHash,\n files: maps.map((m) => ({\n filePath: m.filePath,\n sourceMap: m.content,\n })),\n };\n\n // Strip trailing slashes iteratively to avoid regex (CodeQL js/polynomial-redos).\n let baseUrl = endpoint;\n while (baseUrl.endsWith(\"/\")) {\n baseUrl = baseUrl.slice(0, -1);\n }\n const response = await fetch(`${baseUrl}/v1/source-maps`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n // Consume the response body to release the connection back to the pool.\n // Without this, the underlying TCP socket stays allocated until GC, which\n // causes connection pool exhaustion under sustained error conditions.\n // Wrapped in try-catch so a stream error doesn't mask the HTTP status error.\n try { await response.text(); } catch { /* body drain is best-effort */ }\n throw new Error(\n `Source map upload failed: ${String(response.status)} ${response.statusText}`,\n );\n }\n\n const json: unknown = await response.json();\n return SourceMapUploadResponseSchema.parse(json);\n}\n","import { collectSourceMaps, computeBuildHash, uploadSourceMaps } from \"./source-map-uploader.js\";\n\ntype NextConfig = Record<string, unknown>;\ntype WebpackConfigFn = (config: Record<string, unknown>, context: Record<string, unknown>) => Record<string, unknown>;\n\n/** Subset of the webpack context object passed by Next.js to the webpack config function. */\ninterface WebpackContext {\n isServer: boolean;\n dev: boolean;\n [key: string]: unknown;\n}\n\n/** Minimal webpack compiler shape for the afterEmit hook. */\ninterface WebpackCompiler {\n hooks?: {\n afterEmit?: {\n tapPromise?: (name: string, fn: (compilation: unknown) => Promise<void>) => void;\n };\n };\n}\n\n/**\n * Wraps the developer's Next.js config to enable source map generation\n * and upload .map files to the ingestion API at build time.\n *\n * The build NEVER fails because of Glasstrace — all errors are caught\n * and logged as warnings.\n *\n * @param nextConfig - The developer's existing Next.js configuration object.\n * @returns A new config object with source map generation and upload enabled.\n */\nexport function withGlasstraceConfig(nextConfig: NextConfig): NextConfig {\n // Handle null/undefined gracefully\n const config: NextConfig = nextConfig != null ? { ...nextConfig } : {};\n\n // Enable server-side source map generation for Glasstrace uploads.\n // Intentionally does NOT set productionBrowserSourceMaps — that exposes\n // full source code publicly via browser DevTools. Users who want public\n // browser source maps can set it explicitly in their Next.js config.\n\n // Enable server-side source maps (Next.js experimental feature)\n const existingExperimental = (config.experimental as Record<string, unknown>) ?? {};\n config.experimental = { ...existingExperimental, serverSourceMaps: true };\n\n // Capture distDir for source map collection (default: .next)\n const distDir = typeof config.distDir === \"string\" ? config.distDir : \".next\";\n\n // Capture existing webpack config if any\n const existingWebpack = config.webpack as WebpackConfigFn | undefined;\n\n // Register webpack config modifier\n config.webpack = (\n webpackConfig: Record<string, unknown>,\n context: Record<string, unknown>,\n ): Record<string, unknown> => {\n // Call existing webpack config first\n let result = webpackConfig;\n if (typeof existingWebpack === \"function\") {\n result = existingWebpack(webpackConfig, context);\n }\n\n const webpackContext = context as WebpackContext;\n\n // Only run source map upload on client-side production builds (not server, not dev)\n if (!webpackContext.isServer && webpackContext.dev === false) {\n // Register a plugin to collect and upload source maps after compilation\n const plugins = (result.plugins as Array<Record<string, unknown>>) ?? [];\n plugins.push({\n apply(compiler: Record<string, unknown>) {\n const typedCompiler = compiler as WebpackCompiler;\n if (typedCompiler.hooks?.afterEmit?.tapPromise) {\n typedCompiler.hooks.afterEmit.tapPromise(\n \"GlasstraceSourceMapUpload\",\n async () => {\n await handleSourceMapUpload(distDir);\n },\n );\n }\n },\n });\n result.plugins = plugins;\n }\n\n return result;\n };\n\n return config;\n}\n\n/**\n * Collects source map files from the build output directory and uploads\n * them to the Glasstrace ingestion API. Never throws — all errors are\n * caught and logged as warnings so the build is never blocked.\n *\n * Exported for testing only; not part of the public API.\n *\n * @param distDir - The Next.js build output directory (e.g. \".next\").\n */\nexport async function handleSourceMapUpload(distDir: string): Promise<void> {\n try {\n const apiKey = process.env.GLASSTRACE_API_KEY;\n const endpoint =\n process.env.GLASSTRACE_ENDPOINT ?? \"https://api.glasstrace.dev\";\n\n // Anonymous mode: skip upload\n if (!apiKey || apiKey.trim() === \"\") {\n console.info(\n \"[glasstrace] Source map upload skipped (no API key). Stack traces will show compiled locations.\",\n );\n return;\n }\n\n const maps = await collectSourceMaps(distDir);\n\n if (maps.length === 0) {\n console.info(\"[glasstrace] No source map files found. Skipping upload.\");\n return;\n }\n\n const buildHash = await computeBuildHash(maps);\n\n await uploadSourceMaps(apiKey, endpoint, buildHash, maps);\n console.info(\n `[glasstrace] Uploaded ${String(maps.length)} source map(s) for build ${buildHash}.`,\n );\n } catch (error: unknown) {\n // Build must NEVER fail because of Glasstrace\n const message =\n error instanceof Error ? error.message : \"Unknown error\";\n console.warn(\n `[glasstrace] Source map upload failed: ${message}. Build continues normally.`,\n );\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveConfig, isProductionDisabled } from \"../env-detection.js\";\n\n/**\n * Module-level flag ensuring the nudge fires at most once per process.\n */\nlet hasFired = false;\n\n/**\n * Strips control characters (except space) from a string to prevent\n * terminal escape sequence injection via error summaries written to stderr.\n */\nfunction sanitize(input: string): string {\n // eslint-disable-next-line no-control-regex\n return input.replace(/[\\x00-\\x1f\\x7f]/g, \"\");\n}\n\n/**\n * Shows a one-time stderr nudge when the SDK captures its first error\n * and the MCP connection marker file is absent.\n *\n * The nudge is suppressed when:\n * - It has already fired in this process\n * - The `.glasstrace/mcp-connected` marker file exists at the project root\n * - The environment is detected as production (and force-enable is off)\n *\n * Uses `process.stderr.write()` instead of `console.error()` to avoid\n * being captured by OpenTelemetry console instrumentation.\n */\nexport function maybeShowMcpNudge(errorSummary: string): void {\n if (hasFired) {\n return;\n }\n\n // Production check — suppress silently\n const config = resolveConfig();\n if (isProductionDisabled(config)) {\n return;\n }\n\n // Check for MCP connection marker file.\n // Guard process.cwd() — it throws ENOENT if the working directory has been removed.\n let markerExists = false;\n try {\n const markerPath = join(process.cwd(), \".glasstrace\", \"mcp-connected\");\n markerExists = existsSync(markerPath);\n } catch {\n // Permission denied, ENOENT from cwd(), or other filesystem error — treat as not connected\n markerExists = false;\n }\n\n if (markerExists) {\n return;\n }\n\n // Fire the nudge exactly once\n hasFired = true;\n\n const safe = sanitize(errorSummary);\n process.stderr.write(\n `[glasstrace] Error captured: ${safe}\\n` +\n ` Debug with AI: ask your agent \"What's the latest Glasstrace error?\"\\n` +\n ` Not connected? Run: npx glasstrace mcp add\\n`,\n );\n}\n","/**\n * Manual error capture API.\n *\n * Provides a simple function for developers to manually record errors\n * as span events, independent of the `consoleErrors` config flag.\n */\n\nimport * as otelApi from \"@opentelemetry/api\";\nimport { maybeShowMcpNudge } from \"./nudge/error-nudge.js\";\n\n/**\n * Records an error as a span event on the currently active OTel span.\n *\n * Works regardless of the `consoleErrors` configuration — this is an\n * explicit, opt-in API for manual error reporting. If no span is active\n * or OTel is not available, the call is silently ignored.\n *\n * On the first captured error, may display a one-time diagnostic nudge\n * to stderr if the MCP connection marker is absent (dev environments only).\n *\n * @param error - The error to capture. Accepts `Error` objects, strings, or any value.\n *\n * @example\n * ```ts\n * import { captureError } from \"@glasstrace/sdk\";\n *\n * try {\n * await riskyOperation();\n * } catch (err) {\n * captureError(err);\n * // handle error normally...\n * }\n * ```\n */\nexport function captureError(error: unknown): void {\n try {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (!span) return;\n\n const attributes: Record<string, string> = {\n \"error.message\": String(error),\n };\n\n if (error instanceof Error) {\n attributes[\"error.type\"] = error.constructor.name;\n }\n\n span.addEvent(\"glasstrace.error\", attributes);\n\n // Show one-time MCP connection nudge on first captured error\n maybeShowMcpNudge(String(error));\n } catch {\n // Silently ignore failures\n }\n}\n\n/**\n * Eagerly loads the OTel API module. Previously required for async resolution;\n * now a no-op since OTel is statically imported. Retained for test compatibility.\n *\n * @internal\n */\nexport async function _preloadOtelApi(): Promise<void> {\n // No-op: OTel API is now statically imported and always available.\n}\n\n/**\n * Resets internal state. For testing only.\n * @internal\n */\nexport function _resetCaptureErrorForTesting(): void {\n // No-op: OTel API is now statically imported and always available.\n // Kept for backward compatibility with existing tests.\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EAET,YAAY,MAAyB,SAAiB,OAAe;AACnE,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;ACCA,IAAM,mBAAmB;AAMlB,SAAS,cAAiC;AAC/C,SAAO;AAAA,IACL,oBAAoB,QAAQ,IAAI,oBAAoB,KAAK,KAAK;AAAA,IAC9D,yBAAyB,QAAQ,IAAI;AAAA,IACrC,gBAAgB,QAAQ,IAAI;AAAA,IAC5B,yBAAyB,QAAQ,IAAI;AAAA,IACrC,UAAU,QAAQ,IAAI;AAAA,IACtB,YAAY,QAAQ,IAAI;AAAA,EAC1B;AACF;AAMO,SAAS,cAAc,SAA6C;AACzE,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,aAAaC,MAAK,QAAQ,IAAI,GAAG,eAAe,eAAe;AACrE,mBAAe,WAAW,UAAU;AAAA,EACtC,QAAQ;AAEN,mBAAe;AAAA,EACjB;AAEA,MAAI,cAAc;AAChB;AAAA,EACF;AAGA,aAAW;AAEX,QAAM,OAAO,SAAS,YAAY;AAClC,UAAQ,OAAO;AAAA,IACb,gCAAgC,IAAI;AAAA;AAAA;AAAA;AAAA,EAGtC;AACF;;;AC/BO,SAAS,aAAa,OAAsB;AACjD,MAAI;AACF,UAAM,OAAe,MAAM,QAAgB,QAAQ,OAAO,CAAC;AAC3D,QAAI,CAAC,KAAM;AAEX,UAAM,aAAqC;AAAA,MACzC,iBAAiB,OAAO,KAAK;AAAA,IAC/B;AAEA,QAAI,iBAAiB,OAAO;AAC1B,iBAAW,YAAY,IAAI,MAAM,YAAY;AAAA,IAC/C;AAEA,SAAK,SAAS,oBAAoB,UAAU;AAG5C,sBAAkB,OAAO,KAAK,CAAC;AAAA,EACjC,QAAQ;AAAA,EAER;AACF;","names":["cachedPort","cachedPort","context","context","ExportResultCode","resolve","hrTime","hrTime","VERSION","VERSION","resolve","resolve","path","SamplingDecision","SamplingDecision","SamplingDecision","context","context","SamplingDecision","TracesSamplerValues","resolve","SamplingDecision","VERSION","VERSION","context","resolve","context","ForceFlushState","resolve","fs","path","context","join","join"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/env-detection.ts","../src/session.ts","../src/fetch-classifier.ts","../src/init-client.ts","../src/span-processor.ts","../src/enriching-exporter.ts","../src/discovery-endpoint.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/OTLPExporterBase.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/types.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/bounded-queue-export-promise-handler.ts","../../../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../../../node_modules/@opentelemetry/core/src/baggage/constants.ts","../../../node_modules/@opentelemetry/core/src/baggage/utils.ts","../../../node_modules/@opentelemetry/core/src/common/attributes.ts","../../../node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../../../node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../../../node_modules/@opentelemetry/core/src/platform/node/environment.ts","../../../node_modules/@opentelemetry/core/src/version.ts","../../../node_modules/@opentelemetry/semantic-conventions/src/stable_attributes.ts","../../../node_modules/@opentelemetry/core/src/semconv.ts","../../../node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../../../node_modules/@opentelemetry/core/src/platform/node/index.ts","../../../node_modules/@opentelemetry/core/src/common/time.ts","../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../../../node_modules/@opentelemetry/core/src/utils/lodash.merge.ts","../../../node_modules/@opentelemetry/core/src/utils/merge.ts","../../../node_modules/@opentelemetry/core/src/utils/promise.ts","../../../node_modules/@opentelemetry/core/src/utils/callback.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/logging-response-handler.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/common/utils.ts","../../../node_modules/@opentelemetry/resources/src/default-service-name.ts","../../../node_modules/@opentelemetry/resources/src/utils.ts","../../../node_modules/@opentelemetry/resources/src/ResourceImpl.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/internal.ts","../../../node_modules/@opentelemetry/otlp-transformer/src/trace/json/trace.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/util.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-transport-utils.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/is-export-retryable.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/version.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-exporter-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/retrying-transport.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/otlp-http-export-delegate.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-env-configuration.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-http-options.ts","../../../node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-node-http-options.ts","../../../node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/node/OTLPTraceExporter.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/enums.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Span.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/config.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/utility.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/RandomIdGenerator.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/semconv.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/TracerMetrics.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/version.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts","../../../node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts","../src/otel-config.ts","../src/console-capture.ts","../src/register.ts","../src/source-map-uploader.ts","../src/config-wrapper.ts","../src/nudge/error-nudge.ts","../src/capture-error.ts"],"sourcesContent":["import type { SdkDiagnosticCode } from \"@glasstrace/protocol\";\n\n/**\n * Internal SDK error class with a typed diagnostic code.\n * Caught at the boundary and converted to a log message + diagnostic entry.\n * Never thrown to the developer.\n */\nexport class SdkError extends Error {\n readonly code: SdkDiagnosticCode;\n\n constructor(code: SdkDiagnosticCode, message: string, cause?: Error) {\n super(message, { cause });\n this.name = \"SdkError\";\n this.code = code;\n }\n}\n","import type { GlasstraceEnvVars, GlasstraceOptions } from \"@glasstrace/protocol\";\n\n/**\n * Resolved configuration after merging explicit options with environment variables.\n */\nexport interface ResolvedConfig {\n apiKey: string | undefined;\n endpoint: string;\n forceEnable: boolean;\n verbose: boolean;\n environment: string | undefined;\n coverageMapEnabled: boolean;\n nodeEnv: string | undefined;\n vercelEnv: string | undefined;\n}\n\nconst DEFAULT_ENDPOINT = \"https://api.glasstrace.dev\";\n\n/**\n * Reads all recognized Glasstrace environment variables from process.env.\n * Returns undefined for any variable not set. Never throws.\n */\nexport function readEnvVars(): GlasstraceEnvVars {\n return {\n GLASSTRACE_API_KEY: process.env.GLASSTRACE_API_KEY?.trim() || undefined,\n GLASSTRACE_FORCE_ENABLE: process.env.GLASSTRACE_FORCE_ENABLE,\n GLASSTRACE_ENV: process.env.GLASSTRACE_ENV,\n GLASSTRACE_COVERAGE_MAP: process.env.GLASSTRACE_COVERAGE_MAP,\n NODE_ENV: process.env.NODE_ENV,\n VERCEL_ENV: process.env.VERCEL_ENV,\n };\n}\n\n/**\n * Merges explicit GlasstraceOptions with environment variables.\n * Explicit options take precedence over environment variables.\n */\nexport function resolveConfig(options?: GlasstraceOptions): ResolvedConfig {\n const env = readEnvVars();\n\n return {\n apiKey: options?.apiKey ?? env.GLASSTRACE_API_KEY,\n endpoint: options?.endpoint ?? DEFAULT_ENDPOINT,\n forceEnable: options?.forceEnable ?? env.GLASSTRACE_FORCE_ENABLE === \"true\",\n verbose: options?.verbose ?? false,\n environment: env.GLASSTRACE_ENV,\n coverageMapEnabled: env.GLASSTRACE_COVERAGE_MAP === \"true\",\n nodeEnv: env.NODE_ENV,\n vercelEnv: env.VERCEL_ENV,\n };\n}\n\n/**\n * Returns true when the SDK should be inactive (production detected without force-enable).\n * Logic order:\n * 1. forceEnable === true → return false (override)\n * 2. NODE_ENV === 'production' → return true\n * 3. VERCEL_ENV === 'production' → return true\n * 4. Otherwise → return false\n */\nexport function isProductionDisabled(config: ResolvedConfig): boolean {\n if (config.forceEnable) {\n return false;\n }\n if (config.nodeEnv === \"production\") {\n return true;\n }\n if (config.vercelEnv === \"production\") {\n return true;\n }\n return false;\n}\n\n/**\n * Returns true when no API key is configured (anonymous mode).\n * Treats undefined, empty string, whitespace-only, and gt_anon_* keys as anonymous.\n */\nexport function isAnonymousMode(config: ResolvedConfig): boolean {\n if (config.apiKey === undefined) {\n return true;\n }\n if (config.apiKey.trim() === \"\") {\n return true;\n }\n if (config.apiKey.startsWith(\"gt_anon_\")) {\n return true;\n }\n return false;\n}\n","import { createHash } from \"node:crypto\";\nimport { SessionIdSchema } from \"@glasstrace/protocol\";\nimport type { SessionId } from \"@glasstrace/protocol\";\n\nconst FOUR_HOURS_MS = 4 * 60 * 60 * 1000;\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedGlasstraceEnv: string | undefined = process.env.GLASSTRACE_ENV;\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedGlasstraceEnv = process.env.GLASSTRACE_ENV;\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Derives a deterministic session ID from the given inputs using SHA-256.\n * The hash is truncated to 16 hex characters and parsed through SessionIdSchema.\n *\n * @param apiKey - The project's API key (or anonymous placeholder).\n * @param origin - The origin string identifying the deployment environment.\n * @param date - UTC date as YYYY-MM-DD.\n * @param windowIndex - Zero-based index of the 4-hour activity window within the day.\n * @returns A 16-character hex SessionId.\n */\nexport function deriveSessionId(\n apiKey: string,\n origin: string,\n date: string,\n windowIndex: number,\n): SessionId {\n const input = JSON.stringify([apiKey, origin, date, windowIndex]);\n const hash = createHash(\"sha256\").update(input).digest(\"hex\").slice(0, 16);\n return SessionIdSchema.parse(hash);\n}\n\n/**\n * Returns the origin string for the current process.\n * If GLASSTRACE_ENV is set, returns that value.\n * Otherwise returns `localhost:{PORT}` (PORT defaults to 3000).\n *\n * @returns The origin string used as a session derivation input.\n */\nexport function getOrigin(): string {\n if (cachedGlasstraceEnv) {\n return cachedGlasstraceEnv;\n }\n return `localhost:${cachedPort}`;\n}\n\n/**\n * Returns the current UTC date as a YYYY-MM-DD string.\n *\n * @returns The UTC date formatted as \"YYYY-MM-DD\".\n */\nexport function getDateString(): string {\n const now = new Date();\n const year = now.getUTCFullYear();\n const month = String(now.getUTCMonth() + 1).padStart(2, \"0\");\n const day = String(now.getUTCDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n}\n\n/**\n * Tracks the current session state with 4-hour window tracking.\n * Instantiated once by the orchestrator.\n */\nexport class SessionManager {\n private windowIndex: number = 0;\n private lastActivityTimestamp: number = 0;\n private lastDate: string = \"\";\n private lastApiKey: string = \"\";\n private currentSessionId: SessionId | null = null;\n\n /**\n * Returns the current session ID, deriving a new one if:\n * - More than 4 hours have elapsed since last activity\n * - The UTC date has changed (resets window index to 0)\n * - The API key has changed (e.g., deferred anonymous key swap)\n * - This is the first call\n *\n * @param apiKey - The project's API key used in session derivation.\n * @returns The current or newly derived SessionId.\n */\n getSessionId(apiKey: string): SessionId {\n const now = Date.now();\n const currentDate = getDateString();\n const origin = getOrigin();\n\n const elapsed = now - this.lastActivityTimestamp;\n const dateChanged = currentDate !== this.lastDate;\n const apiKeyChanged = apiKey !== this.lastApiKey;\n\n if (dateChanged) {\n // New UTC day: reset window index\n this.windowIndex = 0;\n this.lastDate = currentDate;\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (apiKeyChanged) {\n // API key changed (e.g., anonymous key resolved): re-derive with same window\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n } else if (this.currentSessionId === null || elapsed > FOUR_HOURS_MS) {\n // First call or gap exceeding 4 hours: increment window\n if (this.currentSessionId !== null) {\n this.windowIndex++;\n }\n this.lastApiKey = apiKey;\n this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);\n this.lastDate = currentDate;\n }\n\n this.lastActivityTimestamp = now;\n return this.currentSessionId;\n }\n}\n","/**\n * The set of recognized fetch target categories.\n */\nexport type FetchTarget = \"supabase\" | \"stripe\" | \"internal\" | \"unknown\";\n\n/** Cached at module load to avoid reading process.env on every span. */\nlet cachedPort: string = process.env.PORT ?? \"3000\";\n\n/**\n * Re-reads cached environment variables. For testing only.\n */\nexport function _resetEnvCacheForTesting(): void {\n cachedPort = process.env.PORT ?? \"3000\";\n}\n\n/**\n * Classifies an outbound fetch target URL into a known category.\n * Classification is case-insensitive and based on the URL hostname.\n * Uses dot-boundary matching to avoid false positives (e.g. evilstripe.com).\n *\n * Returns one of: 'supabase', 'stripe', 'internal', or 'unknown'.\n */\nexport function classifyFetchTarget(url: string): FetchTarget {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return \"unknown\";\n }\n\n const hostname = parsed.hostname.toLowerCase();\n\n if (\n hostname === \"supabase.co\" ||\n hostname.endsWith(\".supabase.co\") ||\n hostname === \"supabase.in\" ||\n hostname.endsWith(\".supabase.in\")\n ) {\n return \"supabase\";\n }\n\n if (hostname === \"stripe.com\" || hostname.endsWith(\".stripe.com\")) {\n return \"stripe\";\n }\n\n const internalOrigin = `localhost:${cachedPort}`;\n const parsedPort = parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n const urlOrigin = `${hostname}:${parsedPort}`;\n\n if (urlOrigin === internalOrigin) {\n return \"internal\";\n }\n\n return \"unknown\";\n}\n","import { readFileSync } from \"node:fs\";\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n SdkInitResponseSchema,\n SdkCachedConfigSchema,\n DEFAULT_CAPTURE_CONFIG,\n} from \"@glasstrace/protocol\";\nimport type {\n SdkInitResponse,\n CaptureConfig,\n AnonApiKey,\n ImportGraphPayload,\n SdkHealthReport,\n SdkDiagnosticCode,\n} from \"@glasstrace/protocol\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\n\nconst GLASSTRACE_DIR = \".glasstrace\";\nconst CONFIG_FILE = \"config\";\nconst TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;\nconst INIT_TIMEOUT_MS = 10_000;\n\n/** In-memory config from the latest successful init response. */\nlet currentConfig: SdkInitResponse | null = null;\n\n/** Whether the next init call should be skipped (rate-limit backoff). */\nlet rateLimitBackoff = false;\n\n/**\n * Reads and validates a cached config file from `.glasstrace/config`.\n * Returns the parsed `SdkInitResponse` or `null` on any failure.\n */\nexport function loadCachedConfig(projectRoot?: string): SdkInitResponse | null {\n const root = projectRoot ?? process.cwd();\n const configPath = join(root, GLASSTRACE_DIR, CONFIG_FILE);\n\n try {\n // Use synchronous read for startup performance (this is called during init)\n const content = readFileSync(configPath, \"utf-8\");\n const parsed = JSON.parse(content);\n const cached = SdkCachedConfigSchema.parse(parsed);\n\n // Warn if cache is stale\n const age = Date.now() - cached.cachedAt;\n if (age > TWENTY_FOUR_HOURS_MS) {\n console.warn(\n `[glasstrace] Cached config is ${Math.round(age / 3600000)}h old. Will refresh on next init.`,\n );\n }\n\n // Parse the response through the schema\n const result = SdkInitResponseSchema.safeParse(cached.response);\n if (result.success) {\n return result.data;\n }\n\n console.warn(\"[glasstrace] Cached config failed validation. Using defaults.\");\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Persists the init response to `.glasstrace/config`.\n * On failure, logs a warning and continues.\n */\nexport async function saveCachedConfig(\n response: SdkInitResponse,\n projectRoot?: string,\n): Promise<void> {\n const root = projectRoot ?? process.cwd();\n const dirPath = join(root, GLASSTRACE_DIR);\n const configPath = join(dirPath, CONFIG_FILE);\n\n try {\n await mkdir(dirPath, { recursive: true });\n const cached = {\n response,\n cachedAt: Date.now(),\n };\n await writeFile(configPath, JSON.stringify(cached), \"utf-8\");\n } catch (err) {\n console.warn(\n `[glasstrace] Failed to cache config to ${configPath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Sends a POST request to `/v1/sdk/init`.\n * Validates the response against `SdkInitResponseSchema`.\n */\nexport async function sendInitRequest(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n importGraph?: ImportGraphPayload,\n healthReport?: SdkHealthReport,\n diagnostics?: Array<{ code: SdkDiagnosticCode; message: string; timestamp: number }>,\n signal?: AbortSignal,\n): Promise<SdkInitResponse> {\n // Determine the API key for auth. Use || (not ??) so empty strings\n // fall through to the anonymous key — defense in depth for DISC-467.\n const effectiveKey = config.apiKey || anonKey;\n if (!effectiveKey) {\n throw new Error(\"No API key available for init request\");\n }\n\n // Build the request payload\n const payload: Record<string, unknown> = {\n apiKey: effectiveKey,\n sdkVersion,\n };\n\n // Straggler linking: if dev key is set AND anonKey is provided\n if (config.apiKey && anonKey) {\n payload.anonKey = anonKey;\n }\n\n if (config.environment) {\n payload.environment = config.environment;\n }\n if (importGraph) {\n payload.importGraph = importGraph;\n }\n if (healthReport) {\n payload.healthReport = healthReport;\n }\n if (diagnostics) {\n payload.diagnostics = diagnostics;\n }\n\n const url = `${config.endpoint}/v1/sdk/init`;\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${effectiveKey}`,\n },\n body: JSON.stringify(payload),\n signal,\n });\n\n if (!response.ok) {\n // Consume the response body to release the connection back to the pool.\n // Without this, the underlying TCP socket stays allocated until GC, which\n // causes connection pool exhaustion under sustained error conditions.\n // Wrapped in try-catch so a stream error doesn't mask the HTTP status error.\n try { await response.text(); } catch { /* body drain is best-effort */ }\n const error = new Error(`Init request failed with status ${response.status}`);\n (error as unknown as Record<string, unknown>).status = response.status;\n throw error;\n }\n\n const body = await response.json();\n return SdkInitResponseSchema.parse(body);\n}\n\n/**\n * Orchestrates the full init flow: send request, update config, cache result.\n * This function MUST NOT throw.\n */\nexport async function performInit(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n): Promise<void> {\n // Skip if in rate-limit backoff\n if (rateLimitBackoff) {\n rateLimitBackoff = false; // Reset for next call\n return;\n }\n\n try {\n const effectiveKey = config.apiKey || anonKey;\n if (!effectiveKey) {\n console.warn(\"[glasstrace] No API key available for init request.\");\n return;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), INIT_TIMEOUT_MS);\n\n try {\n // Delegate to sendInitRequest to avoid duplicating fetch logic\n const result = await sendInitRequest(\n config,\n anonKey,\n sdkVersion,\n undefined,\n undefined,\n undefined,\n controller.signal,\n );\n\n clearTimeout(timeoutId);\n\n // Update in-memory config\n currentConfig = result;\n\n // Persist to disk\n await saveCachedConfig(result);\n } catch (err) {\n clearTimeout(timeoutId);\n\n if (err instanceof DOMException && err.name === \"AbortError\") {\n console.warn(\"[glasstrace] ingestion_unreachable: Init request timed out.\");\n return;\n }\n\n // Check for HTTP status errors attached by sendInitRequest\n const status = (err as Record<string, unknown>).status;\n if (status === 401) {\n console.warn(\n \"[glasstrace] ingestion_auth_failed: Check your GLASSTRACE_API_KEY.\",\n );\n return;\n }\n\n if (status === 429) {\n console.warn(\"[glasstrace] ingestion_rate_limited: Backing off.\");\n rateLimitBackoff = true;\n return;\n }\n\n if (typeof status === \"number\" && status >= 400) {\n console.warn(\n `[glasstrace] Init request failed with status ${status}. Using cached config.`,\n );\n return;\n }\n\n // Schema validation failure from sendInitRequest.parse\n if (err instanceof Error && err.name === \"ZodError\") {\n console.warn(\n \"[glasstrace] Init response failed validation (schema version mismatch?). Using cached config.\",\n );\n return;\n }\n\n // Network error or other fetch failure\n console.warn(\n `[glasstrace] ingestion_unreachable: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n } catch (err) {\n // Outermost catch -- should never reach here, but safety net\n console.warn(\n `[glasstrace] Unexpected init error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Returns the current capture config from the three-tier fallback chain:\n * 1. In-memory config from latest init response\n * 2. File cache\n * 3. DEFAULT_CAPTURE_CONFIG\n */\nexport function getActiveConfig(): CaptureConfig {\n // Tier 1: in-memory\n if (currentConfig) {\n return currentConfig.config;\n }\n\n // Tier 2: file cache\n const cached = loadCachedConfig();\n if (cached) {\n return cached.config;\n }\n\n // Tier 3: defaults\n return { ...DEFAULT_CAPTURE_CONFIG };\n}\n\n/**\n * Resets the in-memory config store. For testing only.\n */\nexport function _resetConfigForTesting(): void {\n currentConfig = null;\n rateLimitBackoff = false;\n}\n\n/**\n * Sets the in-memory config directly. Used by performInit and the orchestrator.\n */\nexport function _setCurrentConfig(config: SdkInitResponse): void {\n currentConfig = config;\n}\n\n/**\n * Returns whether rate-limit backoff is active. For testing only.\n */\nexport function _isRateLimitBackoff(): boolean {\n return rateLimitBackoff;\n}\n","import type { SpanProcessor, ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\nimport type { Span } from \"@opentelemetry/sdk-trace-base\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\n\n/**\n * Lightweight SpanProcessor that delegates to a wrapped processor.\n *\n * All glasstrace.* attribute enrichment has been moved to {@link GlasstraceExporter}\n * (see enriching-exporter.ts), which enriches spans at export time. This resolves:\n * - Cold-start spans are buffered in the exporter, not dropped\n * - Vercel's CompositeSpanProcessor skips onEnding(); the exporter doesn't need it\n * - Session ID is computed at export time with the resolved API key\n *\n * This class is retained for backward compatibility. New code should use\n * GlasstraceExporter directly.\n *\n * @deprecated Use GlasstraceExporter for span enrichment. This processor is now a pass-through.\n */\nexport class GlasstraceSpanProcessor implements SpanProcessor {\n private readonly wrappedProcessor: SpanProcessor;\n\n /* eslint-disable @typescript-eslint/no-unused-vars -- backward compat signature */\n constructor(\n wrappedProcessor: SpanProcessor,\n _sessionManager?: SessionManager,\n _apiKey?: string | (() => string),\n _getConfig?: () => CaptureConfig,\n _environment?: string,\n ) {\n /* eslint-enable @typescript-eslint/no-unused-vars */\n this.wrappedProcessor = wrappedProcessor;\n }\n\n onStart(span: Span, parentContext: Parameters<SpanProcessor[\"onStart\"]>[1]): void {\n this.wrappedProcessor.onStart(span, parentContext);\n }\n\n onEnd(readableSpan: ReadableSpan): void {\n this.wrappedProcessor.onEnd(readableSpan);\n }\n\n async shutdown(): Promise<void> {\n return this.wrappedProcessor.shutdown();\n }\n\n async forceFlush(): Promise<void> {\n return this.wrappedProcessor.forceFlush();\n }\n}\n","import { SpanKind } from \"@opentelemetry/api\";\nimport type { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport type { ExportResult } from \"@opentelemetry/core\";\nimport { GLASSTRACE_ATTRIBUTE_NAMES } from \"@glasstrace/protocol\";\nimport type { CaptureConfig } from \"@glasstrace/protocol\";\nimport type { SessionManager } from \"./session.js\";\nimport { classifyFetchTarget } from \"./fetch-classifier.js\";\n\nconst ATTR = GLASSTRACE_ATTRIBUTE_NAMES;\n\n/**\n * Sentinel value indicating the API key has not yet been resolved.\n */\nexport const API_KEY_PENDING = \"pending\" as const;\n\n/**\n * Maximum number of spans to buffer while waiting for key resolution.\n * Prevents unbounded memory growth if the key never resolves.\n */\nconst MAX_PENDING_SPANS = 1024;\n\n\n/**\n * Options for constructing a {@link GlasstraceExporter}.\n */\nexport interface GlasstraceExporterOptions {\n getApiKey: () => string;\n sessionManager: SessionManager;\n getConfig: () => CaptureConfig;\n environment: string | undefined;\n endpointUrl: string;\n createDelegate: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n}\n\ninterface PendingBatch {\n spans: ReadableSpan[];\n resultCallback: (result: ExportResult) => void;\n}\n\n/**\n * A SpanExporter that enriches spans with glasstrace.* attributes at export\n * time, then delegates to a real OTLP exporter.\n *\n * This design resolves three issues:\n * - Spans emitted before the API key resolves are buffered (not dropped)\n * and flushed once the key is available.\n * - Enrichment happens in the exporter (not onEnding), so it works\n * on Vercel where CompositeSpanProcessor does not forward onEnding().\n * - Session ID is computed at export time using the resolved API key,\n * not the \"pending\" placeholder.\n */\nexport class GlasstraceExporter implements SpanExporter {\n private readonly getApiKey: () => string;\n private readonly sessionManager: SessionManager;\n private readonly getConfig: () => CaptureConfig;\n private readonly environment: string | undefined;\n private readonly endpointUrl: string;\n private readonly createDelegateFn: ((url: string, headers: Record<string, string>) => SpanExporter) | null;\n\n private delegate: SpanExporter | null = null;\n private delegateKey: string | null = null;\n private pendingBatches: PendingBatch[] = [];\n private pendingSpanCount = 0;\n private overflowLogged = false;\n\n constructor(options: GlasstraceExporterOptions) {\n this.getApiKey = options.getApiKey;\n this.sessionManager = options.sessionManager;\n this.getConfig = options.getConfig;\n this.environment = options.environment;\n this.endpointUrl = options.endpointUrl;\n this.createDelegateFn = options.createDelegate;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) {\n // Buffer raw (unenriched) spans — enrichment deferred to flush time\n // so session IDs are computed with the resolved key, not \"pending\".\n this.bufferSpans(spans, resultCallback);\n return;\n }\n\n // Key is available — enrich and export\n const enrichedSpans = spans.map((span) => this.enrichSpan(span));\n const exporter = this.ensureDelegate();\n if (exporter) {\n exporter.export(enrichedSpans, resultCallback);\n } else {\n // No delegate factory — report success so the pipeline does not stall\n resultCallback({ code: 0 });\n }\n }\n\n /**\n * Called when the API key transitions from \"pending\" to a resolved value.\n * Creates the delegate exporter and flushes all buffered spans.\n */\n notifyKeyResolved(): void {\n this.flushPending();\n }\n\n async shutdown(): Promise<void> {\n const currentKey = this.getApiKey();\n if (currentKey !== API_KEY_PENDING && this.pendingBatches.length > 0) {\n this.flushPending();\n } else if (this.pendingBatches.length > 0) {\n console.warn(\n `[glasstrace] Shutdown with ${this.pendingSpanCount} buffered spans — API key never resolved, spans lost.`,\n );\n // Complete pending callbacks so pipeline doesn't hang\n for (const batch of this.pendingBatches) {\n batch.resultCallback({ code: 0 });\n }\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n }\n\n if (this.delegate) {\n return this.delegate.shutdown();\n }\n }\n\n forceFlush(): Promise<void> {\n if (this.delegate?.forceFlush) {\n return this.delegate.forceFlush();\n }\n return Promise.resolve();\n }\n\n /**\n * Enriches a ReadableSpan with all glasstrace.* attributes.\n * Returns a new ReadableSpan wrapper; the original span is not mutated.\n *\n * Only {@link SessionManager.getSessionId} is individually guarded because\n * it calls into crypto and schema validation — a session ID failure should\n * not prevent the rest of enrichment. The other helper calls\n * ({@link deriveErrorCategory}, {@link deriveOrmProvider},\n * {@link classifyFetchTarget}) are pure functions on typed string inputs\n * and rely on the outer catch for any unexpected failure.\n *\n * On total failure, returns the original span unchanged.\n */\n private enrichSpan(span: ReadableSpan): ReadableSpan {\n try {\n const attrs = span.attributes ?? {};\n const name = span.name ?? \"\";\n const extra: Record<string, string | number> = {};\n\n // glasstrace.trace.type\n extra[ATTR.TRACE_TYPE] = \"server\";\n\n // glasstrace.session.id — calls external code (crypto, schema validation)\n try {\n const sessionId = this.sessionManager.getSessionId(this.getApiKey());\n extra[ATTR.SESSION_ID] = sessionId;\n } catch { /* session ID omitted */ }\n\n // glasstrace.environment\n const env = this.environment ?? process.env.GLASSTRACE_ENV;\n if (env) {\n extra[ATTR.ENVIRONMENT] = env;\n }\n\n // glasstrace.correlation.id\n const existingCid = attrs[\"glasstrace.correlation.id\"];\n if (typeof existingCid === \"string\") {\n extra[ATTR.CORRELATION_ID] = existingCid;\n }\n\n // glasstrace.route\n const route =\n (attrs[\"http.route\"] as string | undefined) ?? name;\n if (route) {\n extra[ATTR.ROUTE] = route;\n }\n\n // glasstrace.http.method\n const method =\n (attrs[\"http.method\"] as string | undefined) ??\n (attrs[\"http.request.method\"] as string | undefined);\n if (method) {\n extra[ATTR.HTTP_METHOD] = method;\n }\n\n // glasstrace.http.status_code\n const statusCode =\n (attrs[\"http.status_code\"] as number | undefined) ??\n (attrs[\"http.response.status_code\"] as number | undefined);\n if (statusCode !== undefined) {\n extra[ATTR.HTTP_STATUS_CODE] = statusCode;\n }\n\n // glasstrace.http.duration_ms\n if (span.startTime && span.endTime) {\n const [startSec, startNano] = span.startTime;\n const [endSec, endNano] = span.endTime;\n const durationMs =\n (endSec - startSec) * 1000 + (endNano - startNano) / 1_000_000;\n if (durationMs >= 0) {\n extra[ATTR.HTTP_DURATION_MS] = durationMs;\n }\n }\n\n // glasstrace.error.message\n const errorMessage = attrs[\"exception.message\"];\n if (typeof errorMessage === \"string\") {\n extra[ATTR.ERROR_MESSAGE] = errorMessage;\n }\n\n // glasstrace.error.code + glasstrace.error.category\n // Guard against non-string attribute values (OTel attributes can be\n // string | number | boolean | Array) to prevent toLowerCase() throws.\n const errorType = attrs[\"exception.type\"];\n if (typeof errorType === \"string\") {\n extra[ATTR.ERROR_CODE] = errorType;\n extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(errorType);\n }\n\n // glasstrace.error.field\n const errorField = attrs[\"error.field\"];\n if (typeof errorField === \"string\") {\n extra[ATTR.ERROR_FIELD] = errorField;\n }\n\n // glasstrace.orm.*\n const spanAny = span as unknown as Record<string, { name?: string } | undefined>;\n const instrumentationName =\n (spanAny.instrumentationScope?.name ?? spanAny.instrumentationLibrary?.name) ?? \"\";\n const ormProvider = deriveOrmProvider(instrumentationName);\n if (ormProvider) {\n extra[ATTR.ORM_PROVIDER] = ormProvider;\n\n const table = attrs[\"db.sql.table\"];\n const prismaModel = attrs[\"db.prisma.model\"];\n const model = typeof table === \"string\" ? table\n : typeof prismaModel === \"string\" ? prismaModel\n : undefined;\n if (model) {\n extra[ATTR.ORM_MODEL] = model;\n }\n\n const operation = attrs[\"db.operation\"];\n if (typeof operation === \"string\") {\n extra[ATTR.ORM_OPERATION] = operation;\n }\n }\n\n // glasstrace.fetch.target\n const httpUrl = attrs[\"http.url\"];\n const fullUrl = attrs[\"url.full\"];\n const url = typeof httpUrl === \"string\" ? httpUrl\n : typeof fullUrl === \"string\" ? fullUrl\n : undefined;\n if (url && span.kind === SpanKind.CLIENT) {\n extra[ATTR.FETCH_TARGET] = classifyFetchTarget(url);\n }\n\n return createEnrichedSpan(span, extra);\n } catch {\n // Return original span unchanged so the export pipeline is never blocked\n return span;\n }\n }\n\n /**\n * Lazily creates the delegate OTLP exporter once the API key is resolved.\n * Recreates the delegate if the key has changed (e.g., after key rotation)\n * so the Authorization header stays current.\n */\n private ensureDelegate(): SpanExporter | null {\n if (!this.createDelegateFn) return null;\n\n const currentKey = this.getApiKey();\n if (currentKey === API_KEY_PENDING) return null;\n\n // Recreate delegate if the key has changed since last creation\n if (this.delegate && this.delegateKey === currentKey) {\n return this.delegate;\n }\n\n // Shut down old delegate if key rotated. Catch errors to prevent\n // unhandled rejections from crashing the process during rotation.\n if (this.delegate) {\n void this.delegate.shutdown?.().catch(() => {});\n }\n\n this.delegate = this.createDelegateFn(this.endpointUrl, {\n Authorization: `Bearer ${currentKey}`,\n });\n this.delegateKey = currentKey;\n return this.delegate;\n }\n\n /**\n * Buffers raw (unenriched) spans while the API key is pending.\n * Evicts oldest batches if the buffer exceeds MAX_PENDING_SPANS.\n * Re-checks the key after buffering to close the race window where\n * the key resolves between the caller's check and this buffer call.\n */\n private bufferSpans(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n this.pendingBatches.push({ spans, resultCallback });\n this.pendingSpanCount += spans.length;\n\n // Evict oldest batches if over limit\n while (this.pendingSpanCount > MAX_PENDING_SPANS && this.pendingBatches.length > 1) {\n const evicted = this.pendingBatches.shift()!;\n this.pendingSpanCount -= evicted.spans.length;\n // Complete callback so pipeline doesn't hang\n evicted.resultCallback({ code: 0 });\n\n if (!this.overflowLogged) {\n this.overflowLogged = true;\n console.warn(\n \"[glasstrace] Pending span buffer overflow — oldest spans evicted. \" +\n \"This usually means the API key is taking too long to resolve.\",\n );\n }\n }\n\n // Re-check: if the key resolved between the caller's check and now,\n // flush immediately to avoid spans stuck in the buffer.\n if (this.getApiKey() !== API_KEY_PENDING) {\n this.flushPending();\n }\n }\n\n /**\n * Flushes all buffered spans through the delegate exporter.\n * Enriches spans at flush time (not buffer time) so that session IDs\n * are computed with the resolved API key instead of the \"pending\" sentinel.\n */\n private flushPending(): void {\n if (this.pendingBatches.length === 0) return;\n\n const exporter = this.ensureDelegate();\n if (!exporter) {\n // No delegate factory — complete callbacks and discard\n for (const batch of this.pendingBatches) {\n batch.resultCallback({ code: 0 });\n }\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n return;\n }\n\n const batches = this.pendingBatches;\n this.pendingBatches = [];\n this.pendingSpanCount = 0;\n\n for (const batch of batches) {\n // Enrich at flush time with the now-resolved key\n const enriched = batch.spans.map((span) => this.enrichSpan(span));\n exporter.export(enriched, batch.resultCallback);\n }\n }\n\n}\n\n/**\n * Creates a ReadableSpan wrapper that inherits all properties from the\n * original span but overrides `attributes` to include additional entries.\n * The original span is not mutated.\n */\nfunction createEnrichedSpan(\n span: ReadableSpan,\n extra: Record<string, string | number>,\n): ReadableSpan {\n const enrichedAttributes = { ...span.attributes, ...extra };\n return Object.create(span, {\n attributes: {\n value: enrichedAttributes,\n enumerable: true,\n },\n }) as ReadableSpan;\n}\n\n/**\n * Derives ORM provider from the instrumentation library name.\n */\nexport function deriveOrmProvider(instrumentationName: string): string | null {\n const lower = instrumentationName.toLowerCase();\n if (lower.includes(\"prisma\")) {\n return \"prisma\";\n }\n if (lower.includes(\"drizzle\")) {\n return \"drizzle\";\n }\n return null;\n}\n\n/**\n * Derives error category from error type string.\n */\nexport function deriveErrorCategory(errorType: string): string {\n const lower = errorType.toLowerCase();\n if (lower.includes(\"validation\") || lower.includes(\"zod\")) {\n return \"validation\";\n }\n if (\n lower.includes(\"network\") ||\n lower.includes(\"econnrefused\") ||\n lower.includes(\"fetch\") ||\n lower.includes(\"timeout\")\n ) {\n return \"network\";\n }\n if (lower.includes(\"auth\") || lower.includes(\"unauthorized\") || lower.includes(\"forbidden\")) {\n return \"auth\";\n }\n if (lower.includes(\"notfound\") || lower.includes(\"not_found\")) {\n return \"not-found\";\n }\n return \"internal\";\n}\n","import type { AnonApiKey, SessionId } from \"@glasstrace/protocol\";\n\n/**\n * Checks whether the given Origin header is allowed for CORS access.\n *\n * Allowed origins:\n * - `chrome-extension://*` — any Chrome extension\n * - `moz-extension://*` — any Firefox extension\n * - `safari-web-extension://*` — any Safari extension\n * - Absent origin (same-origin / non-browser request)\n *\n * Replaced wildcard `*` to prevent arbitrary websites from\n * reading the anonymous API key from localhost.\n */\nfunction isAllowedOrigin(origin: string | null): boolean {\n if (origin === null) return true;\n if (origin.startsWith(\"chrome-extension://\")) return true;\n if (origin.startsWith(\"moz-extension://\")) return true;\n if (origin.startsWith(\"safari-web-extension://\")) return true;\n return false;\n}\n\n/**\n * Builds CORS headers for a given request origin.\n * Returns headers with `Access-Control-Allow-Origin` set to the origin\n * if allowed, otherwise omits that header entirely.\n */\nfunction buildCorsHeaders(origin: string | null): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Vary: \"Origin\",\n };\n\n if (origin && isAllowedOrigin(origin)) {\n headers[\"Access-Control-Allow-Origin\"] = origin;\n }\n\n return headers;\n}\n\n/**\n * Creates a request handler for the `/__glasstrace/config` discovery endpoint.\n *\n * The returned handler checks if the request URL path is `/__glasstrace/config`.\n * If not, returns `null` (pass-through). If it matches, returns a `DiscoveryResponse`\n * with the anonymous key and current session ID.\n *\n * The triple guard (anonymous + dev + active) is enforced by the caller,\n * not by this module. If the handler is registered, it serves.\n */\nexport function createDiscoveryHandler(\n getAnonKey: () => Promise<AnonApiKey | null>,\n getSessionId: () => SessionId,\n): (request: Request) => Promise<Response | null> {\n return async (request: Request): Promise<Response | null> => {\n // Check path match\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n\n if (url.pathname !== \"/__glasstrace/config\") {\n return null;\n }\n\n // Restrict CORS to known extension origins instead of wildcard\n const origin = request.headers.get(\"Origin\");\n const corsHeaders = buildCorsHeaders(origin);\n\n // Handle CORS preflight\n if (request.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n ...corsHeaders,\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n },\n });\n }\n\n // Only allow GET requests\n if (request.method !== \"GET\") {\n return new Response(\n JSON.stringify({ error: \"method_not_allowed\" }),\n {\n status: 405,\n headers: corsHeaders,\n },\n );\n }\n\n try {\n // Get the anonymous key\n const anonKey = await getAnonKey();\n\n if (anonKey === null) {\n return new Response(\n JSON.stringify({ error: \"not_ready\" }),\n {\n status: 503,\n headers: corsHeaders,\n },\n );\n }\n\n // Get the current session ID\n const sessionId = getSessionId();\n\n return new Response(\n JSON.stringify({ key: anonKey, sessionId }),\n {\n status: 200,\n headers: corsHeaders,\n },\n );\n } catch {\n return new Response(\n JSON.stringify({ error: \"internal_error\" }),\n {\n status: 500,\n headers: corsHeaders,\n },\n );\n }\n };\n}\n\n// Exported for testing\nexport { isAllowedOrigin, buildCorsHeaders };\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\n\nexport class OTLPExporterBase<Internal> {\n private _delegate: IOtlpExportDelegate<Internal>;\n constructor(delegate: IOtlpExportDelegate<Internal>) {\n this._delegate = delegate;\n }\n\n /**\n * Export items.\n * @param items\n * @param resultCallback\n */\n export(\n items: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._delegate.export(items, resultCallback);\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n readonly code?: number;\n override readonly name: string = 'OTLPExporterError';\n readonly data?: string;\n\n constructor(message?: string, code?: number, data?: string) {\n super(message);\n this.data = data;\n this.code = code;\n }\n}\n\n/**\n * Interface for handling export service errors\n */\nexport interface ExportServiceError {\n name: string;\n code: number;\n details: string;\n metadata: { [key: string]: unknown };\n message: string;\n stack: string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HeadersFactory } from './otlp-http-configuration';\n\n/**\n * Configuration shared across all OTLP exporters\n *\n * Implementation note: anything added here MUST be\n * - platform-agnostic\n * - signal-agnostic\n * - transport-agnostic\n */\nexport interface OtlpSharedConfiguration {\n timeoutMillis: number;\n concurrencyLimit: number;\n compression: 'gzip' | 'none';\n}\n\nexport function validateTimeoutMillis(timeoutMillis: number) {\n if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {\n return timeoutMillis;\n }\n throw new Error(\n `Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`\n );\n}\n\nexport function wrapStaticHeadersInFunction(\n headers: Record<string, string> | undefined\n): HeadersFactory | undefined {\n if (headers == null) {\n return undefined;\n }\n\n return async () => headers;\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpSharedConfiguration>,\n fallbackConfiguration: Partial<OtlpSharedConfiguration>,\n defaultConfiguration: OtlpSharedConfiguration\n): OtlpSharedConfiguration {\n return {\n timeoutMillis: validateTimeoutMillis(\n userProvidedConfiguration.timeoutMillis ??\n fallbackConfiguration.timeoutMillis ??\n defaultConfiguration.timeoutMillis\n ),\n concurrencyLimit:\n userProvidedConfiguration.concurrencyLimit ??\n fallbackConfiguration.concurrencyLimit ??\n defaultConfiguration.concurrencyLimit,\n compression:\n userProvidedConfiguration.compression ??\n fallbackConfiguration.compression ??\n defaultConfiguration.compression,\n };\n}\n\nexport function getSharedConfigurationDefaults(): OtlpSharedConfiguration {\n return {\n timeoutMillis: 10000,\n concurrencyLimit: 30,\n compression: 'none',\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface IExportPromiseHandler {\n pushPromise(promise: Promise<void>): void;\n hasReachedLimit(): boolean;\n awaitAll(): Promise<void>;\n}\n\nclass BoundedQueueExportPromiseHandler implements IExportPromiseHandler {\n private readonly _concurrencyLimit: number;\n private _sendingPromises: Promise<unknown>[] = [];\n\n /**\n * @param concurrencyLimit maximum promises allowed in a queue at the same time.\n */\n constructor(concurrencyLimit: number) {\n this._concurrencyLimit = concurrencyLimit;\n }\n\n public pushPromise(promise: Promise<void>): void {\n if (this.hasReachedLimit()) {\n throw new Error('Concurrency Limit reached');\n }\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n void this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n\n public hasReachedLimit(): boolean {\n return this._sendingPromises.length >= this._concurrencyLimit;\n }\n\n public async awaitAll(): Promise<void> {\n await Promise.all(this._sendingPromises);\n }\n}\n\n/**\n * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued.\n * Allows for awaiting all promises in the queue.\n */\nexport function createBoundedQueueExportPromiseHandler(options: {\n concurrencyLimit: number;\n}): IExportPromiseHandler {\n return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Baggage, BaggageEntryMetadata } from '@opentelemetry/api';\nimport { baggageEntryMetadataFromString } from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n if (!entry) return;\n const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);\n const keyPairPart =\n metadataSeparatorIndex === -1\n ? entry\n : entry.substring(0, metadataSeparatorIndex);\n\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n\n const rawKey = keyPairPart.substring(0, separatorIndex).trim();\n const rawValue = keyPairPart.substring(separatorIndex + 1).trim();\n\n if (!rawKey || !rawValue) return;\n let key: string;\n let value: string;\n try {\n key = decodeURIComponent(rawKey);\n value = decodeURIComponent(rawValue);\n } catch {\n return;\n }\n\n let metadata;\n if (\n metadataSeparatorIndex !== -1 &&\n metadataSeparatorIndex < entry.length - 1\n ) {\n const metadataString = entry.substring(metadataSeparatorIndex + 1);\n metadata = baggageEntryMetadataFromString(metadataString);\n }\n\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n if (typeof value === 'string' && value.length > 0) {\n value.split(BAGGAGE_ITEMS_SEPARATOR).forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n\n if (keyPair !== undefined && keyPair.value.length > 0) {\n result[keyPair.key] = keyPair.value;\n }\n });\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AttributeValue, Attributes } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): Attributes {\n const out: Attributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const key in attributes) {\n if (!Object.prototype.hasOwnProperty.call(attributes, key)) {\n continue;\n }\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n const val = (attributes as Record<string, unknown>)[key];\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key !== '';\n}\n\nexport function isAttributeValue(val: unknown): val is AttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValueType(typeof val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n const elementType = typeof element;\n\n if (elementType === type) {\n continue;\n }\n\n if (!type) {\n if (isValidPrimitiveAttributeValueType(elementType)) {\n type = elementType;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValueType(valType: string): boolean {\n switch (valType) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport type { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport type { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { inspect } from 'util';\n\n/**\n * Retrieves a number from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number.\n * - Returns a number in all other cases.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {number | undefined} - The number value or `undefined`.\n */\nexport function getNumberFromEnv(key: string): number | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n\n const value = Number(raw);\n if (isNaN(value)) {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`\n );\n return undefined;\n }\n\n return value;\n}\n\n/**\n * Retrieves a string from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string | undefined} - The string value or `undefined`.\n */\nexport function getStringFromEnv(key: string): string | undefined {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n return raw;\n}\n\n/**\n * Retrieves a boolean value from an environment variable.\n * - Trims leading and trailing whitespace and ignores casing.\n * - Returns `false` if the environment variable is empty, unset, or contains only whitespace.\n * - Returns `false` for strings that cannot be mapped to a boolean.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace.\n */\nexport function getBooleanFromEnv(key: string): boolean {\n const raw = process.env[key]?.trim().toLowerCase();\n if (raw == null || raw === '') {\n // NOTE: falling back to `false` instead of `undefined` as required by the specification.\n // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary\n // normalizations in the consuming code.\n return false;\n }\n if (raw === 'true') {\n return true;\n } else if (raw === 'false') {\n return false;\n } else {\n diag.warn(\n `Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`\n );\n return false;\n }\n}\n\n/**\n * Retrieves a list of strings from an environment variable.\n * - Uses ',' as the delimiter.\n * - Trims leading and trailing whitespace from each entry.\n * - Excludes empty entries.\n * - Returns `undefined` if the environment variable is empty or contains only whitespace.\n * - Returns an empty array if all entries are empty or whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string[] | undefined} - The list of strings or `undefined`.\n */\nexport function getStringListFromEnv(key: string): string[] | undefined {\n return getStringFromEnv(key)\n ?.split(',')\n .map(v => v.trim())\n .filter(s => s !== '');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result' as const;\n\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\" as const;\n\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\" as const;\n\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\" as const;\n\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\" as const;\n\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type' as const;\n\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy' as const;\n\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result' as const;\n\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\" as const;\n\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\" as const;\n\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\" as const;\n\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\" as const;\n\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled' as const;\n\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback' as const;\n\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status' as const;\n\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\" as const;\n\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\" as const;\n\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated' as const;\n\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address' as const;\n\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port' as const;\n\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number' as const;\n\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path' as const;\n\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name' as const;\n\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace' as const;\n\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name' as const;\n\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace' as const;\n\n/**\n * The number of queries included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size' as const;\n\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name' as const;\n\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary' as const;\n\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text' as const;\n\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code' as const;\n\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name' as const;\n\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name' as const;\n\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\" as const;\n\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\" as const;\n\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\" as const;\n\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\" as const;\n\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation' as const;\n\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\" as const;\n\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\" as const;\n\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\" as const;\n\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\" as const;\n\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\" as const;\n\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped' as const;\n\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message' as const;\n\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace' as const;\n\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type' as const;\n\n/**\n * HTTP request headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key: string) => `http.request.header.${key}`;\n\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method' as const;\n\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\" as const;\n\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\" as const;\n\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\" as const;\n\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\" as const;\n\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\" as const;\n\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\" as const;\n\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\" as const;\n\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\" as const;\n\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\" as const;\n\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\" as const;\n\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original' as const;\n\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count' as const;\n\n/**\n * HTTP response headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key: string) => `http.response.header.${key}`;\n\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code' as const;\n\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route' as const;\n\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action' as const;\n\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name' as const;\n\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name' as const;\n\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type' as const;\n\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\" as const;\n\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\" as const;\n\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon' as const;\n\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state' as const;\n\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\" as const;\n\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\" as const;\n\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\" as const;\n\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\" as const;\n\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\" as const;\n\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\" as const;\n\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address' as const;\n\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port' as const;\n\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address' as const;\n\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port' as const;\n\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name' as const;\n\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version' as const;\n\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport' as const;\n\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\" as const;\n\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\" as const;\n\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\" as const;\n\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\" as const;\n\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\" as const;\n\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type' as const;\n\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\" as const;\n\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\" as const;\n\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name' as const;\n\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version' as const;\n\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code' as const;\n\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\" as const;\n\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\" as const;\n\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description' as const;\n\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address' as const;\n\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port' as const;\n\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id' as const;\n\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`.\n */\nexport const ATTR_SERVICE_NAME = 'service.name' as const;\n\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace' as const;\n\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version' as const;\n\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status' as const;\n\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\" as const;\n\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\" as const;\n\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\" as const;\n\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport' as const;\n\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\" as const;\n\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\" as const;\n\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\" as const;\n\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language' as const;\n\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\" as const;\n\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\" as const;\n\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\" as const;\n\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\" as const;\n\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\" as const;\n\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\" as const;\n\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\" as const;\n\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\" as const;\n\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\" as const;\n\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\" as const;\n\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\" as const;\n\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\" as const;\n\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name' as const;\n\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version' as const;\n\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment' as const;\n\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full' as const;\n\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path' as const;\n\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query' as const;\n\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme' as const;\n\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original' as const;\n\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../../version';\nimport {\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport {\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance: { now(): number; readonly timeOrigin: number } =\n performance;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < performance.timeOrigin) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototypeOf = Object.getPrototypeOf;\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (\n typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString\n );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n tag = value[symToStringTag as any];\n let unmasked = false;\n\n try {\n value[symToStringTag as any] = undefined;\n unmasked = true;\n } catch {\n // silence\n }\n\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag as any] = tag;\n } else {\n delete value[symToStringTag as any];\n }\n }\n return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n return nativeObjectToString.call(value);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n private _callback: T;\n private _that: This;\n\n constructor(callback: T, that: This) {\n this._callback = callback;\n this._that = that;\n }\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport type { IOtlpResponseHandler } from './response-handler';\n\nfunction isPartialSuccessResponse(\n response: unknown\n): response is { partialSuccess: never } {\n return Object.prototype.hasOwnProperty.call(response, 'partialSuccess');\n}\n\n/**\n * Default response handler that logs a partial success to the console.\n */\nexport function createLoggingPartialSuccessResponseHandler<\n T,\n>(): IOtlpResponseHandler<T> {\n return {\n handleResponse(response: T) {\n // Partial success MUST never be an empty object according the specification\n // see https://opentelemetry.io/docs/specs/otlp/#partial-success\n if (\n response == null ||\n !isPartialSuccessResponse(response) ||\n response.partialSuccess == null ||\n Object.keys(response.partialSuccess).length === 0\n ) {\n return;\n }\n diag.warn(\n 'Received Partial Success response:',\n JSON.stringify(response.partialSuccess)\n );\n },\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport type { IExporterTransport } from './exporter-transport';\nimport type { IExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { OTLPExporterError } from './types';\nimport type { IOtlpResponseHandler } from './response-handler';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport type { DiagLogger } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Internally shared export logic for OTLP.\n */\nexport interface IOtlpExportDelegate<Internal> {\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void;\n forceFlush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nclass OTLPExportDelegate<Internal, Response>\n implements IOtlpExportDelegate<Internal>\n{\n private _diagLogger: DiagLogger;\n private _transport: IExporterTransport;\n private _serializer: ISerializer<Internal, Response>;\n private _responseHandler: IOtlpResponseHandler<Response>;\n private _promiseQueue: IExportPromiseHandler;\n private _timeout: number;\n\n constructor(\n transport: IExporterTransport,\n serializer: ISerializer<Internal, Response>,\n responseHandler: IOtlpResponseHandler<Response>,\n promiseQueue: IExportPromiseHandler,\n timeout: number\n ) {\n this._transport = transport;\n this._serializer = serializer;\n this._responseHandler = responseHandler;\n this._promiseQueue = promiseQueue;\n this._timeout = timeout;\n this._diagLogger = diag.createComponentLogger({\n namespace: 'OTLPExportDelegate',\n });\n }\n\n export(\n internalRepresentation: Internal,\n resultCallback: (result: ExportResult) => void\n ): void {\n this._diagLogger.debug('items to be sent', internalRepresentation);\n\n // don't do any work if too many exports are in progress.\n if (this._promiseQueue.hasReachedLimit()) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Concurrent export limit reached'),\n });\n return;\n }\n\n const serializedRequest = this._serializer.serializeRequest(\n internalRepresentation\n );\n\n if (serializedRequest == null) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Nothing to send'),\n });\n return;\n }\n\n this._promiseQueue.pushPromise(\n this._transport.send(serializedRequest, this._timeout).then(\n response => {\n if (response.status === 'success') {\n if (response.data != null) {\n try {\n this._responseHandler.handleResponse(\n this._serializer.deserializeResponse(response.data)\n );\n } catch (e) {\n this._diagLogger.warn(\n 'Export succeeded but could not deserialize response - is the response specification compliant?',\n e,\n response.data\n );\n }\n }\n // No matter the response, we can consider the export still successful.\n resultCallback({\n code: ExportResultCode.SUCCESS,\n });\n return;\n } else if (response.status === 'failure' && response.error) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: response.error,\n });\n return;\n } else if (response.status === 'retryable') {\n resultCallback({\n code: ExportResultCode.FAILED,\n error:\n response.error ??\n new OTLPExporterError('Export failed with retryable status'),\n });\n } else {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new OTLPExporterError('Export failed with unknown error'),\n });\n }\n },\n reason =>\n resultCallback({\n code: ExportResultCode.FAILED,\n error: reason,\n })\n )\n );\n }\n\n forceFlush(): Promise<void> {\n return this._promiseQueue.awaitAll();\n }\n\n async shutdown(): Promise<void> {\n this._diagLogger.debug('shutdown started');\n await this.forceFlush();\n this._transport.shutdown();\n }\n}\n\n/**\n * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all\n * signals.\n */\nexport function createOtlpExportDelegate<Internal, Response>(\n components: {\n transport: IExporterTransport;\n serializer: ISerializer<Internal, Response>;\n promiseHandler: IExportPromiseHandler;\n },\n settings: { timeout: number }\n): IOtlpExportDelegate<Internal> {\n return new OTLPExportDelegate(\n components.transport,\n components.serializer,\n createLoggingPartialSuccessResponseHandler(),\n components.promiseHandler,\n settings.timeout\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n IAnyValue,\n IInstrumentationScope,\n IKeyValue,\n Resource,\n} from './internal-types';\nimport type { Attributes } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { Resource as ISdkResource } from '@opentelemetry/resources';\nimport type { Encoder } from './utils';\n\nexport function createResource(\n resource: ISdkResource,\n encoder: Encoder\n): Resource {\n const result: Resource = {\n attributes: toAttributes(resource.attributes, encoder),\n droppedAttributesCount: 0,\n };\n\n const schemaUrl = resource.schemaUrl;\n if (schemaUrl && schemaUrl !== '') result.schemaUrl = schemaUrl;\n\n return result;\n}\n\nexport function createInstrumentationScope(\n scope: InstrumentationScope\n): IInstrumentationScope {\n return {\n name: scope.name,\n version: scope.version,\n };\n}\n\nexport function toAttributes(\n attributes: Attributes,\n encoder: Encoder\n): IKeyValue[] {\n return Object.keys(attributes).map(key =>\n toKeyValue(key, attributes[key], encoder)\n );\n}\n\nexport function toKeyValue(\n key: string,\n value: unknown,\n encoder: Encoder\n): IKeyValue {\n return {\n key: key,\n value: toAnyValue(value, encoder),\n };\n}\n\nexport function toAnyValue(value: unknown, encoder: Encoder): IAnyValue {\n const t = typeof value;\n if (t === 'string') return { stringValue: value as string };\n if (t === 'number') {\n if (!Number.isInteger(value)) return { doubleValue: value as number };\n return { intValue: value as number };\n }\n if (t === 'boolean') return { boolValue: value as boolean };\n if (value instanceof Uint8Array)\n return { bytesValue: encoder.encodeUint8Array(value) };\n if (Array.isArray(value)) {\n const values: IAnyValue[] = new Array(value.length);\n for (let i = 0; i < value.length; i++) {\n values[i] = toAnyValue(value[i], encoder);\n }\n return { arrayValue: { values } };\n }\n if (t === 'object' && value != null) {\n const keys = Object.keys(value);\n const values: IKeyValue[] = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n values[i] = {\n key: keys[i],\n value: toAnyValue((value as Record<string, unknown>)[keys[i]], encoder),\n };\n }\n return { kvlistValue: { values } };\n }\n\n return {};\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Fixed64, LongBits } from './internal-types';\nimport type { HrTime } from '@opentelemetry/api';\nimport { hrTimeToNanoseconds } from '@opentelemetry/core';\nimport { hexToBinary } from './hex-to-binary';\n\nexport function hrTimeToNanos(hrTime: HrTime): bigint {\n const NANOSECONDS = BigInt(1_000_000_000);\n return (\n BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))\n );\n}\n\nexport function toLongBits(value: bigint): LongBits {\n const low = Number(BigInt.asUintN(32, value));\n const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n return { low, high };\n}\n\nexport function encodeAsLongBits(hrTime: HrTime): LongBits {\n const nanos = hrTimeToNanos(hrTime);\n return toLongBits(nanos);\n}\n\nexport function encodeAsString(hrTime: HrTime): string {\n const nanos = hrTimeToNanos(hrTime);\n return nanos.toString();\n}\n\nconst encodeTimestamp =\n typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\n\nexport type HrTimeEncodeFunction = (hrTime: HrTime) => Fixed64;\nexport type SpanContextEncodeFunction = (\n spanContext: string\n) => string | Uint8Array;\nexport type OptionalSpanContextEncodeFunction = (\n spanContext: string | undefined\n) => string | Uint8Array | undefined;\nexport type Uint8ArrayEncodeFunction = (\n value: Uint8Array\n) => string | Uint8Array;\n\nexport interface Encoder {\n encodeHrTime: HrTimeEncodeFunction;\n encodeSpanContext: SpanContextEncodeFunction;\n encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\n encodeUint8Array: Uint8ArrayEncodeFunction;\n}\n\nfunction identity<T>(value: T): T {\n return value;\n}\n\nfunction optionalHexToBinary(str: string | undefined): Uint8Array | undefined {\n if (str === undefined) return undefined;\n return hexToBinary(str);\n}\n\n/**\n * Encoder for protobuf format.\n * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is.\n */\nexport const PROTOBUF_ENCODER: Encoder = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n encodeUint8Array: identity,\n};\n\n/**\n * Encoder for JSON format.\n * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array.\n */\nexport const JSON_ENCODER: Encoder = {\n encodeHrTime: encodeTimestamp,\n encodeSpanContext: identity,\n encodeOptionalSpanContext: identity,\n encodeUint8Array: (bytes: Uint8Array): string => {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n\n // implementation note: not using spread operator and passing to\n // btoa to avoid stack overflow on large Uint8Arrays\n const chars = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n chars[i] = String.fromCharCode(bytes[i]);\n }\n return btoa(chars.join(''));\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nlet serviceName: string | undefined;\n\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName(): string {\n if (serviceName === undefined) {\n try {\n const argv0 = globalThis.process.argv0;\n serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n } catch {\n serviceName = 'unknown_service';\n }\n }\n return serviceName;\n}\n\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache(): void {\n serviceName = undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const isPromiseLike = <R>(val: unknown): val is PromiseLike<R> => {\n return (\n val !== null &&\n typeof val === 'object' &&\n typeof (val as Partial<PromiseLike<R>>).then === 'function'\n );\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '@opentelemetry/api';\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n ATTR_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport type { Resource } from './Resource';\nimport { defaultServiceName } from './default-service-name';\nimport type {\n DetectedResource,\n DetectedResourceAttributes,\n MaybePromise,\n RawResourceAttribute,\n ResourceOptions,\n} from './types';\nimport { isPromiseLike } from './utils';\n\nclass ResourceImpl implements Resource {\n private _rawAttributes: RawResourceAttribute[];\n private _asyncAttributesPending = false;\n private _schemaUrl?: string;\n\n private _memoizedAttributes?: Attributes;\n\n static FromAttributeList(\n attributes: [string, MaybePromise<AttributeValue | undefined>][],\n options?: ResourceOptions\n ): Resource {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource: DetectedResource,\n options?: ResourceOptions\n ) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n\n return [k, v];\n });\n\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n\n public get asyncAttributesPending(): boolean {\n return this._asyncAttributesPending;\n }\n\n public async waitForAsyncAttributes(): Promise<void> {\n if (!this.asyncAttributesPending) {\n return;\n }\n\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n\n this._asyncAttributesPending = false;\n }\n\n public get attributes(): Attributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n\n const attrs: Attributes = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n\n return attrs;\n }\n\n public getRawAttributes(): RawResourceAttribute[] {\n return this._rawAttributes;\n }\n\n public get schemaUrl(): string | undefined {\n return this._schemaUrl;\n }\n\n public merge(resource: Resource | null): Resource {\n if (resource == null) return this;\n\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions: ResourceOptions | undefined = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n\n return ResourceImpl.FromAttributeList(\n [...resource.getRawAttributes(), ...this.getRawAttributes()],\n mergedOptions\n );\n }\n}\n\nexport function resourceFromAttributes(\n attributes: DetectedResourceAttributes,\n options?: ResourceOptions\n): Resource {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\n\nexport function resourceFromDetectedResource(\n detectedResource: DetectedResource,\n options?: ResourceOptions\n): Resource {\n return new ResourceImpl(detectedResource, options);\n}\n\nexport function emptyResource(): Resource {\n return resourceFromAttributes({});\n}\n\nexport function defaultResource(): Resource {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\n\nfunction guardedRawAttributes(\n attributes: RawResourceAttribute[]\n): RawResourceAttribute[] {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug(\n 'promise rejection for resource attribute: %s - %s',\n k,\n err\n );\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\n\nfunction validateSchemaUrl(schemaUrl?: string): string | undefined {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n\n diag.warn(\n 'Schema URL must be string or undefined, got %s. Schema URL will be ignored.',\n schemaUrl\n );\n\n return undefined;\n}\n\nfunction mergeSchemaUrl(\n old: Resource,\n updating: Resource | null\n): string | undefined {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty =\n updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n\n diag.warn(\n 'Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.',\n oldSchemaUrl,\n updatingSchemaUrl\n );\n\n return undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Link } from '@opentelemetry/api';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport type { Encoder } from '../common/utils';\nimport {\n createInstrumentationScope,\n createResource,\n toAttributes,\n} from '../common/internal';\nimport type {\n EStatusCode,\n IEvent,\n IExportTraceServiceRequest,\n ILink,\n IResourceSpans,\n IScopeSpans,\n ISpan,\n} from './internal-types';\n\n// Span flags constants matching the OTLP specification\nconst SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100;\nconst SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200;\n\n/**\n * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags\n * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.\n */\nfunction buildSpanFlagsFrom(traceFlags: number, isRemote?: boolean): number {\n // low 8 bits are W3C TraceFlags (e.g., sampled)\n let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;\n if (isRemote) {\n flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;\n }\n return flags;\n}\n\nexport function sdkSpanToOtlpSpan(span: ReadableSpan, encoder: Encoder): ISpan {\n const ctx = span.spanContext();\n const status = span.status;\n const parentSpanId = span.parentSpanContext?.spanId\n ? encoder.encodeSpanContext(span.parentSpanContext?.spanId)\n : undefined;\n return {\n traceId: encoder.encodeSpanContext(ctx.traceId),\n spanId: encoder.encodeSpanContext(ctx.spanId),\n parentSpanId: parentSpanId,\n traceState: ctx.traceState?.serialize(),\n name: span.name,\n // Span kind is offset by 1 because the API does not define a value for unset\n kind: span.kind == null ? 0 : span.kind + 1,\n startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n attributes: toAttributes(span.attributes, encoder),\n droppedAttributesCount: span.droppedAttributesCount,\n events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n droppedEventsCount: span.droppedEventsCount,\n status: {\n // API and proto enums share the same values\n code: status.code as unknown as EStatusCode,\n message: status.message,\n },\n links: span.links.map(link => toOtlpLink(link, encoder)),\n droppedLinksCount: span.droppedLinksCount,\n flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote),\n };\n}\n\nexport function toOtlpLink(link: Link, encoder: Encoder): ILink {\n return {\n attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],\n spanId: encoder.encodeSpanContext(link.context.spanId),\n traceId: encoder.encodeSpanContext(link.context.traceId),\n traceState: link.context.traceState?.serialize(),\n droppedAttributesCount: link.droppedAttributesCount || 0,\n flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote),\n };\n}\n\nexport function toOtlpSpanEvent(\n timedEvent: TimedEvent,\n encoder: Encoder\n): IEvent {\n return {\n attributes: timedEvent.attributes\n ? toAttributes(timedEvent.attributes, encoder)\n : [],\n name: timedEvent.name,\n timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n };\n}\n\nexport function createExportTraceServiceRequest(\n spans: ReadableSpan[],\n encoder: Encoder\n): IExportTraceServiceRequest {\n return {\n resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n };\n}\n\nfunction createResourceMap(readableSpans: ReadableSpan[]) {\n const resourceMap: Map<Resource, Map<string, ReadableSpan[]>> = new Map();\n for (const record of readableSpans) {\n let ilsMap = resourceMap.get(record.resource);\n\n if (!ilsMap) {\n ilsMap = new Map();\n resourceMap.set(record.resource, ilsMap);\n }\n\n // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n const instrumentationScopeKey = `${record.instrumentationScope.name}@${\n record.instrumentationScope.version || ''\n }:${record.instrumentationScope.schemaUrl || ''}`;\n let records = ilsMap.get(instrumentationScopeKey);\n\n if (!records) {\n records = [];\n ilsMap.set(instrumentationScopeKey, records);\n }\n\n records.push(record);\n }\n\n return resourceMap;\n}\n\nfunction spanRecordsToResourceSpans(\n readableSpans: ReadableSpan[],\n encoder: Encoder\n): IResourceSpans[] {\n const resourceMap = createResourceMap(readableSpans);\n const out: IResourceSpans[] = [];\n\n const entryIterator = resourceMap.entries();\n let entry = entryIterator.next();\n while (!entry.done) {\n const [resource, ilmMap] = entry.value;\n const scopeResourceSpans: IScopeSpans[] = [];\n const ilmIterator = ilmMap.values();\n let ilmEntry = ilmIterator.next();\n while (!ilmEntry.done) {\n const scopeSpans = ilmEntry.value;\n if (scopeSpans.length > 0) {\n const spans = scopeSpans.map(readableSpan =>\n sdkSpanToOtlpSpan(readableSpan, encoder)\n );\n\n scopeResourceSpans.push({\n scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),\n spans: spans,\n schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl,\n });\n }\n ilmEntry = ilmIterator.next();\n }\n const processedResource = createResource(resource, encoder);\n const transformedSpans: IResourceSpans = {\n resource: processedResource,\n scopeSpans: scopeResourceSpans,\n schemaUrl: processedResource.schemaUrl,\n };\n\n out.push(transformedSpans);\n entry = entryIterator.next();\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { ISerializer } from '../../i-serializer';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport type { IExportTraceServiceResponse } from '../export-response';\nimport { createExportTraceServiceRequest } from '../internal';\nimport { JSON_ENCODER } from '../../common/utils';\n\nexport const JsonTraceSerializer: ISerializer<\n ReadableSpan[],\n IExportTraceServiceResponse\n> = {\n serializeRequest: (arg: ReadableSpan[]) => {\n const request = createExportTraceServiceRequest(arg, JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportTraceServiceResponse;\n },\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Parses headers from config leaving only those that have defined values\n * @param partialHeaders\n */\nexport function validateAndNormalizeHeaders(\n partialHeaders: Record<string, string> | undefined\n): Record<string, string> {\n const headers: Record<string, string> = {};\n Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {\n if (typeof value !== 'undefined') {\n headers[key] = String(value);\n } else {\n diag.warn(\n `Header \"${key}\" has invalid value (${value}) and will be ignored`\n );\n }\n });\n return headers;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport {\n getSharedConfigurationDefaults,\n mergeOtlpSharedConfigurationWithDefaults,\n} from './shared-configuration';\nimport { validateAndNormalizeHeaders } from '../util';\n\nexport type HeadersFactory = () => Promise<Record<string, string>>;\n\nexport interface OtlpHttpConfiguration extends OtlpSharedConfiguration {\n url: string;\n headers: HeadersFactory;\n}\n\nfunction mergeHeaders(\n userProvidedHeaders: HeadersFactory | undefined | null,\n fallbackHeaders: HeadersFactory | undefined | null,\n defaultHeaders: HeadersFactory\n): HeadersFactory {\n return async () => {\n const requiredHeaders = {\n ...(await defaultHeaders()),\n };\n const headers = {};\n\n // add fallback ones first\n if (fallbackHeaders != null) {\n Object.assign(headers, await fallbackHeaders());\n }\n\n // override with user-provided ones\n if (userProvidedHeaders != null) {\n Object.assign(\n headers,\n validateAndNormalizeHeaders(await userProvidedHeaders())\n );\n }\n\n // override required ones.\n return Object.assign(headers, requiredHeaders);\n };\n}\n\nfunction validateUserProvidedUrl(url: string | undefined): string | undefined {\n if (url == null) {\n return undefined;\n }\n try {\n // NOTE: In non-browser environments, `globalThis.location` will be `undefined`.\n const base = globalThis.location?.href;\n return new URL(url, base).href;\n } catch {\n throw new Error(\n `Configuration: Could not parse user-provided export URL: '${url}'`\n );\n }\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpHttpConfiguration>,\n defaultConfiguration: OtlpHttpConfiguration\n): OtlpHttpConfiguration {\n return {\n ...mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n headers: mergeHeaders(\n userProvidedConfiguration.headers,\n fallbackConfiguration.headers,\n defaultConfiguration.headers\n ),\n url:\n validateUserProvidedUrl(userProvidedConfiguration.url) ??\n fallbackConfiguration.url ??\n defaultConfiguration.url,\n };\n}\n\nexport function getHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpHttpConfiguration {\n return {\n ...getSharedConfigurationDefaults(),\n headers: async () => requiredHeaders,\n url: 'http://localhost:4318/' + signalResourcePath,\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OtlpHttpConfiguration } from './otlp-http-configuration';\nimport {\n getHttpConfigurationDefaults,\n mergeOtlpHttpConfigurationWithDefaults,\n} from './otlp-http-configuration';\n\n// NOTE: do not change these imports to be actual imports, otherwise they WILL break `@opentelemetry/instrumentation-http`\nimport type * as http from 'http';\nimport type * as https from 'https';\n\nexport type HttpAgentFactory = (\n protocol: string\n) => http.Agent | https.Agent | Promise<http.Agent> | Promise<https.Agent>;\n\nexport interface OtlpNodeHttpConfiguration extends OtlpHttpConfiguration {\n /**\n * Factory function for creating agents.\n *\n * @remarks\n * Prefer using {@link httpAgentFactoryFromOptions} over manually writing a factory function wherever possible.\n * If using a factory function (`HttpAgentFactory`), **do not import `http.Agent` or `https.Agent`\n * statically at the top of the file**.\n * Instead, use dynamic `import()` or `require()` to load the module. This ensures that the `http` or `https`\n * module is not loaded before `@opentelemetry/instrumentation-http` can instrument it.\n */\n agentFactory: HttpAgentFactory;\n /**\n * User agent header string to be appended to the exporter's value as a prefix.\n * Availablie since v1.49.0 of the spec.\n * Ref: https://opentelemetry.io/docs/specs/otel/protocol/exporter/#user-agent\n */\n userAgent?: string;\n}\n\nexport function httpAgentFactoryFromOptions(\n options: http.AgentOptions | https.AgentOptions\n): HttpAgentFactory {\n return async protocol => {\n const isInsecure = protocol === 'http:';\n const module = isInsecure ? import('http') : import('https');\n const { Agent } = await module;\n\n if (isInsecure) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options\n const { ca, cert, key, ...insecureOptions } =\n options as https.AgentOptions;\n return new Agent(insecureOptions);\n }\n return new Agent(options);\n };\n}\n\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpNodeHttpConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpNodeHttpConfiguration>,\n fallbackConfiguration: Partial<OtlpNodeHttpConfiguration>,\n defaultConfiguration: OtlpNodeHttpConfiguration\n): OtlpNodeHttpConfiguration {\n return {\n ...mergeOtlpHttpConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n agentFactory:\n userProvidedConfiguration.agentFactory ??\n fallbackConfiguration.agentFactory ??\n defaultConfiguration.agentFactory,\n userAgent: userProvidedConfiguration.userAgent,\n };\n}\n\nexport function getNodeHttpConfigurationDefaults(\n requiredHeaders: Record<string, string>,\n signalResourcePath: string\n): OtlpNodeHttpConfiguration {\n return {\n ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),\n agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport * as zlib from 'zlib';\nimport { Readable } from 'stream';\nimport type { ExportResponse } from '../export-response';\nimport {\n isExportHTTPErrorRetryable,\n parseRetryAfterToMills,\n} from '../is-export-retryable';\nimport { OTLPExporterError } from '../types';\nimport { VERSION } from '../version';\n\nconst DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION}`;\n\n/**\n * Sends data using http\n * @param request\n * @param url\n * @param headers\n * @param compression\n * @param userAgent\n * @param agent\n * @param data\n * @param timeoutMillis\n */\nexport function sendWithHttp(\n request: typeof https.request | typeof http.request,\n url: string,\n headers: Record<string, string>,\n compression: 'gzip' | 'none',\n userAgent: string | undefined,\n agent: http.Agent | https.Agent,\n data: Uint8Array,\n timeoutMillis: number\n): Promise<ExportResponse> {\n return new Promise<ExportResponse>(resolve => {\n const parsedUrl = new URL(url);\n\n if (userAgent) {\n headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`;\n } else {\n headers['User-Agent'] = DEFAULT_USER_AGENT;\n }\n\n const options: http.RequestOptions | https.RequestOptions = {\n hostname: parsedUrl.hostname,\n port: parsedUrl.port,\n path: parsedUrl.pathname,\n method: 'POST',\n headers,\n agent,\n };\n\n const req = request(options, (res: http.IncomingMessage) => {\n const responseData: Buffer[] = [];\n res.on('data', chunk => responseData.push(chunk));\n\n res.on('end', () => {\n if (res.statusCode && res.statusCode <= 299) {\n resolve({\n status: 'success',\n data: Buffer.concat(responseData),\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n const error = new OTLPExporterError(\n res.statusMessage,\n res.statusCode,\n Buffer.concat(responseData).toString()\n );\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n res.on('error', (error: Error) => {\n // Note: 'end' may still be emitted after 'error' on the same response object, since we're resolving a promise,\n // the first call to resolve() will determine the final state.\n if (res.statusCode && res.statusCode <= 299) {\n // If the response is successful but an error occurs while reading the response,\n // we consider it a success since the data has been sent successfully.\n resolve({\n status: 'success',\n });\n } else if (\n res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)\n ) {\n resolve({\n status: 'retryable',\n error: error,\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n });\n\n req.setTimeout(timeoutMillis, () => {\n req.destroy();\n resolve({\n status: 'retryable',\n error: new Error('Request timed out'),\n });\n });\n\n req.on('error', (error: Error) => {\n if (isHttpTransportNetworkErrorRetryable(error)) {\n resolve({\n status: 'retryable',\n error,\n });\n } else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n\n compressAndSend(req, compression, data, (error: Error) => {\n resolve({\n status: 'failure',\n error,\n });\n });\n });\n}\n\nexport function compressAndSend(\n req: http.ClientRequest,\n compression: 'gzip' | 'none',\n data: Uint8Array,\n onError: (error: Error) => void\n) {\n let dataStream = readableFromUint8Array(data);\n\n if (compression === 'gzip') {\n req.setHeader('Content-Encoding', 'gzip');\n dataStream = dataStream\n .on('error', onError)\n .pipe(zlib.createGzip())\n .on('error', onError);\n }\n\n dataStream.pipe(req).on('error', onError);\n}\n\nfunction readableFromUint8Array(buff: string | Uint8Array): Readable {\n const readable = new Readable();\n readable.push(buff);\n readable.push(null);\n\n return readable;\n}\n\nfunction isHttpTransportNetworkErrorRetryable(error: Error): boolean {\n const RETRYABLE_NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]);\n\n if ('code' in error && typeof error.code === 'string') {\n return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function isExportHTTPErrorRetryable(statusCode: number): boolean {\n return (\n statusCode === 429 ||\n statusCode === 502 ||\n statusCode === 503 ||\n statusCode === 504\n );\n}\n\nexport function parseRetryAfterToMills(\n retryAfter?: string | undefined | null\n): number | undefined {\n if (retryAfter == null) {\n return undefined;\n }\n\n const seconds = Number.parseInt(retryAfter, 10);\n if (Number.isInteger(seconds)) {\n return seconds > 0 ? seconds * 1000 : -1;\n }\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n const delay = new Date(retryAfter).getTime() - Date.now();\n\n if (delay >= 0) {\n return delay;\n }\n return 0;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.214.0';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type * as https from 'https';\nimport type * as http from 'http';\nimport type { ExportResponse } from '../export-response';\nimport type { IExporterTransport } from '../exporter-transport';\nimport { sendWithHttp } from './http-transport-utils';\nimport type { NodeHttpRequestParameters } from './node-http-transport-types';\n\ninterface Utils {\n agent: http.Agent | https.Agent;\n request: typeof http.request | typeof https.request;\n}\n\nclass HttpExporterTransport implements IExporterTransport {\n private _utils: Utils | null = null;\n private _parameters: NodeHttpRequestParameters;\n\n constructor(parameters: NodeHttpRequestParameters) {\n this._parameters = parameters;\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n const { agent, request } = await this._loadUtils();\n const headers = await this._parameters.headers();\n\n return sendWithHttp(\n request,\n this._parameters.url,\n headers,\n this._parameters.compression,\n this._parameters.userAgent,\n agent,\n data,\n timeoutMillis\n );\n }\n\n shutdown() {\n // intentionally left empty, nothing to do.\n }\n\n private async _loadUtils(): Promise<Utils> {\n let utils = this._utils;\n\n if (utils === null) {\n const protocol = new URL(this._parameters.url).protocol;\n const [agent, request] = await Promise.all([\n this._parameters.agentFactory(protocol),\n requestFunctionFactory(protocol),\n ]);\n utils = this._utils = { agent, request };\n }\n\n return utils;\n }\n}\n\nasync function requestFunctionFactory(\n protocol: string\n): Promise<typeof http.request | typeof https.request> {\n const module = protocol === 'http:' ? import('http') : import('https');\n const { request } = await module;\n return request;\n}\n\nexport function createHttpExporterTransport(\n parameters: NodeHttpRequestParameters\n): IExporterTransport {\n return new HttpExporterTransport(parameters);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IExporterTransport } from './exporter-transport';\nimport type { ExportResponse } from './export-response';\nimport { diag } from '@opentelemetry/api';\n\nconst MAX_ATTEMPTS = 5;\nconst INITIAL_BACKOFF = 1000;\nconst MAX_BACKOFF = 5000;\nconst BACKOFF_MULTIPLIER = 1.5;\nconst JITTER = 0.2;\n\n/**\n * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER]\n */\nfunction getJitter() {\n return Math.random() * (2 * JITTER) - JITTER;\n}\n\nclass RetryingTransport implements IExporterTransport {\n private _transport: IExporterTransport;\n\n constructor(transport: IExporterTransport) {\n this._transport = transport;\n }\n\n private retry(\n data: Uint8Array,\n timeoutMillis: number,\n inMillis: number\n ): Promise<ExportResponse> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n this._transport.send(data, timeoutMillis).then(resolve, reject);\n }, inMillis);\n });\n }\n\n async send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n let attempts = MAX_ATTEMPTS;\n let nextBackoff = INITIAL_BACKOFF;\n\n const deadline = Date.now() + timeoutMillis;\n let result = await this._transport.send(data, timeoutMillis);\n\n while (result.status === 'retryable' && attempts > 0) {\n attempts--;\n\n // use maximum of computed backoff and 0 to avoid negative timeouts\n const backoff = Math.max(\n Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF),\n 0\n );\n nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;\n const retryInMillis = result.retryInMillis ?? backoff;\n\n // return when expected retry time is after the export deadline.\n const remainingTimeoutMillis = deadline - Date.now();\n if (retryInMillis > remainingTimeoutMillis) {\n diag.info(\n `Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(\n remainingTimeoutMillis\n )}ms, not retrying further.`\n );\n return result;\n }\n\n diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);\n result = await this.retry(data, remainingTimeoutMillis, retryInMillis);\n }\n\n if (result.status === 'success') {\n diag.verbose(\n `Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`\n );\n } else if (result.status === 'retryable') {\n diag.info(\n `Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`\n );\n } else {\n diag.info(`Export failed with non-retryable error: ${result.error}`);\n }\n\n return result;\n }\n\n shutdown() {\n return this._transport.shutdown();\n }\n}\n\n/**\n * Creates an Exporter Transport that retries on 'retryable' response.\n */\nexport function createRetryingTransport(options: {\n // Underlying transport to wrap.\n transport: IExporterTransport;\n}): IExporterTransport {\n return new RetryingTransport(options.transport);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { IOtlpExportDelegate } from './otlp-export-delegate';\nimport { createOtlpExportDelegate } from './otlp-export-delegate';\nimport type { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { createHttpExporterTransport } from './transport/http-exporter-transport';\nimport { createBoundedQueueExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { createRetryingTransport } from './retrying-transport';\nimport type { OtlpNodeHttpConfiguration } from './configuration/otlp-node-http-configuration';\n\nexport function createOtlpHttpExportDelegate<Internal, Response>(\n options: OtlpNodeHttpConfiguration,\n serializer: ISerializer<Internal, Response>\n): IOtlpExportDelegate<Internal> {\n return createOtlpExportDelegate(\n {\n transport: createRetryingTransport({\n transport: createHttpExporterTransport(options),\n }),\n serializer: serializer,\n promiseHandler: createBoundedQueueExportPromiseHandler(options),\n },\n { timeout: options.timeoutMillis }\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { OtlpSharedConfiguration } from './shared-configuration';\nimport { diag } from '@opentelemetry/api';\n\nfunction parseAndValidateTimeoutFromEnv(\n timeoutEnvVar: string\n): number | undefined {\n const envTimeout = getNumberFromEnv(timeoutEnvVar);\n if (envTimeout != null) {\n if (Number.isFinite(envTimeout) && envTimeout > 0) {\n return envTimeout;\n }\n diag.warn(\n `Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`\n );\n }\n\n return undefined;\n}\n\nfunction getTimeoutFromEnv(signalIdentifier: string) {\n const specificTimeout = parseAndValidateTimeoutFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`\n );\n const nonSpecificTimeout = parseAndValidateTimeoutFromEnv(\n 'OTEL_EXPORTER_OTLP_TIMEOUT'\n );\n\n return specificTimeout ?? nonSpecificTimeout;\n}\n\nfunction parseAndValidateCompressionFromEnv(\n compressionEnvVar: string\n): 'none' | 'gzip' | undefined {\n const compression = getStringFromEnv(compressionEnvVar)?.trim();\n\n if (compression == null || compression === 'none' || compression === 'gzip') {\n return compression;\n }\n\n diag.warn(\n `Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`\n );\n return undefined;\n}\n\nfunction getCompressionFromEnv(\n signalIdentifier: string\n): 'none' | 'gzip' | undefined {\n const specificCompression = parseAndValidateCompressionFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`\n );\n const nonSpecificCompression = parseAndValidateCompressionFromEnv(\n 'OTEL_EXPORTER_OTLP_COMPRESSION'\n );\n\n return specificCompression ?? nonSpecificCompression;\n}\n\nexport function getSharedConfigurationFromEnvironment(\n signalIdentifier: string\n): Partial<OtlpSharedConfiguration> {\n return {\n timeoutMillis: getTimeoutFromEnv(signalIdentifier),\n compression: getCompressionFromEnv(signalIdentifier),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getStringFromEnv, parseKeyPairsIntoRecord } from '@opentelemetry/core';\nimport { diag } from '@opentelemetry/api';\nimport { getSharedConfigurationFromEnvironment } from './shared-env-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { OtlpNodeHttpConfiguration } from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from './otlp-node-http-configuration';\n\nfunction getStaticHeadersFromEnv(\n signalIdentifier: string\n): Record<string, string> | undefined {\n const signalSpecificRawHeaders = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`\n );\n const nonSignalSpecificRawHeaders = getStringFromEnv(\n 'OTEL_EXPORTER_OTLP_HEADERS'\n );\n\n const signalSpecificHeaders = parseKeyPairsIntoRecord(\n signalSpecificRawHeaders\n );\n const nonSignalSpecificHeaders = parseKeyPairsIntoRecord(\n nonSignalSpecificRawHeaders\n );\n\n if (\n Object.keys(signalSpecificHeaders).length === 0 &&\n Object.keys(nonSignalSpecificHeaders).length === 0\n ) {\n return undefined;\n }\n\n // headers are combined instead of overwritten, with the specific headers taking precedence over\n // the non-specific ones.\n return Object.assign(\n {},\n parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders),\n parseKeyPairsIntoRecord(signalSpecificRawHeaders)\n );\n}\n\nfunction appendRootPathToUrlIfNeeded(url: string): string | undefined {\n try {\n const parsedUrl = new URL(url);\n // This will automatically append '/' if there's no root path.\n return parsedUrl.toString();\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n}\n\nfunction appendResourcePathToUrl(\n url: string,\n path: string\n): string | undefined {\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`\n );\n return undefined;\n }\n\n if (!url.endsWith('/')) {\n url = url + '/';\n }\n url += path;\n\n try {\n // just try to parse, if it fails we catch and warn.\n new URL(url);\n } catch {\n diag.warn(\n `Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`\n );\n return undefined;\n }\n\n return url;\n}\n\nfunction getNonSpecificUrlFromEnv(\n signalResourcePath: string\n): string | undefined {\n const envUrl = getStringFromEnv('OTEL_EXPORTER_OTLP_ENDPOINT');\n if (envUrl === undefined) {\n return undefined;\n }\n return appendResourcePathToUrl(envUrl, signalResourcePath);\n}\n\nfunction getSpecificUrlFromEnv(signalIdentifier: string): string | undefined {\n const envUrl = getStringFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`\n );\n if (envUrl === undefined) {\n return undefined;\n }\n return appendRootPathToUrlIfNeeded(envUrl);\n}\n\nfunction readFileFromEnv(\n signalSpecificEnvVar: string,\n nonSignalSpecificEnvVar: string,\n warningMessage: string\n): Buffer | undefined {\n const signalSpecificPath = getStringFromEnv(signalSpecificEnvVar);\n const nonSignalSpecificPath = getStringFromEnv(nonSignalSpecificEnvVar);\n const filePath = signalSpecificPath ?? nonSignalSpecificPath;\n\n if (filePath != null) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), filePath));\n } catch {\n diag.warn(warningMessage);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nfunction getClientCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE',\n 'Failed to read client certificate chain file'\n );\n}\n\nfunction getClientKeyFromEnv(signalIdentifier: string): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`,\n 'OTEL_EXPORTER_OTLP_CLIENT_KEY',\n 'Failed to read client certificate private key file'\n );\n}\n\nfunction getRootCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CERTIFICATE',\n 'Failed to read root certificate file'\n );\n}\n\n/**\n * Reads and returns configuration from the environment\n *\n * @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS)\n * @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs)\n */\nexport function getNodeHttpConfigurationFromEnvironment(\n signalIdentifier: string,\n signalResourcePath: string\n): Partial<OtlpNodeHttpConfiguration> {\n return {\n ...getSharedConfigurationFromEnvironment(signalIdentifier),\n url:\n getSpecificUrlFromEnv(signalIdentifier) ??\n getNonSpecificUrlFromEnv(signalResourcePath),\n headers: wrapStaticHeadersInFunction(\n getStaticHeadersFromEnv(signalIdentifier)\n ),\n agentFactory: httpAgentFactoryFromOptions({\n keepAlive: true,\n ca: getRootCertificateFromEnv(signalIdentifier),\n cert: getClientCertificateFromEnv(signalIdentifier),\n key: getClientKeyFromEnv(signalIdentifier),\n }),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { OTLPExporterConfigBase } from './legacy-base-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport type { HeadersFactory } from './otlp-http-configuration';\n\nexport function convertLegacyHeaders(\n config: OTLPExporterConfigBase\n): HeadersFactory | undefined {\n if (typeof config.headers === 'function') {\n return config.headers;\n }\n return wrapStaticHeadersInFunction(config.headers);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { OTLPExporterNodeConfigBase } from './legacy-node-configuration';\nimport { diag } from '@opentelemetry/api';\nimport type {\n HttpAgentFactory,\n OtlpNodeHttpConfiguration,\n} from './otlp-node-http-configuration';\nimport {\n getNodeHttpConfigurationDefaults,\n mergeOtlpNodeHttpConfigurationWithDefaults,\n} from './otlp-node-http-configuration';\nimport { httpAgentFactoryFromOptions } from '../index-node-http';\nimport { getNodeHttpConfigurationFromEnvironment } from './otlp-node-http-env-configuration';\nimport { convertLegacyHeaders } from './convert-legacy-http-options';\n\nfunction convertLegacyAgentOptions(\n config: OTLPExporterNodeConfigBase\n): HttpAgentFactory | undefined {\n if (typeof config.httpAgentOptions === 'function') {\n return config.httpAgentOptions;\n }\n\n let legacy = config.httpAgentOptions;\n if (config.keepAlive != null) {\n legacy = { keepAlive: config.keepAlive, ...legacy };\n }\n\n if (legacy != null) {\n return httpAgentFactoryFromOptions(legacy);\n } else {\n return undefined;\n }\n}\n\n/**\n * @deprecated this will be removed in 2.0\n * @param config\n * @param signalIdentifier\n * @param signalResourcePath\n * @param requiredHeaders\n */\nexport function convertLegacyHttpOptions(\n config: OTLPExporterNodeConfigBase,\n signalIdentifier: string,\n signalResourcePath: string,\n requiredHeaders: Record<string, string>\n): OtlpNodeHttpConfiguration {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if ((config as any).metadata) {\n diag.warn('Metadata cannot be set when using http');\n }\n\n return mergeOtlpNodeHttpConfigurationWithDefaults(\n {\n url: config.url,\n headers: convertLegacyHeaders(config),\n concurrencyLimit: config.concurrencyLimit,\n timeoutMillis: config.timeoutMillis,\n compression: config.compression,\n agentFactory: convertLegacyAgentOptions(config),\n userAgent: config.userAgent,\n },\n getNodeHttpConfigurationFromEnvironment(\n signalIdentifier,\n signalResourcePath\n ),\n getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base';\nimport { OTLPExporterBase } from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport {\n convertLegacyHttpOptions,\n createOtlpHttpExportDelegate,\n} from '@opentelemetry/otlp-exporter-base/node-http';\n\n/**\n * Collector Trace Exporter for Node\n */\nexport class OTLPTraceExporter\n extends OTLPExporterBase<ReadableSpan[]>\n implements SpanExporter\n{\n constructor(config: OTLPExporterNodeConfigBase = {}) {\n super(\n createOtlpHttpExportDelegate(\n convertLegacyHttpOptions(config, 'TRACES', 'v1/traces', {\n 'Content-Type': 'application/json',\n }),\n JsonTraceSerializer\n )\n );\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanOptions as APISpanOptions,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n TimeInput,\n} from '@opentelemetry/api';\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { TimedEvent } from './TimedEvent';\nimport type { SpanLimits } from './types';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\n// `root` is omitted because it is consumed by Tracer.startSpan() to strip\n// parent context but it has no meaning when constructing a Span directly.\ntype SpanOptions = Omit<APISpanOptions, 'root'> & {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n // Required here to override optional `kind` from the API's SpanOptions\n // SpanImpl assigns it unconditionally and ReadableSpan expects it to be set.\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n recordEndMetrics?: () => void;\n};\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n private readonly _recordEndMetrics?: () => void;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit ?? 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n eventAttributesCount++;\n }\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n\n addLink(link: Link): this {\n if (this._isSpanEnded()) return this;\n\n const { linkCountLimit } = this._spanLimits;\n\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes: Attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (\n attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit\n ) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal!);\n linkAttributesCount++;\n }\n\n const processedLink: Link = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n\n this.links.push(processedLink);\n return this;\n }\n\n addLinks(links: Link[]): this {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n if (status.code === SpanStatusCode.UNSET) return this;\n if (this.status.code === SpanStatusCode.OK) return this;\n\n const newStatus: SpanStatus = { code: status.code };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n } else if (status.message != null) {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n }\n }\n\n this.status = newStatus;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(\n `Dropped ${this._droppedLinksCount} links because linkCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport type { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport type { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport type { Sampler } from './Sampler';\nimport type { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type { Span } from '../Span';\nimport type { SpanProcessor } from '../SpanProcessor';\nimport type { BufferConfig } from '../types';\nimport type { ReadableSpan } from './ReadableSpan';\nimport type { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport type { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin' as const;\n\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT =\n 'otel.span.sampling_result' as const;\n\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live' as const;\n\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started' as const;\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Counter,\n Meter,\n SpanContext,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport { SamplingDecision } from './Sampler';\nimport {\n ATTR_OTEL_SPAN_PARENT_ORIGIN,\n ATTR_OTEL_SPAN_SAMPLING_RESULT,\n METRIC_OTEL_SDK_SPAN_LIVE,\n METRIC_OTEL_SDK_SPAN_STARTED,\n} from './semconv';\n\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n private readonly startedSpans: Counter;\n private readonly liveSpans: UpDownCounter;\n\n constructor(meter: Meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n\n startSpan(\n parentSpanCtx: SpanContext | undefined,\n samplingDecision: SamplingDecision\n ): () => void {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => {};\n }\n\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\n\nfunction parentOrigin(parentSpanContext: SpanContext | undefined): string {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\n\nfunction samplingDecisionToString(decision: SamplingDecision): string {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.6.1';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport type { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport type { SpanProcessor } from './SpanProcessor';\nimport type { Sampler } from './Sampler';\nimport type { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport type { Resource } from '@opentelemetry/resources';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n private readonly _tracerMetrics: TracerMetrics;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n\n const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n const recordEndMetrics = this._tracerMetrics.startSpan(\n parentSpanContext,\n samplingResult.decision\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n recordEndMetrics,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport type { ReadableSpan } from './export/ReadableSpan';\nimport type { Span } from './Span';\nimport type { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport type { Resource } from '@opentelemetry/resources';\nimport { defaultResource } from '@opentelemetry/resources';\nimport type { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport type { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n}\n","import type { ResolvedConfig } from \"./env-detection.js\";\nimport type { SessionManager } from \"./session.js\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { BasicTracerProvider, BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport * as otelApi from \"@opentelemetry/api\";\nimport { GlasstraceExporter, API_KEY_PENDING } from \"./enriching-exporter.js\";\nimport { getActiveConfig } from \"./init-client.js\";\n\n/** Module-level resolved API key, updated when the anon key resolves. */\nlet _resolvedApiKey: string = API_KEY_PENDING;\n\n/** Module-level reference to the active exporter for key-resolution notification. */\nlet _activeExporter: GlasstraceExporter | null = null;\n\n/** Registered shutdown handler, tracked so it can be removed on reset. */\nlet _shutdownHandler: ((signal: NodeJS.Signals) => void) | null = null;\n\n/**\n * Sets the resolved API key for OTel export authentication.\n * Called once the anonymous key or dev key is available.\n * @param key - The resolved API key (anonymous or developer).\n */\nexport function setResolvedApiKey(key: string): void {\n _resolvedApiKey = key;\n}\n\n/**\n * Returns the current resolved API key.\n * Returns the {@link API_KEY_PENDING} sentinel if the key has not yet resolved.\n */\nexport function getResolvedApiKey(): string {\n return _resolvedApiKey;\n}\n\n/**\n * Notifies the active exporter that the API key has transitioned from\n * \"pending\" to a resolved value. This triggers flushing of any buffered spans.\n */\nexport function notifyApiKeyResolved(): void {\n _activeExporter?.notifyKeyResolved();\n}\n\n/**\n * Resets OTel configuration state to initial values. For testing only.\n */\nexport function resetOtelConfigForTesting(): void {\n _resolvedApiKey = API_KEY_PENDING;\n _activeExporter = null;\n if (_shutdownHandler && typeof process !== \"undefined\") {\n process.removeListener(\"SIGTERM\", _shutdownHandler);\n process.removeListener(\"SIGINT\", _shutdownHandler);\n _shutdownHandler = null;\n }\n}\n\n/**\n * Dynamically imports an optional peer dependency at runtime.\n *\n * Uses `Function()` constructor to build the `import()` expression so that\n * bundlers (webpack, esbuild, turbopack) do not attempt to resolve the module\n * at compile time. This is intentional -- the SDK's peer dependencies are\n * optional, and static analysis would cause missing-module build errors for\n * users who have not installed them.\n *\n * **CSP note:** The `Function()` constructor is semantically equivalent to\n * `eval()` and will trigger Content Security Policy violations in environments\n * that disallow `unsafe-eval`. If your CSP blocks this, install the OTel peer\n * dependencies explicitly so they resolve via normal `import` statements, or\n * use the `@vercel/otel` path which does not rely on `tryImport` for its own\n * module.\n *\n * @param moduleId - The npm package name to import (e.g. \"@vercel/otel\").\n * @returns The module namespace object, or `null` if the module is not installed.\n */\nasync function tryImport(moduleId: string): Promise<Record<string, unknown> | null> {\n try {\n return await (Function(\"id\", \"return import(id)\")(moduleId) as Promise<Record<string, unknown>>);\n } catch {\n return null;\n }\n}\n\n/**\n * Registers process shutdown hooks that flush and shut down the OTel provider.\n * Uses `process.once()` to avoid stacking handlers on repeated calls.\n * Guarded for non-Node environments where `process` may not exist.\n */\nfunction registerShutdownHooks(provider: { shutdown: () => Promise<void> }): void {\n if (typeof process === \"undefined\" || typeof process.once !== \"function\") {\n return;\n }\n\n // Remove any previously registered handler before adding a new one\n if (_shutdownHandler) {\n process.removeListener(\"SIGTERM\", _shutdownHandler);\n process.removeListener(\"SIGINT\", _shutdownHandler);\n }\n\n let shutdownCalled = false;\n\n const shutdown = (signal: string) => {\n if (shutdownCalled) return;\n shutdownCalled = true;\n\n void provider.shutdown()\n .catch((err: unknown) => {\n console.warn(\n `[glasstrace] Error during OTel shutdown: ${err instanceof Error ? err.message : String(err)}`,\n );\n })\n .finally(() => {\n // Re-raise the signal so Node's default termination behavior proceeds.\n // Remove our listeners first to avoid re-entering this handler.\n process.removeListener(\"SIGTERM\", _shutdownHandler!);\n process.removeListener(\"SIGINT\", _shutdownHandler!);\n process.kill(process.pid, signal);\n });\n };\n\n const handler = (signal: NodeJS.Signals) => shutdown(signal);\n _shutdownHandler = handler;\n process.once(\"SIGTERM\", handler);\n process.once(\"SIGINT\", handler);\n}\n\n/**\n * Configures OpenTelemetry with the GlasstraceExporter.\n * The exporter handles all span enrichment (glasstrace.* attributes) at\n * export time, solving buffering, no-onEnding,\n * and session-ID-uses-resolved-key concerns.\n *\n * Attempts to use `@vercel/otel` first, falls back to bare OTel SDK.\n *\n * @param config - The resolved SDK configuration (endpoint, environment, etc.).\n * @param sessionManager - Provides session IDs for span enrichment.\n */\nexport async function configureOtel(\n config: ResolvedConfig,\n sessionManager: SessionManager,\n): Promise<void> {\n // Build OTLP exporter configuration\n const exporterUrl = `${config.endpoint}/v1/traces`;\n\n // OTLP exporter factory — always available since OTel is bundled.\n const createOtlpExporter = (url: string, headers: Record<string, string>) =>\n new OTLPTraceExporter({ url, headers });\n\n // Create the GlasstraceExporter that enriches + buffers + delegates\n const glasstraceExporter = new GlasstraceExporter({\n getApiKey: getResolvedApiKey,\n sessionManager,\n getConfig: () => getActiveConfig(),\n environment: config.environment,\n endpointUrl: exporterUrl,\n createDelegate: createOtlpExporter,\n });\n _activeExporter = glasstraceExporter;\n\n // Try @vercel/otel first\n const vercelOtel = await tryImport(\"@vercel/otel\");\n if (vercelOtel && typeof vercelOtel.registerOTel === \"function\") {\n const otelConfig: Record<string, unknown> = {\n serviceName: \"glasstrace-sdk\",\n traceExporter: glasstraceExporter,\n };\n\n // Try @prisma/instrumentation\n const prismaModule = await tryImport(\"@prisma/instrumentation\");\n if (prismaModule) {\n const PrismaInstrumentation = prismaModule.PrismaInstrumentation as\n (new () => unknown) | undefined;\n if (PrismaInstrumentation) {\n otelConfig.instrumentations = [new PrismaInstrumentation()];\n }\n }\n\n (vercelOtel.registerOTel as (opts: Record<string, unknown>) => void)(otelConfig);\n return;\n }\n\n // Fallback: bare OTel SDK with BasicTracerProvider\n // Check for an existing OTel provider before registering.\n // If another tool (Datadog, Sentry, New Relic) already registered a provider,\n // skip Glasstrace registration to avoid silently breaking their tracing.\n // OTel wraps the global provider in a ProxyTracerProvider, so we probe for a\n // real provider by requesting a tracer and checking if it's a \"ProxyTracer\"\n // (the no-op default) or a real Tracer from a registered provider.\n const existingProvider = otelApi.trace.getTracerProvider();\n const probeTracer = existingProvider.getTracer(\"glasstrace-probe\");\n if (probeTracer.constructor.name !== \"ProxyTracer\") {\n console.warn(\n \"[glasstrace] An existing OpenTelemetry TracerProvider is already registered. \" +\n \"Glasstrace will not overwrite it. To use Glasstrace alongside another \" +\n \"tracing tool, add GlasstraceExporter as an additional span processor \" +\n \"on your existing provider.\",\n );\n _activeExporter = null;\n return;\n }\n\n // Use BatchSpanProcessor for production OTLP exports to avoid blocking\n // the event loop on every span.end() call.\n const processor = new BatchSpanProcessor(glasstraceExporter);\n const provider = new BasicTracerProvider({\n spanProcessors: [processor],\n });\n\n otelApi.trace.setGlobalTracerProvider(provider);\n registerShutdownHooks(provider);\n}\n","/**\n * Console error/warn capture module.\n *\n * When enabled, monkey-patches `console.error` and `console.warn` to record\n * their output as OTel span events on the currently active span. SDK-internal\n * log messages (prefixed with \"[glasstrace]\") are never captured.\n */\n\n/**\n * Module-level flag to suppress capture of SDK-internal log messages.\n * Set to `true` before calling `console.warn`/`console.error` from SDK code,\n * then reset to `false` immediately after.\n */\nexport let isGlasstraceLog = false;\n\n/** Saved reference to the original `console.error`. */\nlet originalError: typeof console.error | null = null;\n\n/** Saved reference to the original `console.warn`. */\nlet originalWarn: typeof console.warn | null = null;\n\n/** Whether the console capture is currently installed. */\nlet installed = false;\n\n/** Cached OTel API module reference, resolved at install time. */\nlet otelApi: typeof import(\"@opentelemetry/api\") | null = null;\n\n/**\n * Formats console arguments into a single string for span event attributes.\n * Uses best-effort serialization: strings pass through, Errors preserve their\n * stack trace, and other values are JSON-stringified with a String() fallback.\n */\nfunction formatArgs(args: unknown[]): string {\n return args\n .map((arg) => {\n if (typeof arg === \"string\") return arg;\n if (arg instanceof Error) return arg.stack ?? arg.message;\n try {\n return JSON.stringify(arg);\n } catch {\n return String(arg);\n }\n })\n .join(\" \");\n}\n\n/**\n * Returns `true` if the first argument is a string starting with \"[glasstrace]\".\n * Used to skip capture of SDK-internal log messages without requiring every\n * call site to set the `isGlasstraceLog` flag.\n */\nfunction isSdkMessage(args: unknown[]): boolean {\n return typeof args[0] === \"string\" && args[0].startsWith(\"[glasstrace]\");\n}\n\n/**\n * Installs console capture by replacing `console.error` and `console.warn`\n * with wrappers that record span events on the active OTel span.\n *\n * Must be called after OTel is configured so the API module is available.\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport async function installConsoleCapture(): Promise<void> {\n if (installed) return;\n\n // Resolve OTel API at install time via dynamic import so that:\n // 1. tsup inlines @opentelemetry/api into the bundle (it's in noExternal)\n // 2. vitest's vi.doMock can intercept this import for testing\n try {\n otelApi = await import(\"@opentelemetry/api\");\n } catch {\n otelApi = null;\n }\n\n originalError = console.error;\n originalWarn = console.warn;\n installed = true;\n\n console.error = (...args: unknown[]) => {\n // Always call the original first to preserve developer experience\n originalError!.apply(console, args);\n\n // Skip SDK-internal messages and flagged messages\n if (isGlasstraceLog || isSdkMessage(args)) return;\n\n if (otelApi) {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (span) {\n span.addEvent(\"console.error\", {\n \"console.message\": formatArgs(args),\n });\n }\n }\n };\n\n console.warn = (...args: unknown[]) => {\n originalWarn!.apply(console, args);\n\n if (isGlasstraceLog || isSdkMessage(args)) return;\n\n if (otelApi) {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (span) {\n span.addEvent(\"console.warn\", {\n \"console.message\": formatArgs(args),\n });\n }\n }\n };\n}\n\n/**\n * Restores the original `console.error` and `console.warn` methods.\n * Primarily intended for use in tests.\n */\nexport function uninstallConsoleCapture(): void {\n if (!installed) return;\n\n if (originalError) console.error = originalError;\n if (originalWarn) console.warn = originalWarn;\n\n originalError = null;\n originalWarn = null;\n otelApi = null;\n installed = false;\n}\n\n/**\n * Logs a message from SDK-internal code without triggering console capture.\n *\n * Use this helper in new SDK code instead of bare `console.warn(...)` calls\n * to prevent SDK log messages from being recorded as user-facing span events.\n *\n * @param level - The console log level to use.\n * @param message - The message to log.\n */\nexport function sdkLog(level: \"warn\" | \"info\" | \"error\", message: string): void {\n isGlasstraceLog = true;\n try {\n console[level](message);\n } finally {\n isGlasstraceLog = false;\n }\n}\n","declare const __SDK_VERSION__: string;\n\nimport type { GlasstraceOptions, AnonApiKey } from \"@glasstrace/protocol\";\nimport { resolveConfig, isProductionDisabled, isAnonymousMode } from \"./env-detection.js\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { SessionManager } from \"./session.js\";\nimport { getOrCreateAnonKey, readAnonKey } from \"./anon-key.js\";\nimport { loadCachedConfig, performInit, _setCurrentConfig, getActiveConfig } from \"./init-client.js\";\nimport { createDiscoveryHandler } from \"./discovery-endpoint.js\";\nimport { configureOtel, setResolvedApiKey, getResolvedApiKey, notifyApiKeyResolved, resetOtelConfigForTesting } from \"./otel-config.js\";\nimport { installConsoleCapture, uninstallConsoleCapture } from \"./console-capture.js\";\n\n/** Whether console capture has been installed in this registration cycle. */\nlet consoleCaptureInstalled = false;\n\n/** Module-level state tracking for the registered discovery handler. */\nlet discoveryHandler: ((request: Request) => Promise<Response | null>) | null = null;\n\n/** Module-level flag to prevent double registration. */\nlet isRegistered = false;\n\n/** Generation counter to invalidate stale background promises after reset. */\nlet registrationGeneration = 0;\n\n/**\n * The primary SDK entry point called by developers in their `instrumentation.ts`.\n * Orchestrates OTel setup, span processor, init client, anon key, and discovery endpoint.\n *\n * This function is synchronous and MUST NOT throw. The developer's server is never blocked.\n * Background work (key resolution, init call) happens via fire-and-forget promises.\n *\n * @param options - Optional SDK configuration. Environment variables are used as fallbacks.\n *\n * @example\n * ```ts\n * // instrumentation.ts\n * import { registerGlasstrace } from \"@glasstrace/sdk\";\n * registerGlasstrace(); // uses env vars\n * ```\n */\nexport function registerGlasstrace(options?: GlasstraceOptions): void {\n try {\n // Prevent double registration\n if (isRegistered) {\n return;\n }\n\n // Resolve config\n const config = resolveConfig(options);\n if (config.verbose) {\n console.info(\"[glasstrace] Config resolved.\");\n }\n\n // Production check\n if (isProductionDisabled(config)) {\n console.warn(\n \"[glasstrace] Disabled in production. Set GLASSTRACE_FORCE_ENABLE=true to override.\",\n );\n return;\n }\n if (config.verbose) {\n console.info(\"[glasstrace] Not production-disabled.\");\n }\n\n // Determine auth mode\n const anonymous = isAnonymousMode(config);\n let effectiveKey: string | undefined = config.apiKey;\n\n if (effectiveKey) {\n setResolvedApiKey(effectiveKey);\n }\n\n if (config.verbose) {\n console.info(\n `[glasstrace] Auth mode = ${anonymous ? \"anonymous\" : \"dev-key\"}.`,\n );\n }\n\n // Load cached config and apply to in-memory store\n const cachedInitResponse = loadCachedConfig();\n if (cachedInitResponse) {\n _setCurrentConfig(cachedInitResponse);\n }\n if (config.verbose) {\n console.info(\n `[glasstrace] Cached config ${cachedInitResponse ? \"loaded and applied\" : \"not found\"}.`,\n );\n }\n\n // Create SessionManager\n const sessionManager = new SessionManager();\n if (config.verbose) {\n console.info(\"[glasstrace] SessionManager created.\");\n }\n\n isRegistered = true;\n const currentGeneration = registrationGeneration;\n\n // Configure OTel IMMEDIATELY in all modes.\n // OTel is registered before the anon key resolves so that\n // spans are captured from cold start. GlasstraceExporter buffers spans\n // while the key is \"pending\" and flushes them once notifyApiKeyResolved()\n // is called after anonymous key resolution.\n // This is fire-and-forget -- OTel failure must not block init.\n void configureOtel(config, sessionManager).then(\n () => {\n // Check cached config for consoleErrors (may be stale or absent).\n // Re-checked after performInit completes with the authoritative config.\n maybeInstallConsoleCapture();\n\n if (config.verbose) {\n console.info(\"[glasstrace] OTel configured.\");\n }\n },\n (err: unknown) => {\n console.warn(\n `[glasstrace] Failed to configure OTel: ${err instanceof Error ? err.message : String(err)}`,\n );\n },\n );\n\n // Background work: anonymous key resolution, discovery endpoint, init\n if (anonymous) {\n // Register discovery endpoint IMMEDIATELY with async key resolution\n if (isDiscoveryEnabled(config)) {\n let resolvedAnonKey: AnonApiKey | null = null;\n const anonKeyPromise = getOrCreateAnonKey();\n\n // Use getResolvedApiKey() for session ID instead of\n // capturing the mutable effectiveKey closure variable.\n discoveryHandler = createDiscoveryHandler(\n async () => resolvedAnonKey,\n () => sessionManager.getSessionId(getResolvedApiKey()),\n );\n\n if (config.verbose) {\n console.info(\"[glasstrace] Discovery endpoint registered (key pending).\");\n }\n\n // Background: resolve key, update API key, then init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await anonKeyPromise;\n resolvedAnonKey = anonKey;\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n // Update the discovery handler to serve the resolved key\n // Use getResolvedApiKey() for canonical key state\n discoveryHandler = createDiscoveryHandler(\n () => Promise.resolve(anonKey),\n () => sessionManager.getSessionId(getResolvedApiKey()),\n );\n\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n\n await performInit(config, anonKey, __SDK_VERSION__);\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n } else {\n // Anonymous + non-dev: no discovery endpoint, just background init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n const anonKey = await getOrCreateAnonKey();\n setResolvedApiKey(anonKey);\n notifyApiKeyResolved();\n effectiveKey = anonKey;\n\n if (currentGeneration !== registrationGeneration) return;\n\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n\n await performInit(config, anonKey, __SDK_VERSION__);\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n } else {\n // Dev key mode: read straggler anon key, then fire init\n void (async () => {\n try {\n if (currentGeneration !== registrationGeneration) return;\n\n let anonKeyForInit: AnonApiKey | null = null;\n try {\n anonKeyForInit = await readAnonKey();\n } catch {\n // Expected when no prior anon key file exists on disk (first run).\n }\n\n if (currentGeneration !== registrationGeneration) return;\n\n if (config.verbose) {\n console.info(\"[glasstrace] Background init firing.\");\n }\n await performInit(config, anonKeyForInit, __SDK_VERSION__);\n\n // Re-check consoleErrors with the authoritative init response config\n maybeInstallConsoleCapture();\n } catch (err) {\n console.warn(\n `[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n })();\n }\n\n // Import graph (coverageMapEnabled) -- placeholder\n if (config.coverageMapEnabled && config.verbose) {\n console.info(\"[glasstrace] Import graph building skipped.\");\n }\n } catch (err) {\n console.warn(\n `[glasstrace] Registration failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Returns the registered discovery handler, or null if not registered.\n */\nexport function getDiscoveryHandler(): ((request: Request) => Promise<Response | null>) | null {\n return discoveryHandler;\n}\n\n/**\n * Checks the active config and installs console capture if enabled.\n * Idempotent — safe to call multiple times (after OTel config, after init).\n * This ensures console capture is installed whenever authoritative config\n * becomes available, whether from the file cache or the init response.\n */\nfunction maybeInstallConsoleCapture(): void {\n if (consoleCaptureInstalled) return;\n if (getActiveConfig().consoleErrors) {\n consoleCaptureInstalled = true;\n void installConsoleCapture();\n }\n}\n\n/**\n * Returns `true` if the discovery endpoint should be enabled for this environment.\n *\n * Tightened from \"not production\" to explicit development conditions:\n * 1. `GLASSTRACE_DISCOVERY_ENABLED=true` -- explicit override (highest priority)\n * 2. `GLASSTRACE_DISCOVERY_ENABLED=false` -- explicit disable (highest priority)\n * 3. `NODE_ENV` is `\"development\"` or unset, AND `VERCEL_ENV` is not `\"production\"`\n *\n * Environments like `staging`, `test`, and `ci` do not expose the discovery\n * endpoint by default, since it serves the anonymous API key over CORS.\n *\n * @param config - The resolved SDK configuration.\n * @returns Whether the discovery endpoint should be registered.\n */\nfunction isDiscoveryEnabled(config: ResolvedConfig): boolean {\n // Explicit flag takes precedence\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"true\") return true;\n if (process.env.GLASSTRACE_DISCOVERY_ENABLED === \"false\") return false;\n\n // Block production environments\n if (config.nodeEnv === \"production\") return false;\n if (config.vercelEnv === \"production\") return false;\n\n // Only allow in development or when NODE_ENV is unset\n if (config.nodeEnv === \"development\" || config.nodeEnv === undefined) return true;\n\n return false;\n}\n\n/**\n * Resets registration state. For testing only.\n */\nexport function _resetRegistrationForTesting(): void {\n isRegistered = false;\n discoveryHandler = null;\n consoleCaptureInstalled = false;\n registrationGeneration++;\n uninstallConsoleCapture();\n resetOtelConfigForTesting();\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as crypto from \"node:crypto\";\nimport { execSync } from \"node:child_process\";\nimport {\n SourceMapUploadResponseSchema,\n type SourceMapUploadResponse,\n} from \"@glasstrace/protocol\";\n\nexport interface SourceMapEntry {\n filePath: string;\n content: string;\n}\n\n/**\n * Recursively finds all .map files in the given build directory.\n * Returns relative paths and file contents.\n */\nexport async function collectSourceMaps(\n buildDir: string,\n): Promise<SourceMapEntry[]> {\n const results: SourceMapEntry[] = [];\n\n try {\n await walkDir(buildDir, buildDir, results);\n } catch {\n // Directory doesn't exist or is unreadable — return empty\n return [];\n }\n\n return results;\n}\n\nasync function walkDir(\n baseDir: string,\n currentDir: string,\n results: SourceMapEntry[],\n): Promise<void> {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(currentDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = path.join(currentDir, entry.name);\n\n if (entry.isDirectory()) {\n await walkDir(baseDir, fullPath, results);\n } else if (entry.isFile() && entry.name.endsWith(\".map\")) {\n try {\n const content = await fs.readFile(fullPath, \"utf-8\");\n const relativePath = path.relative(baseDir, fullPath).replace(/\\\\/g, \"/\");\n // Strip the trailing .map extension so the key matches the compiled\n // JS path that the runtime uses for stack-frame lookups (e.g.\n // \"static/chunks/main.js\" instead of \"static/chunks/main.js.map\").\n const compiledPath = relativePath.replace(/\\.map$/, \"\");\n results.push({ filePath: compiledPath, content });\n } catch {\n // Skip unreadable files\n }\n }\n }\n}\n\n/**\n * Computes a build hash for source map uploads.\n *\n * First tries `git rev-parse HEAD` to get the git commit SHA.\n * On failure, falls back to a deterministic content hash:\n * sort source map file paths alphabetically, concatenate each as\n * `{relativePath}\\n{fileLength}\\n{fileContent}`, then SHA-256 the result.\n */\nexport async function computeBuildHash(\n maps?: SourceMapEntry[],\n): Promise<string> {\n // Try git first\n try {\n const sha = execSync(\"git rev-parse HEAD\", { encoding: \"utf-8\" }).trim();\n if (sha) {\n return sha;\n }\n } catch {\n // Git not available, fall through to content hash\n }\n\n // Fallback: content-based hash\n const sortedMaps = [...(maps ?? [])].sort((a, b) =>\n a.filePath.localeCompare(b.filePath),\n );\n\n const hashInput = sortedMaps\n .map((m) => `${m.filePath}\\n${m.content.length}\\n${m.content}`)\n .join(\"\");\n\n const hash = crypto.createHash(\"sha256\").update(hashInput).digest(\"hex\");\n return hash;\n}\n\n/**\n * Uploads source maps to the ingestion API.\n *\n * POSTs to `{endpoint}/v1/source-maps` with the API key, build hash,\n * and file entries. Validates the response against SourceMapUploadResponseSchema.\n */\nexport async function uploadSourceMaps(\n apiKey: string,\n endpoint: string,\n buildHash: string,\n maps: SourceMapEntry[],\n): Promise<SourceMapUploadResponse> {\n const body = {\n apiKey,\n buildHash,\n files: maps.map((m) => ({\n filePath: m.filePath,\n sourceMap: m.content,\n })),\n };\n\n // Strip trailing slashes iteratively to avoid regex (CodeQL js/polynomial-redos).\n let baseUrl = endpoint;\n while (baseUrl.endsWith(\"/\")) {\n baseUrl = baseUrl.slice(0, -1);\n }\n const response = await fetch(`${baseUrl}/v1/source-maps`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n // Consume the response body to release the connection back to the pool.\n // Without this, the underlying TCP socket stays allocated until GC, which\n // causes connection pool exhaustion under sustained error conditions.\n // Wrapped in try-catch so a stream error doesn't mask the HTTP status error.\n try { await response.text(); } catch { /* body drain is best-effort */ }\n throw new Error(\n `Source map upload failed: ${String(response.status)} ${response.statusText}`,\n );\n }\n\n const json: unknown = await response.json();\n return SourceMapUploadResponseSchema.parse(json);\n}\n","import { collectSourceMaps, computeBuildHash, uploadSourceMaps } from \"./source-map-uploader.js\";\n\ntype NextConfig = Record<string, unknown>;\ntype WebpackConfigFn = (config: Record<string, unknown>, context: Record<string, unknown>) => Record<string, unknown>;\n\n/** Subset of the webpack context object passed by Next.js to the webpack config function. */\ninterface WebpackContext {\n isServer: boolean;\n dev: boolean;\n [key: string]: unknown;\n}\n\n/** Minimal webpack compiler shape for the afterEmit hook. */\ninterface WebpackCompiler {\n hooks?: {\n afterEmit?: {\n tapPromise?: (name: string, fn: (compilation: unknown) => Promise<void>) => void;\n };\n };\n}\n\n/**\n * Wraps the developer's Next.js config to enable source map generation\n * and upload .map files to the ingestion API at build time.\n *\n * The build NEVER fails because of Glasstrace — all errors are caught\n * and logged as warnings.\n *\n * @param nextConfig - The developer's existing Next.js configuration object.\n * @returns A new config object with source map generation and upload enabled.\n */\nexport function withGlasstraceConfig(nextConfig: NextConfig): NextConfig {\n // Handle null/undefined gracefully\n const config: NextConfig = nextConfig != null ? { ...nextConfig } : {};\n\n // Enable server-side source map generation for Glasstrace uploads.\n // Intentionally does NOT set productionBrowserSourceMaps — that exposes\n // full source code publicly via browser DevTools. Users who want public\n // browser source maps can set it explicitly in their Next.js config.\n\n // Enable server-side source maps (Next.js experimental feature)\n const existingExperimental = (config.experimental as Record<string, unknown>) ?? {};\n config.experimental = { ...existingExperimental, serverSourceMaps: true };\n\n // Capture distDir for source map collection (default: .next)\n const distDir = typeof config.distDir === \"string\" ? config.distDir : \".next\";\n\n // Capture existing webpack config if any\n const existingWebpack = config.webpack as WebpackConfigFn | undefined;\n\n // Register webpack config modifier\n config.webpack = (\n webpackConfig: Record<string, unknown>,\n context: Record<string, unknown>,\n ): Record<string, unknown> => {\n // Call existing webpack config first\n let result = webpackConfig;\n if (typeof existingWebpack === \"function\") {\n result = existingWebpack(webpackConfig, context);\n }\n\n const webpackContext = context as WebpackContext;\n\n // Only run source map upload on client-side production builds (not server, not dev)\n if (!webpackContext.isServer && webpackContext.dev === false) {\n // Register a plugin to collect and upload source maps after compilation\n const plugins = (result.plugins as Array<Record<string, unknown>>) ?? [];\n plugins.push({\n apply(compiler: Record<string, unknown>) {\n const typedCompiler = compiler as WebpackCompiler;\n if (typedCompiler.hooks?.afterEmit?.tapPromise) {\n typedCompiler.hooks.afterEmit.tapPromise(\n \"GlasstraceSourceMapUpload\",\n async () => {\n await handleSourceMapUpload(distDir);\n },\n );\n }\n },\n });\n result.plugins = plugins;\n }\n\n return result;\n };\n\n return config;\n}\n\n/**\n * Collects source map files from the build output directory and uploads\n * them to the Glasstrace ingestion API. Never throws — all errors are\n * caught and logged as warnings so the build is never blocked.\n *\n * Exported for testing only; not part of the public API.\n *\n * @param distDir - The Next.js build output directory (e.g. \".next\").\n */\nexport async function handleSourceMapUpload(distDir: string): Promise<void> {\n try {\n const apiKey = process.env.GLASSTRACE_API_KEY;\n const endpoint =\n process.env.GLASSTRACE_ENDPOINT ?? \"https://api.glasstrace.dev\";\n\n // Anonymous mode: skip upload\n if (!apiKey || apiKey.trim() === \"\") {\n console.info(\n \"[glasstrace] Source map upload skipped (no API key). Stack traces will show compiled locations.\",\n );\n return;\n }\n\n const maps = await collectSourceMaps(distDir);\n\n if (maps.length === 0) {\n console.info(\"[glasstrace] No source map files found. Skipping upload.\");\n return;\n }\n\n const buildHash = await computeBuildHash(maps);\n\n await uploadSourceMaps(apiKey, endpoint, buildHash, maps);\n console.info(\n `[glasstrace] Uploaded ${String(maps.length)} source map(s) for build ${buildHash}.`,\n );\n } catch (error: unknown) {\n // Build must NEVER fail because of Glasstrace\n const message =\n error instanceof Error ? error.message : \"Unknown error\";\n console.warn(\n `[glasstrace] Source map upload failed: ${message}. Build continues normally.`,\n );\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveConfig, isProductionDisabled } from \"../env-detection.js\";\n\n/**\n * Module-level flag ensuring the nudge fires at most once per process.\n */\nlet hasFired = false;\n\n/**\n * Strips control characters (except space) from a string to prevent\n * terminal escape sequence injection via error summaries written to stderr.\n */\nfunction sanitize(input: string): string {\n // eslint-disable-next-line no-control-regex\n return input.replace(/[\\x00-\\x1f\\x7f]/g, \"\");\n}\n\n/**\n * Shows a one-time stderr nudge when the SDK captures its first error\n * and the MCP connection marker file is absent.\n *\n * The nudge is suppressed when:\n * - It has already fired in this process\n * - The `.glasstrace/mcp-connected` marker file exists at the project root\n * - The environment is detected as production (and force-enable is off)\n *\n * Uses `process.stderr.write()` instead of `console.error()` to avoid\n * being captured by OpenTelemetry console instrumentation.\n */\nexport function maybeShowMcpNudge(errorSummary: string): void {\n if (hasFired) {\n return;\n }\n\n // Production check — suppress silently\n const config = resolveConfig();\n if (isProductionDisabled(config)) {\n return;\n }\n\n // Check for MCP connection marker file.\n // Guard process.cwd() — it throws ENOENT if the working directory has been removed.\n let markerExists = false;\n try {\n const markerPath = join(process.cwd(), \".glasstrace\", \"mcp-connected\");\n markerExists = existsSync(markerPath);\n } catch {\n // Permission denied, ENOENT from cwd(), or other filesystem error — treat as not connected\n markerExists = false;\n }\n\n if (markerExists) {\n return;\n }\n\n // Fire the nudge exactly once\n hasFired = true;\n\n const safe = sanitize(errorSummary);\n process.stderr.write(\n `[glasstrace] Error captured: ${safe}\\n` +\n ` Debug with AI: ask your agent \"What's the latest Glasstrace error?\"\\n` +\n ` Not connected? Run: npx glasstrace mcp add\\n`,\n );\n}\n","/**\n * Manual error capture API.\n *\n * Provides a simple function for developers to manually record errors\n * as span events, independent of the `consoleErrors` config flag.\n */\n\nimport * as otelApi from \"@opentelemetry/api\";\nimport { maybeShowMcpNudge } from \"./nudge/error-nudge.js\";\n\n/**\n * Records an error as a span event on the currently active OTel span.\n *\n * Works regardless of the `consoleErrors` configuration — this is an\n * explicit, opt-in API for manual error reporting. If no span is active\n * or OTel is not available, the call is silently ignored.\n *\n * On the first captured error, may display a one-time diagnostic nudge\n * to stderr if the MCP connection marker is absent (dev environments only).\n *\n * @param error - The error to capture. Accepts `Error` objects, strings, or any value.\n *\n * @example\n * ```ts\n * import { captureError } from \"@glasstrace/sdk\";\n *\n * try {\n * await riskyOperation();\n * } catch (err) {\n * captureError(err);\n * // handle error normally...\n * }\n * ```\n */\nexport function captureError(error: unknown): void {\n try {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (!span) return;\n\n const attributes: Record<string, string> = {\n \"error.message\": String(error),\n };\n\n if (error instanceof Error) {\n attributes[\"error.type\"] = error.constructor.name;\n }\n\n span.addEvent(\"glasstrace.error\", attributes);\n\n // Show one-time MCP connection nudge on first captured error\n maybeShowMcpNudge(String(error));\n } catch {\n // Silently ignore failures\n }\n}\n\n/**\n * Eagerly loads the OTel API module. Previously required for async resolution;\n * now a no-op since OTel is statically imported. Retained for test compatibility.\n *\n * @internal\n */\nexport async function _preloadOtelApi(): Promise<void> {\n // No-op: OTel API is now statically imported and always available.\n}\n\n/**\n * Resets internal state. For testing only.\n * @internal\n */\nexport function _resetCaptureErrorForTesting(): void {\n // No-op: OTel API is now statically imported and always available.\n // Kept for backward compatibility with existing tests.\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EAET,YAAY,MAAyB,SAAiB,OAAe;AACnE,UAAM,SAAS,EAAE,MAAM,CAAC;AACxB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;ACCA,IAAM,mBAAmB;AAMlB,SAAS,cAAiC;AAC/C,SAAO;AAAA,IACL,oBAAoB,QAAQ,IAAI,oBAAoB,KAAK,KAAK;AAAA,IAC9D,yBAAyB,QAAQ,IAAI;AAAA,IACrC,gBAAgB,QAAQ,IAAI;AAAA,IAC5B,yBAAyB,QAAQ,IAAI;AAAA,IACrC,UAAU,QAAQ,IAAI;AAAA,IACtB,YAAY,QAAQ,IAAI;AAAA,EAC1B;AACF;AAMO,SAAS,cAAc,SAA6C;AACzE,QAAM,MAAM,YAAY;AAExB,SAAO;AAAA,IACL,QAAQ,SAAS,UAAU,IAAI;AAAA,IAC/B,UAAU,SAAS,YAAY;AAAA,IAC/B,aAAa,SAAS,eAAe,IAAI,4BAA4B;AAAA,IACrE,SAAS,SAAS,WAAW;AAAA,IAC7B,aAAa,IAAI;AAAA,IACjB,oBAAoB,IAAI,4BAA4B;AAAA,IACpD,SAAS,IAAI;AAAA,IACb,WAAW,IAAI;AAAA,EACjB;AACF;AAUO,SAAS,qBAAqB,QAAiC;AACpE,MAAI,OAAO,aAAa;AACtB,WAAO;AAAA,EACT;AACA,MAAI,OAAO,YAAY,cAAc;AACnC,WA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AACjD,MAAI;AACF,UAAM,OAAe,MAAM,QAAgB,QAAQ,OAAO,CAAC;AAC3D,QAAI,CAAC,KAAM;AAEX,UAAM,aAAqC;AAAA,MACzC,iBAAiB,OAAO,KAAK;AAAA,IAC/B;AAEA,QAAI,iBAAiB,OAAO;AAC1B,iBAAW,YAAY,IAAI,MAAM,YAAY;AAAA,IAC/C;AAEA,SAAK,SAAS,oBAAoB,UAAU;AAG5C,sBAAkB,OAAO,KAAK,CAAC;AAAA,EACjC,QAAQ;AAAA,EAER;AACF;","names":["cachedPort","cachedPort","context","context","ExportResultCode","resolve","hrTime","hrTime","VERSION","VERSION","resolve","resolve","path","SamplingDecision","SamplingDecision","SamplingDecision","context","context","SamplingDecision","TracesSamplerValues","resolve","SamplingDecision","VERSION","VERSION","context","resolve","context","ForceFlushState","resolve","fs","path","context","join","join"]}