@cloudbase/agent-observability 1.0.1-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -0
- package/dist/chunk-NFEGQTCC.mjs +27 -0
- package/dist/chunk-NFEGQTCC.mjs.map +1 -0
- package/dist/chunk-ZGEMAYS4.mjs +716 -0
- package/dist/chunk-ZGEMAYS4.mjs.map +1 -0
- package/dist/esm-PGEDANAI.mjs +1030 -0
- package/dist/esm-PGEDANAI.mjs.map +1 -0
- package/dist/index.d.mts +728 -0
- package/dist/index.d.ts +728 -0
- package/dist/index.js +732 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +52 -0
- package/dist/index.mjs.map +1 -0
- package/dist/langchain.d.mts +108 -0
- package/dist/langchain.d.ts +108 -0
- package/dist/langchain.js +1237 -0
- package/dist/langchain.js.map +1 -0
- package/dist/langchain.mjs +535 -0
- package/dist/langchain.mjs.map +1 -0
- package/dist/server.d.mts +163 -0
- package/dist/server.d.ts +163 -0
- package/dist/server.js +1528 -0
- package/dist/server.js.map +1 -0
- package/dist/server.mjs +175 -0
- package/dist/server.mjs.map +1 -0
- package/package.json +91 -0
- package/src/core/attributes.ts +233 -0
- package/src/core/constants.ts +75 -0
- package/src/core/spanWrapper.ts +417 -0
- package/src/core/tracerProvider.ts +136 -0
- package/src/index.ts +775 -0
- package/src/langchain/CallbackHandler.ts +893 -0
- package/src/langchain/index.ts +7 -0
- package/src/server/config.ts +160 -0
- package/src/server/index.ts +21 -0
- package/src/server/setup.ts +344 -0
- package/src/types.ts +254 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/OTLPExporterBase.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/types.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-configuration.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/bounded-queue-export-promise-handler.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/baggage/constants.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/baggage/utils.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/platform/node/index.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/platform/index.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/common/time.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/ExportResult.ts","../../../node_modules/.pnpm/@opentelemetry+core@2.4.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/core/src/index.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/logging-response-handler.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/otlp-export-delegate.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/index.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-transformer/src/common/hex-to-binary.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-transformer/src/common/utils.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-transformer/src/common/internal.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-transformer/src/trace/internal.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-transformer/src/trace/json/trace.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-transformer/src/trace/json/index.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-transformer/src/index.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/util.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-http-configuration.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-configuration.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/is-export-retryable.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/version.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-transport-utils.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/transport/http-exporter-transport.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/retrying-transport.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/otlp-http-export-delegate.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/configuration/shared-env-configuration.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/configuration/otlp-node-http-env-configuration.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-http-options.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/configuration/convert-legacy-node-http-options.ts","../../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/otlp-exporter-base/src/index-node-http.ts","../../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/node/OTLPTraceExporter.ts","../../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/node/index.ts","../../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/exporter-trace-otlp-http/src/platform/index.ts","../../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.210.0_@opentelemetry+api@1.9.0/node_modules/@opentelemetry/exporter-trace-otlp-http/src/index.ts","../src/server/index.ts","../src/server/setup.ts","../src/server/config.ts"],"sourcesContent":["/*\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\nimport { ExportResult } from '@opentelemetry/core';\nimport { 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 *\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 * 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 *\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\nimport { 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 *\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\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 *\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\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 *\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 */\nimport {\n Baggage,\n BaggageEntryMetadata,\n baggageEntryMetadataFromString,\n} 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 *\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\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 *\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\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 *\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 */\nexport {\n SDK_INFO,\n _globalThis,\n otperformance,\n getBooleanFromEnv,\n getStringFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n} from './node';\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\nimport * 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 *\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\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 *\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\nexport { W3CBaggagePropagator } from './baggage/propagation/W3CBaggagePropagator';\nexport { AnchoredClock } from './common/anchored-clock';\nexport type { Clock } from './common/anchored-clock';\nexport { isAttributeValue, sanitizeAttributes } from './common/attributes';\nexport {\n globalErrorHandler,\n setGlobalErrorHandler,\n} from './common/global-error-handler';\nexport { loggingErrorHandler } from './common/logging-error-handler';\nexport {\n addHrTimes,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n hrTimeToMicroseconds,\n hrTimeToMilliseconds,\n hrTimeToNanoseconds,\n hrTimeToTimeStamp,\n isTimeInput,\n isTimeInputHrTime,\n millisToHrTime,\n timeInputToHrTime,\n} from './common/time';\nexport { unrefTimer } from './common/timer-util';\nexport type { ErrorHandler, InstrumentationScope } from './common/types';\nexport { ExportResultCode } from './ExportResult';\nexport type { ExportResult } from './ExportResult';\nexport { parseKeyPairsIntoRecord } from './baggage/utils';\nexport {\n SDK_INFO,\n _globalThis,\n getStringFromEnv,\n getBooleanFromEnv,\n getNumberFromEnv,\n getStringListFromEnv,\n otperformance,\n} from './platform';\nexport { CompositePropagator } from './propagation/composite';\nexport type { CompositePropagatorConfig } from './propagation/composite';\nexport {\n TRACE_PARENT_HEADER,\n TRACE_STATE_HEADER,\n W3CTraceContextPropagator,\n parseTraceParent,\n} from './trace/W3CTraceContextPropagator';\nexport {\n RPCType,\n deleteRPCMetadata,\n getRPCMetadata,\n setRPCMetadata,\n} from './trace/rpc-metadata';\nexport type { RPCMetadata } from './trace/rpc-metadata';\nexport {\n isTracingSuppressed,\n suppressTracing,\n unsuppressTracing,\n} from './trace/suppress-tracing';\nexport { TraceState } from './trace/TraceState';\nexport { merge } from './utils/merge';\nexport { TimeoutError, callWithTimeout } from './utils/timeout';\nexport { isUrlIgnored, urlMatches } from './utils/url';\nexport { BindOnceFuture } from './utils/callback';\nexport { diagLogLevelFromString } from './utils/configuration';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\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 */\nimport { diag } from '@opentelemetry/api';\nimport { 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 *\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\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport { IExporterTransport } from './exporter-transport';\nimport { IExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { OTLPExporterError } from './types';\nimport { IOtlpResponseHandler } from './response-handler';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport { diag, DiagLogger } 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 *\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\nexport { OTLPExporterBase } from './OTLPExporterBase';\nexport { OTLPExporterError } from './types';\n\nexport type {\n ExportResponse,\n ExportResponseFailure,\n ExportResponseSuccess,\n ExportResponseRetryable,\n} from './export-response';\n\nexport type { IExporterTransport } from './exporter-transport';\n\nexport {\n mergeOtlpSharedConfigurationWithDefaults,\n getSharedConfigurationDefaults,\n} from './configuration/shared-configuration';\nexport type { OtlpSharedConfiguration } from './configuration/shared-configuration';\n\nexport { CompressionAlgorithm } from './configuration/legacy-node-configuration';\nexport type { OTLPExporterNodeConfigBase } from './configuration/legacy-node-configuration';\nexport type { OTLPExporterConfigBase } from './configuration/legacy-base-configuration';\nexport type { IOtlpExportDelegate } from './otlp-export-delegate';\nexport { createOtlpNetworkExportDelegate } from './otlp-network-export-delegate';\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\nfunction intValue(charCode: number): number {\n // 0-9\n if (charCode >= 48 && charCode <= 57) {\n return charCode - 48;\n }\n\n // a-f\n if (charCode >= 97 && charCode <= 102) {\n return charCode - 87;\n }\n\n // A-F\n return charCode - 55;\n}\n\nexport function hexToBinary(hexStr: string): Uint8Array {\n const buf = new Uint8Array(hexStr.length / 2);\n let offset = 0;\n\n for (let i = 0; i < hexStr.length; i += 2) {\n const hi = intValue(hexStr.charCodeAt(i));\n const lo = intValue(hexStr.charCodeAt(i + 1));\n buf[offset++] = (hi << 4) | lo;\n }\n\n return buf;\n}\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\nimport type { OtlpEncodingOptions, Fixed64, LongBits } from './internal-types';\nimport { 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;\n\nexport interface Encoder {\n encodeHrTime: HrTimeEncodeFunction;\n encodeSpanContext: SpanContextEncodeFunction;\n encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\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\nconst DEFAULT_ENCODER: Encoder = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n};\n\nexport function getOtlpEncoder(options?: OtlpEncodingOptions): Encoder {\n if (options === undefined) {\n return DEFAULT_ENCODER;\n }\n\n const useLongBits = options.useLongBits ?? true;\n const useHex = options.useHex ?? false;\n return {\n encodeHrTime: useLongBits ? encodeAsLongBits : encodeTimestamp,\n encodeSpanContext: useHex ? identity : hexToBinary,\n encodeOptionalSpanContext: useHex ? identity : optionalHexToBinary,\n };\n}\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 */\nimport type {\n IAnyValue,\n IInstrumentationScope,\n IKeyValue,\n Resource,\n} from './internal-types';\nimport { Attributes } from '@opentelemetry/api';\nimport { InstrumentationScope } from '@opentelemetry/core';\nimport { Resource as ISdkResource } from '@opentelemetry/resources';\n\nexport function createResource(resource: ISdkResource): Resource {\n const result: Resource = {\n attributes: toAttributes(resource.attributes),\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(attributes: Attributes): IKeyValue[] {\n return Object.keys(attributes).map(key => toKeyValue(key, attributes[key]));\n}\n\nexport function toKeyValue(key: string, value: unknown): IKeyValue {\n return {\n key: key,\n value: toAnyValue(value),\n };\n}\n\nexport function toAnyValue(value: unknown): 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) return { bytesValue: value };\n if (Array.isArray(value))\n return { arrayValue: { values: value.map(toAnyValue) } };\n if (t === 'object' && value != null)\n return {\n kvlistValue: {\n values: Object.entries(value as object).map(([k, v]) =>\n toKeyValue(k, v)\n ),\n },\n };\n\n return {};\n}\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 */\nimport type { Link } from '@opentelemetry/api';\nimport { 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 {\n EStatusCode,\n IEvent,\n IExportTraceServiceRequest,\n ILink,\n IResourceSpans,\n IScopeSpans,\n ISpan,\n} from './internal-types';\nimport { OtlpEncodingOptions } from '../common/internal-types';\nimport { getOtlpEncoder } from '../common/utils';\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),\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) : [],\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)\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 options?: OtlpEncodingOptions\n): IExportTraceServiceRequest {\n const encoder = getOtlpEncoder(options);\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);\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 *\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 */\nimport { ISerializer } from '../../i-serializer';\nimport { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { IExportTraceServiceResponse } from '../export-response';\nimport { createExportTraceServiceRequest } from '../internal';\n\nexport const JsonTraceSerializer: ISerializer<\n ReadableSpan[],\n IExportTraceServiceResponse\n> = {\n serializeRequest: (arg: ReadableSpan[]) => {\n const request = createExportTraceServiceRequest(arg, {\n useHex: true,\n useLongBits: false,\n });\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 *\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// IMPORTANT: exports added here are public\nexport { JsonTraceSerializer } from './trace';\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\nexport type {\n IExportMetricsPartialSuccess,\n IExportMetricsServiceResponse,\n} from './metrics';\nexport type {\n IExportTracePartialSuccess,\n IExportTraceServiceResponse,\n} from './trace';\nexport type {\n IExportLogsServiceResponse,\n IExportLogsPartialSuccess,\n} from './logs';\n\nexport { ProtobufLogsSerializer } from './logs/protobuf';\nexport { ProtobufMetricsSerializer } from './metrics/protobuf';\nexport { ProtobufTraceSerializer } from './trace/protobuf';\n\nexport { JsonLogsSerializer } from './logs/json';\nexport { JsonMetricsSerializer } from './metrics/json';\nexport { JsonTraceSerializer } from './trace/json';\n\nexport type { ISerializer } from './i-serializer';\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\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 *\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\nimport {\n getSharedConfigurationDefaults,\n mergeOtlpSharedConfigurationWithDefaults,\n OtlpSharedConfiguration,\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 *\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 */\nimport {\n getHttpConfigurationDefaults,\n mergeOtlpHttpConfigurationWithDefaults,\n OtlpHttpConfiguration,\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 *\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\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 *\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// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.210.0';\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 */\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport * as zlib from 'zlib';\nimport { Readable } from 'stream';\nimport { 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 params\n * @param agent\n * @param data\n * @param onDone\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 onDone: (response: ExportResponse) => void,\n timeoutMillis: number\n): void {\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 onDone({\n status: 'success',\n data: Buffer.concat(responseData),\n });\n } else if (res.statusCode && isExportHTTPErrorRetryable(res.statusCode)) {\n onDone({\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 onDone({\n status: 'failure',\n error,\n });\n }\n });\n });\n\n req.setTimeout(timeoutMillis, () => {\n req.destroy();\n onDone({\n status: 'retryable',\n error: new Error('Request timed out'),\n });\n });\n\n req.on('error', (error: Error) => {\n if (isHttpTransportNetworkErrorRetryable(error)) {\n onDone({\n status: 'retryable',\n error,\n });\n } else {\n onDone({\n status: 'failure',\n error,\n });\n }\n });\n\n compressAndSend(req, compression, data, (error: Error) => {\n onDone({\n status: 'failure',\n error,\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 *\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// 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 { ExportResponse } from '../export-response';\nimport { IExporterTransport } from '../exporter-transport';\nimport { sendWithHttp } from './http-transport-utils';\nimport { 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 new Promise<ExportResponse>(resolve => {\n sendWithHttp(\n request,\n this._parameters.url,\n headers,\n this._parameters.compression,\n this._parameters.userAgent,\n agent,\n data,\n result => {\n resolve(result);\n },\n timeoutMillis\n );\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 *\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\nimport { IExporterTransport } from './exporter-transport';\nimport { 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 succeded 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 *\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 */\nimport {\n createOtlpExportDelegate,\n IOtlpExportDelegate,\n} from './otlp-export-delegate';\nimport { 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 { 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 *\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 */\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport { 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 *\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 */\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 {\n OtlpNodeHttpConfiguration,\n httpAgentFactoryFromOptions,\n} 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 *\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\nimport { OTLPExporterConfigBase } from './legacy-base-configuration';\nimport { wrapStaticHeadersInFunction } from './shared-configuration';\nimport { 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 *\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 */\nimport { OTLPExporterNodeConfigBase } from './legacy-node-configuration';\nimport { diag } from '@opentelemetry/api';\nimport {\n getNodeHttpConfigurationDefaults,\n HttpAgentFactory,\n mergeOtlpNodeHttpConfigurationWithDefaults,\n OtlpNodeHttpConfiguration,\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 *\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\nexport { httpAgentFactoryFromOptions } from './configuration/otlp-node-http-configuration';\nexport { createOtlpHttpExportDelegate } from './otlp-http-export-delegate';\nexport { getSharedConfigurationFromEnvironment } from './configuration/shared-env-configuration';\nexport { convertLegacyHttpOptions } from './configuration/convert-legacy-node-http-options';\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\nimport { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport {\n OTLPExporterNodeConfigBase,\n OTLPExporterBase,\n} 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 *\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\nexport { OTLPTraceExporter } from './OTLPTraceExporter';\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\nexport { OTLPTraceExporter } from './node';\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\nexport { OTLPTraceExporter } from './platform';\n","/**\n * Server utilities for AG-Kit observability.\n *\n * Provides server-side observability features like AUTO_TRACES_STDOUT\n * and unified trace exporter configuration.\n *\n * @packageDocumentation\n */\n\n// Unified setup API\nexport {\n setupObservability,\n type ObservabilityConfig,\n type ConsoleTraceConfig,\n type OTLPTraceConfig,\n type CustomTraceConfig,\n type BatchConfig,\n} from './setup.js';\n\n// Exporter type constants\nexport { ExporterType } from './config.js';\n","/**\n * Observability setup implementation for AG-Kit Server.\n *\n * Merges configuration from environment variables and parameters,\n * then applies each exporter configuration.\n *\n * @packageDocumentation\n */\n\nimport type {\n BatchConfig,\n ObservabilityConfig,\n ConsoleTraceConfig,\n OTLPTraceConfig,\n CustomTraceConfig,\n} from './config';\n\nexport type {\n BatchConfig,\n ObservabilityConfig,\n ConsoleTraceConfig,\n OTLPTraceConfig,\n CustomTraceConfig,\n} from './config';\n\n/**\n * Environment variable truthy values.\n * Matches Python SDK implementation for consistency.\n */\nconst TRUTHY_ENV_VALUES = new Set(['true', '1', 'yes', 'on']);\n\n/**\n * Merged configuration result.\n * Console config allows merge (param overrides env),\n * while OTLP and custom configs are arrays (additive).\n */\ninterface MergedConfig {\n console?: ConsoleTraceConfig | null;\n otlp: OTLPTraceConfig[];\n custom: CustomTraceConfig[];\n}\n\n/**\n * Default batch configuration.\n */\nconst DEFAULT_BATCH_CONFIG: Required<BatchConfig> = {\n maxExportBatchSize: 100,\n scheduledDelayMillis: 5000,\n maxQueueSize: 2048,\n exportTimeoutMillis: 30000,\n};\n\n/**\n * Merge environment variable and parameter configurations.\n *\n * - AUTO_TRACES_STDOUT env adds a console config\n * - Parameter configs override/extend env configs\n */\nfunction mergeConfigs(paramConfigs: ObservabilityConfig[]): MergedConfig {\n const result: MergedConfig = {\n console: null,\n otlp: [],\n custom: [],\n };\n\n // 1. Check AUTO_TRACES_STDOUT env\n const autoTracesStdout = process.env.AUTO_TRACES_STDOUT?.toLowerCase() || '';\n if (TRUTHY_ENV_VALUES.has(autoTracesStdout)) {\n result.console = { type: 'console' };\n console.debug(\n `[Observability] AUTO_TRACES_STDOUT=${autoTracesStdout}, console exporter enabled`\n );\n }\n\n // 2. Process parameter configs\n for (const config of paramConfigs) {\n switch (config.type) {\n case 'console':\n // Parameter overrides env (merge batch config)\n result.console = { ...result.console, ...config };\n break;\n\n case 'otlp':\n result.otlp.push(config);\n break;\n\n case 'custom':\n result.custom.push(config);\n break;\n }\n }\n\n return result;\n}\n\n/**\n * Apply batch configuration with defaults.\n */\nfunction resolveBatchConfig(batch?: BatchConfig): Required<BatchConfig> {\n return { ...DEFAULT_BATCH_CONFIG, ...batch };\n}\n\n/**\n * Safe wrapper for exporter setup functions.\n * Ensures individual exporter failures don't crash the entire setup.\n */\nasync function safeSetup(\n name: string,\n setupFn: () => Promise<void>\n): Promise<void> {\n try {\n await setupFn();\n } catch (error) {\n console.warn(\n `[Observability] ${name} setup failed (non-fatal): ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n // Don't rethrow - allow other exporters to continue\n }\n}\n\n/**\n * Setup console exporter.\n */\nasync function setupConsoleExporter(config: ConsoleTraceConfig): Promise<void> {\n const { trace } = await import('@opentelemetry/api');\n const { resourceFromAttributes } = await import('@opentelemetry/resources');\n const { NodeTracerProvider } = await import('@opentelemetry/sdk-trace-node');\n const { ConsoleSpanExporter, BatchSpanProcessor } = await import(\n '@opentelemetry/sdk-trace-base'\n );\n\n const batchConfig = resolveBatchConfig(config.batch);\n\n // Check if a real TracerProvider already exists\n let provider = trace.getTracerProvider();\n const isRealProvider = 'addSpanProcessor' in provider;\n\n if (isRealProvider) {\n // Add processor to existing provider\n const exporter = new ConsoleSpanExporter();\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n (provider as any).addSpanProcessor(processor);\n\n console.info(\n `[Observability] Console exporter configured (batch=${batchConfig.maxExportBatchSize}, ` +\n `delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n } else {\n // Create new provider with console exporter\n const resource = resourceFromAttributes({\n 'service.name': process.env.OTEL_SERVICE_NAME || 'ag-ui-server',\n 'service.version': '1.0.0',\n });\n\n const exporter = new ConsoleSpanExporter();\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n\n const tracerProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n tracerProvider.register();\n\n console.info(\n `[Observability] Console exporter configured (batch=${batchConfig.maxExportBatchSize}, ` +\n `delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n }\n}\n\n/**\n * Setup OTLP exporter.\n */\nasync function setupOTLPExporter(config: OTLPTraceConfig): Promise<void> {\n const { trace } = await import('@opentelemetry/api');\n const { resourceFromAttributes } = await import('@opentelemetry/resources');\n const { NodeTracerProvider } = await import('@opentelemetry/sdk-trace-node');\n const { OTLPTraceExporter } = await import('@opentelemetry/exporter-trace-otlp-http');\n const { BatchSpanProcessor } = await import('@opentelemetry/sdk-trace-base');\n\n const batchConfig = resolveBatchConfig(config.batch);\n\n // Check if a real TracerProvider already exists\n let provider = trace.getTracerProvider();\n const isRealProvider = 'addSpanProcessor' in provider;\n\n if (isRealProvider) {\n // Add processor to existing provider\n const exporter = new OTLPTraceExporter({\n url: config.url,\n headers: config.headers,\n timeoutMillis: config.timeout ?? 10000,\n });\n\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n (provider as any).addSpanProcessor(processor);\n\n console.info(\n `[Observability] OTLP exporter configured (url=${config.url}, ` +\n `batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n } else {\n // Create new provider with OTLP exporter\n const resource = resourceFromAttributes({\n 'service.name': process.env.OTEL_SERVICE_NAME || 'ag-ui-server',\n 'service.version': '1.0.0',\n });\n\n const exporter = new OTLPTraceExporter({\n url: config.url,\n headers: config.headers,\n timeoutMillis: config.timeout ?? 10000,\n });\n\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n\n const tracerProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n tracerProvider.register();\n\n console.info(\n `[Observability] OTLP exporter configured (url=${config.url}, ` +\n `batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n }\n}\n\n/**\n * Setup custom exporter.\n */\nasync function setupCustomExporter(config: CustomTraceConfig): Promise<void> {\n await config.setup();\n console.info(`[Observability] Custom exporter setup completed`);\n}\n\n/**\n * Setup observability from merged configuration.\n *\n * @internal\n */\nasync function applyMergedConfigs(merged: MergedConfig): Promise<void> {\n const setupTasks: Promise<void>[] = [];\n\n // Apply console (non-blocking)\n if (merged.console) {\n setupTasks.push(safeSetup('Console exporter', () => setupConsoleExporter(merged.console!)));\n }\n\n // Apply otlp (non-blocking)\n for (const otlp of merged.otlp) {\n setupTasks.push(safeSetup(`OTLP exporter (${otlp.url})`, () => setupOTLPExporter(otlp)));\n }\n\n // Apply custom (non-blocking)\n for (const custom of merged.custom) {\n setupTasks.push(safeSetup('Custom exporter', () => setupCustomExporter(custom)));\n }\n\n // Wait for all exporters to complete (or fail gracefully)\n await Promise.all(setupTasks);\n\n if (merged.console || merged.otlp.length > 0 || merged.custom.length > 0) {\n console.info(`[Observability] Setup completed`);\n }\n}\n\n/**\n * Setup observability from configuration.\n *\n * Merges environment variable (AUTO_TRACES_STDOUT) with parameter configs,\n * then applies each exporter configuration.\n *\n * Environment variables act as presets, parameter configs override or extend.\n *\n * Returns a promise that resolves when setup is complete. This allows callers\n * to await initialization before proceeding, eliminating race conditions.\n *\n * The returned promise is cached - subsequent calls return the same promise\n * to avoid duplicate initialization.\n *\n * @param configs - Observability configuration(s)\n *\n * @example\n * ```typescript\n * // Console only (from env)\n * await setupObservability();\n *\n * // Console + OTLP\n * await setupObservability([\n * { type: 'console' },\n * { type: 'otlp', url: 'http://localhost:4318/v1/traces' }\n * ]);\n *\n * // OTLP only\n * await setupObservability({\n * type: 'otlp',\n * url: 'https://cloud.langfuse.com/api/public/otlp/v1/traces',\n * headers: { 'Authorization': 'Basic xxx' }\n * });\n * ```\n *\n * @public\n */\n\nlet setupPromise: Promise<void> | null = null;\n\nexport async function setupObservability(\n configs?: ObservabilityConfig | ObservabilityConfig[]\n): Promise<void> {\n // Return cached promise if setup is in progress or completed\n if (setupPromise) {\n return setupPromise;\n }\n\n // Create the setup promise\n setupPromise = (async () => {\n try {\n // Normalize to array\n const configsArray = configs\n ? Array.isArray(configs)\n ? configs\n : [configs]\n : [];\n\n // Merge env and parameter configs\n const merged = mergeConfigs(configsArray);\n\n // Apply merged configs\n await applyMergedConfigs(merged);\n } catch (error) {\n // Reset promise on error to allow retry\n setupPromise = null;\n throw error;\n }\n })();\n\n return setupPromise;\n}\n","/**\n * Observability configuration types for AG-Kit Server.\n *\n * Provides a unified configuration interface for trace exporters:\n * - Console: Development/debugging output\n * - OTLP: Production export to Langfuse, Jaeger, etc.\n * - Custom: User-defined setup logic\n *\n * @packageDocumentation\n */\n\n/**\n * Trace exporter type constants.\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * { type: ExporterType.Console }\n * { type: ExporterType.OTLP }\n * { type: ExporterType.Custom }\n * ```\n *\n * @public\n */\nexport const ExporterType = {\n /** Console exporter - outputs traces to stdout */\n Console: 'console',\n /** OTLP exporter - sends traces to OTLP-compatible backend */\n OTLP: 'otlp',\n /** Custom exporter - user-defined setup logic */\n Custom: 'custom',\n} as const;\n\n/**\n * Trace exporter type literal values.\n *\n * @public\n */\nexport type ExporterType = typeof ExporterType[keyof typeof ExporterType];\n\n/**\n * Batch processing configuration for span exporters.\n *\n * Used by BatchSpanProcessor to optimize performance:\n * - Collects spans in memory and exports them in batches\n * - Reduces I/O operations (console) or network requests (OTLP)\n * - Recommended for production environments\n *\n * @public\n */\nexport interface BatchConfig {\n /** Maximum number of spans per export batch (default: 100) */\n maxExportBatchSize?: number;\n /** Maximum delay in milliseconds before exporting (default: 5000) */\n scheduledDelayMillis?: number;\n /** Maximum queue size (default: 2048) */\n maxQueueSize?: number;\n /** Export timeout in milliseconds (default: 30000) */\n exportTimeoutMillis?: number;\n}\n\n/**\n * Console trace exporter configuration.\n *\n * Outputs traces to stdout in JSON format using ConsoleSpanExporter.\n * Useful for development and debugging.\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * { type: ExporterType.Console }\n * { type: ExporterType.Console, batch: { maxExportBatchSize: 200 } }\n * ```\n *\n * @public\n */\nexport interface ConsoleTraceConfig {\n /** Discriminator for console exporter */\n type: typeof ExporterType.Console;\n /** Optional batch processing configuration */\n batch?: BatchConfig;\n}\n\n/**\n * OTLP trace exporter configuration.\n *\n * Exports traces via OTLP protocol to any compatible backend:\n * - Langfuse: https://cloud.langfuse.com/api/public/otlp/v1/traces\n * - Jaeger: http://localhost:4318/v1/traces\n * - OTel Collector: custom endpoint\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * {\n * type: ExporterType.OTLP,\n * url: 'https://cloud.langfuse.com/api/public/otlp/v1/traces',\n * headers: {\n * 'Authorization': 'Basic ' + btoa('pk-lf-xxx:sk-lf-xxx')\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface OTLPTraceConfig {\n /** Discriminator for OTLP exporter */\n type: typeof ExporterType.OTLP;\n /** OTLP endpoint URL (http/https) */\n url: string;\n /** Optional HTTP headers for authentication */\n headers?: Record<string, string>;\n /** Request timeout in milliseconds (default: 10000) */\n timeout?: number;\n /** Optional batch processing configuration */\n batch?: BatchConfig;\n}\n\n/**\n * Custom trace exporter configuration.\n *\n * Allows users to provide custom trace setup logic.\n * Useful for integrations not covered by console/otlp.\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * {\n * type: ExporterType.Custom,\n * setup: async () => {\n * const exporter = new MyCustomExporter();\n * const provider = new BasicTracerProvider();\n * provider.addSpanProcessor(new SimpleSpanProcessor(exporter));\n * provider.register();\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface CustomTraceConfig {\n /** Discriminator for custom setup */\n type: typeof ExporterType.Custom;\n /** User-defined setup function */\n setup: () => Promise<void> | void;\n}\n\n/**\n * Union type of all supported trace exporter configurations.\n *\n * @public\n */\nexport type ObservabilityConfig =\n | ConsoleTraceConfig\n | OTLPTraceConfig\n | CustomTraceConfig;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAmBa;AAnBb;;;AAmBM,IAAO,mBAAP,MAAuB;MACnB;MACR,YAAY,UAAuC;AACjD,aAAK,YAAY;MACnB;;;;;;MAOA,OACE,OACA,gBAA8C;AAE9C,aAAK,UAAU,OAAO,OAAO,cAAc;MAC7C;MAEA,aAAU;AACR,eAAO,KAAK,UAAU,WAAU;MAClC;MAEA,WAAQ;AACN,eAAO,KAAK,UAAU,SAAQ;MAChC;;;;;;AC3CF,IAmBa;AAnBb;;;AAmBM,IAAO,oBAAP,cAAiC,MAAK;MACjC;MACS,OAAe;MACxB;MAET,YAAY,SAAkB,MAAe,MAAa;AACxD,cAAM,OAAO;AACb,aAAK,OAAO;AACZ,aAAK,OAAO;MACd;;;;;;ACII,SAAU,sBAAsB,eAAqB;AACzD,MAAI,OAAO,SAAS,aAAa,KAAK,gBAAgB,GAAG;AACvD,WAAO;;AAET,QAAM,IAAI,MACR,qFAAqF,aAAa,IAAI;AAE1G;AAEM,SAAU,4BACd,SAA2C;AAE3C,MAAI,WAAW,MAAM;AACnB,WAAO;;AAGT,SAAO,YAAY;AACrB;AAOM,SAAU,yCACd,2BACA,uBACA,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,eAAW,KAAK,UAAU,kBAAkB,KAAK,GAAG,KAAK,MAAM,kBAAkB,IAAI,CAAC,CAAC;AAAA,EACzF;AAGA,aAAW,UAAU,OAAO,QAAQ;AAClC,eAAW,KAAK,UAAU,mBAAmB,MAAM,oBAAoB,MAAM,CAAC,CAAC;AAAA,EACjF;AAGA,QAAM,QAAQ,IAAI,UAAU;AAE5B,MAAI,OAAO,WAAW,OAAO,KAAK,SAAS,KAAK,OAAO,OAAO,SAAS,GAAG;AACxE,YAAQ,KAAK,iCAAiC;AAAA,EAChD;AACF;AAwCA,IAAI,eAAqC;AAEzC,eAAsB,mBACpB,SACe;AAEf,MAAI,cAAc;AAChB,WAAO;AAAA,EACT;AAGA,kBAAgB,YAAY;AAC1B,QAAI;AAEF,YAAM,eAAe,UACjB,MAAM,QAAQ,OAAO,IACnB,UACA,CAAC,OAAO,IACV,CAAC;AAGL,YAAM,SAAS,aAAa,YAAY;AAGxC,YAAM,mBAAmB,MAAM;AAAA,IACjC,SAAS,OAAO;AAEd,qBAAe;AACf,YAAM;AAAA,IACR;AAAA,EACF,GAAG;AAEH,SAAO;AACT;;;AC9TO,IAAM,eAAe;AAAA;AAAA,EAE1B,SAAS;AAAA;AAAA,EAET,MAAM;AAAA;AAAA,EAEN,QAAQ;AACV;","names":["import_api","ExportResultCode","import_api","import_api","init_esm","hrTime","init_utils","init_internal","init_utils","init_internal","init_esm","import_api","module","module","resolve","import_api","resolve","import_api","path","import_api","import_api","init_esm","init_node","init_platform","init_node","init_esm","init_platform","OTLPTraceExporter"]}
|
package/dist/server.mjs
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import "./chunk-NFEGQTCC.mjs";
|
|
2
|
+
|
|
3
|
+
// src/server/setup.ts
|
|
4
|
+
var TRUTHY_ENV_VALUES = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
5
|
+
var DEFAULT_BATCH_CONFIG = {
|
|
6
|
+
maxExportBatchSize: 100,
|
|
7
|
+
scheduledDelayMillis: 5e3,
|
|
8
|
+
maxQueueSize: 2048,
|
|
9
|
+
exportTimeoutMillis: 3e4
|
|
10
|
+
};
|
|
11
|
+
function mergeConfigs(paramConfigs) {
|
|
12
|
+
const result = {
|
|
13
|
+
console: null,
|
|
14
|
+
otlp: [],
|
|
15
|
+
custom: []
|
|
16
|
+
};
|
|
17
|
+
const autoTracesStdout = process.env.AUTO_TRACES_STDOUT?.toLowerCase() || "";
|
|
18
|
+
if (TRUTHY_ENV_VALUES.has(autoTracesStdout)) {
|
|
19
|
+
result.console = { type: "console" };
|
|
20
|
+
console.debug(
|
|
21
|
+
`[Observability] AUTO_TRACES_STDOUT=${autoTracesStdout}, console exporter enabled`
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
for (const config of paramConfigs) {
|
|
25
|
+
switch (config.type) {
|
|
26
|
+
case "console":
|
|
27
|
+
result.console = { ...result.console, ...config };
|
|
28
|
+
break;
|
|
29
|
+
case "otlp":
|
|
30
|
+
result.otlp.push(config);
|
|
31
|
+
break;
|
|
32
|
+
case "custom":
|
|
33
|
+
result.custom.push(config);
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
function resolveBatchConfig(batch) {
|
|
40
|
+
return { ...DEFAULT_BATCH_CONFIG, ...batch };
|
|
41
|
+
}
|
|
42
|
+
async function safeSetup(name, setupFn) {
|
|
43
|
+
try {
|
|
44
|
+
await setupFn();
|
|
45
|
+
} catch (error) {
|
|
46
|
+
console.warn(
|
|
47
|
+
`[Observability] ${name} setup failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function setupConsoleExporter(config) {
|
|
52
|
+
const { trace } = await import("@opentelemetry/api");
|
|
53
|
+
const { resourceFromAttributes } = await import("@opentelemetry/resources");
|
|
54
|
+
const { NodeTracerProvider } = await import("@opentelemetry/sdk-trace-node");
|
|
55
|
+
const { ConsoleSpanExporter, BatchSpanProcessor } = await import("@opentelemetry/sdk-trace-base");
|
|
56
|
+
const batchConfig = resolveBatchConfig(config.batch);
|
|
57
|
+
let provider = trace.getTracerProvider();
|
|
58
|
+
const isRealProvider = "addSpanProcessor" in provider;
|
|
59
|
+
if (isRealProvider) {
|
|
60
|
+
const exporter = new ConsoleSpanExporter();
|
|
61
|
+
const processor = new BatchSpanProcessor(exporter, batchConfig);
|
|
62
|
+
provider.addSpanProcessor(processor);
|
|
63
|
+
console.info(
|
|
64
|
+
`[Observability] Console exporter configured (batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`
|
|
65
|
+
);
|
|
66
|
+
} else {
|
|
67
|
+
const resource = resourceFromAttributes({
|
|
68
|
+
"service.name": process.env.OTEL_SERVICE_NAME || "ag-ui-server",
|
|
69
|
+
"service.version": "1.0.0"
|
|
70
|
+
});
|
|
71
|
+
const exporter = new ConsoleSpanExporter();
|
|
72
|
+
const processor = new BatchSpanProcessor(exporter, batchConfig);
|
|
73
|
+
const tracerProvider = new NodeTracerProvider({
|
|
74
|
+
resource,
|
|
75
|
+
spanProcessors: [processor]
|
|
76
|
+
});
|
|
77
|
+
tracerProvider.register();
|
|
78
|
+
console.info(
|
|
79
|
+
`[Observability] Console exporter configured (batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async function setupOTLPExporter(config) {
|
|
84
|
+
const { trace } = await import("@opentelemetry/api");
|
|
85
|
+
const { resourceFromAttributes } = await import("@opentelemetry/resources");
|
|
86
|
+
const { NodeTracerProvider } = await import("@opentelemetry/sdk-trace-node");
|
|
87
|
+
const { OTLPTraceExporter } = await import("./esm-PGEDANAI.mjs");
|
|
88
|
+
const { BatchSpanProcessor } = await import("@opentelemetry/sdk-trace-base");
|
|
89
|
+
const batchConfig = resolveBatchConfig(config.batch);
|
|
90
|
+
let provider = trace.getTracerProvider();
|
|
91
|
+
const isRealProvider = "addSpanProcessor" in provider;
|
|
92
|
+
if (isRealProvider) {
|
|
93
|
+
const exporter = new OTLPTraceExporter({
|
|
94
|
+
url: config.url,
|
|
95
|
+
headers: config.headers,
|
|
96
|
+
timeoutMillis: config.timeout ?? 1e4
|
|
97
|
+
});
|
|
98
|
+
const processor = new BatchSpanProcessor(exporter, batchConfig);
|
|
99
|
+
provider.addSpanProcessor(processor);
|
|
100
|
+
console.info(
|
|
101
|
+
`[Observability] OTLP exporter configured (url=${config.url}, batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`
|
|
102
|
+
);
|
|
103
|
+
} else {
|
|
104
|
+
const resource = resourceFromAttributes({
|
|
105
|
+
"service.name": process.env.OTEL_SERVICE_NAME || "ag-ui-server",
|
|
106
|
+
"service.version": "1.0.0"
|
|
107
|
+
});
|
|
108
|
+
const exporter = new OTLPTraceExporter({
|
|
109
|
+
url: config.url,
|
|
110
|
+
headers: config.headers,
|
|
111
|
+
timeoutMillis: config.timeout ?? 1e4
|
|
112
|
+
});
|
|
113
|
+
const processor = new BatchSpanProcessor(exporter, batchConfig);
|
|
114
|
+
const tracerProvider = new NodeTracerProvider({
|
|
115
|
+
resource,
|
|
116
|
+
spanProcessors: [processor]
|
|
117
|
+
});
|
|
118
|
+
tracerProvider.register();
|
|
119
|
+
console.info(
|
|
120
|
+
`[Observability] OTLP exporter configured (url=${config.url}, batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
async function setupCustomExporter(config) {
|
|
125
|
+
await config.setup();
|
|
126
|
+
console.info(`[Observability] Custom exporter setup completed`);
|
|
127
|
+
}
|
|
128
|
+
async function applyMergedConfigs(merged) {
|
|
129
|
+
const setupTasks = [];
|
|
130
|
+
if (merged.console) {
|
|
131
|
+
setupTasks.push(safeSetup("Console exporter", () => setupConsoleExporter(merged.console)));
|
|
132
|
+
}
|
|
133
|
+
for (const otlp of merged.otlp) {
|
|
134
|
+
setupTasks.push(safeSetup(`OTLP exporter (${otlp.url})`, () => setupOTLPExporter(otlp)));
|
|
135
|
+
}
|
|
136
|
+
for (const custom of merged.custom) {
|
|
137
|
+
setupTasks.push(safeSetup("Custom exporter", () => setupCustomExporter(custom)));
|
|
138
|
+
}
|
|
139
|
+
await Promise.all(setupTasks);
|
|
140
|
+
if (merged.console || merged.otlp.length > 0 || merged.custom.length > 0) {
|
|
141
|
+
console.info(`[Observability] Setup completed`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
var setupPromise = null;
|
|
145
|
+
async function setupObservability(configs) {
|
|
146
|
+
if (setupPromise) {
|
|
147
|
+
return setupPromise;
|
|
148
|
+
}
|
|
149
|
+
setupPromise = (async () => {
|
|
150
|
+
try {
|
|
151
|
+
const configsArray = configs ? Array.isArray(configs) ? configs : [configs] : [];
|
|
152
|
+
const merged = mergeConfigs(configsArray);
|
|
153
|
+
await applyMergedConfigs(merged);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
setupPromise = null;
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
})();
|
|
159
|
+
return setupPromise;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/server/config.ts
|
|
163
|
+
var ExporterType = {
|
|
164
|
+
/** Console exporter - outputs traces to stdout */
|
|
165
|
+
Console: "console",
|
|
166
|
+
/** OTLP exporter - sends traces to OTLP-compatible backend */
|
|
167
|
+
OTLP: "otlp",
|
|
168
|
+
/** Custom exporter - user-defined setup logic */
|
|
169
|
+
Custom: "custom"
|
|
170
|
+
};
|
|
171
|
+
export {
|
|
172
|
+
ExporterType,
|
|
173
|
+
setupObservability
|
|
174
|
+
};
|
|
175
|
+
//# sourceMappingURL=server.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/setup.ts","../src/server/config.ts"],"sourcesContent":["/**\n * Observability setup implementation for AG-Kit Server.\n *\n * Merges configuration from environment variables and parameters,\n * then applies each exporter configuration.\n *\n * @packageDocumentation\n */\n\nimport type {\n BatchConfig,\n ObservabilityConfig,\n ConsoleTraceConfig,\n OTLPTraceConfig,\n CustomTraceConfig,\n} from './config';\n\nexport type {\n BatchConfig,\n ObservabilityConfig,\n ConsoleTraceConfig,\n OTLPTraceConfig,\n CustomTraceConfig,\n} from './config';\n\n/**\n * Environment variable truthy values.\n * Matches Python SDK implementation for consistency.\n */\nconst TRUTHY_ENV_VALUES = new Set(['true', '1', 'yes', 'on']);\n\n/**\n * Merged configuration result.\n * Console config allows merge (param overrides env),\n * while OTLP and custom configs are arrays (additive).\n */\ninterface MergedConfig {\n console?: ConsoleTraceConfig | null;\n otlp: OTLPTraceConfig[];\n custom: CustomTraceConfig[];\n}\n\n/**\n * Default batch configuration.\n */\nconst DEFAULT_BATCH_CONFIG: Required<BatchConfig> = {\n maxExportBatchSize: 100,\n scheduledDelayMillis: 5000,\n maxQueueSize: 2048,\n exportTimeoutMillis: 30000,\n};\n\n/**\n * Merge environment variable and parameter configurations.\n *\n * - AUTO_TRACES_STDOUT env adds a console config\n * - Parameter configs override/extend env configs\n */\nfunction mergeConfigs(paramConfigs: ObservabilityConfig[]): MergedConfig {\n const result: MergedConfig = {\n console: null,\n otlp: [],\n custom: [],\n };\n\n // 1. Check AUTO_TRACES_STDOUT env\n const autoTracesStdout = process.env.AUTO_TRACES_STDOUT?.toLowerCase() || '';\n if (TRUTHY_ENV_VALUES.has(autoTracesStdout)) {\n result.console = { type: 'console' };\n console.debug(\n `[Observability] AUTO_TRACES_STDOUT=${autoTracesStdout}, console exporter enabled`\n );\n }\n\n // 2. Process parameter configs\n for (const config of paramConfigs) {\n switch (config.type) {\n case 'console':\n // Parameter overrides env (merge batch config)\n result.console = { ...result.console, ...config };\n break;\n\n case 'otlp':\n result.otlp.push(config);\n break;\n\n case 'custom':\n result.custom.push(config);\n break;\n }\n }\n\n return result;\n}\n\n/**\n * Apply batch configuration with defaults.\n */\nfunction resolveBatchConfig(batch?: BatchConfig): Required<BatchConfig> {\n return { ...DEFAULT_BATCH_CONFIG, ...batch };\n}\n\n/**\n * Safe wrapper for exporter setup functions.\n * Ensures individual exporter failures don't crash the entire setup.\n */\nasync function safeSetup(\n name: string,\n setupFn: () => Promise<void>\n): Promise<void> {\n try {\n await setupFn();\n } catch (error) {\n console.warn(\n `[Observability] ${name} setup failed (non-fatal): ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n // Don't rethrow - allow other exporters to continue\n }\n}\n\n/**\n * Setup console exporter.\n */\nasync function setupConsoleExporter(config: ConsoleTraceConfig): Promise<void> {\n const { trace } = await import('@opentelemetry/api');\n const { resourceFromAttributes } = await import('@opentelemetry/resources');\n const { NodeTracerProvider } = await import('@opentelemetry/sdk-trace-node');\n const { ConsoleSpanExporter, BatchSpanProcessor } = await import(\n '@opentelemetry/sdk-trace-base'\n );\n\n const batchConfig = resolveBatchConfig(config.batch);\n\n // Check if a real TracerProvider already exists\n let provider = trace.getTracerProvider();\n const isRealProvider = 'addSpanProcessor' in provider;\n\n if (isRealProvider) {\n // Add processor to existing provider\n const exporter = new ConsoleSpanExporter();\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n (provider as any).addSpanProcessor(processor);\n\n console.info(\n `[Observability] Console exporter configured (batch=${batchConfig.maxExportBatchSize}, ` +\n `delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n } else {\n // Create new provider with console exporter\n const resource = resourceFromAttributes({\n 'service.name': process.env.OTEL_SERVICE_NAME || 'ag-ui-server',\n 'service.version': '1.0.0',\n });\n\n const exporter = new ConsoleSpanExporter();\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n\n const tracerProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n tracerProvider.register();\n\n console.info(\n `[Observability] Console exporter configured (batch=${batchConfig.maxExportBatchSize}, ` +\n `delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n }\n}\n\n/**\n * Setup OTLP exporter.\n */\nasync function setupOTLPExporter(config: OTLPTraceConfig): Promise<void> {\n const { trace } = await import('@opentelemetry/api');\n const { resourceFromAttributes } = await import('@opentelemetry/resources');\n const { NodeTracerProvider } = await import('@opentelemetry/sdk-trace-node');\n const { OTLPTraceExporter } = await import('@opentelemetry/exporter-trace-otlp-http');\n const { BatchSpanProcessor } = await import('@opentelemetry/sdk-trace-base');\n\n const batchConfig = resolveBatchConfig(config.batch);\n\n // Check if a real TracerProvider already exists\n let provider = trace.getTracerProvider();\n const isRealProvider = 'addSpanProcessor' in provider;\n\n if (isRealProvider) {\n // Add processor to existing provider\n const exporter = new OTLPTraceExporter({\n url: config.url,\n headers: config.headers,\n timeoutMillis: config.timeout ?? 10000,\n });\n\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n (provider as any).addSpanProcessor(processor);\n\n console.info(\n `[Observability] OTLP exporter configured (url=${config.url}, ` +\n `batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n } else {\n // Create new provider with OTLP exporter\n const resource = resourceFromAttributes({\n 'service.name': process.env.OTEL_SERVICE_NAME || 'ag-ui-server',\n 'service.version': '1.0.0',\n });\n\n const exporter = new OTLPTraceExporter({\n url: config.url,\n headers: config.headers,\n timeoutMillis: config.timeout ?? 10000,\n });\n\n const processor = new BatchSpanProcessor(exporter, batchConfig);\n\n const tracerProvider = new NodeTracerProvider({\n resource,\n spanProcessors: [processor],\n });\n\n tracerProvider.register();\n\n console.info(\n `[Observability] OTLP exporter configured (url=${config.url}, ` +\n `batch=${batchConfig.maxExportBatchSize}, delay=${batchConfig.scheduledDelayMillis}ms)`\n );\n }\n}\n\n/**\n * Setup custom exporter.\n */\nasync function setupCustomExporter(config: CustomTraceConfig): Promise<void> {\n await config.setup();\n console.info(`[Observability] Custom exporter setup completed`);\n}\n\n/**\n * Setup observability from merged configuration.\n *\n * @internal\n */\nasync function applyMergedConfigs(merged: MergedConfig): Promise<void> {\n const setupTasks: Promise<void>[] = [];\n\n // Apply console (non-blocking)\n if (merged.console) {\n setupTasks.push(safeSetup('Console exporter', () => setupConsoleExporter(merged.console!)));\n }\n\n // Apply otlp (non-blocking)\n for (const otlp of merged.otlp) {\n setupTasks.push(safeSetup(`OTLP exporter (${otlp.url})`, () => setupOTLPExporter(otlp)));\n }\n\n // Apply custom (non-blocking)\n for (const custom of merged.custom) {\n setupTasks.push(safeSetup('Custom exporter', () => setupCustomExporter(custom)));\n }\n\n // Wait for all exporters to complete (or fail gracefully)\n await Promise.all(setupTasks);\n\n if (merged.console || merged.otlp.length > 0 || merged.custom.length > 0) {\n console.info(`[Observability] Setup completed`);\n }\n}\n\n/**\n * Setup observability from configuration.\n *\n * Merges environment variable (AUTO_TRACES_STDOUT) with parameter configs,\n * then applies each exporter configuration.\n *\n * Environment variables act as presets, parameter configs override or extend.\n *\n * Returns a promise that resolves when setup is complete. This allows callers\n * to await initialization before proceeding, eliminating race conditions.\n *\n * The returned promise is cached - subsequent calls return the same promise\n * to avoid duplicate initialization.\n *\n * @param configs - Observability configuration(s)\n *\n * @example\n * ```typescript\n * // Console only (from env)\n * await setupObservability();\n *\n * // Console + OTLP\n * await setupObservability([\n * { type: 'console' },\n * { type: 'otlp', url: 'http://localhost:4318/v1/traces' }\n * ]);\n *\n * // OTLP only\n * await setupObservability({\n * type: 'otlp',\n * url: 'https://cloud.langfuse.com/api/public/otlp/v1/traces',\n * headers: { 'Authorization': 'Basic xxx' }\n * });\n * ```\n *\n * @public\n */\n\nlet setupPromise: Promise<void> | null = null;\n\nexport async function setupObservability(\n configs?: ObservabilityConfig | ObservabilityConfig[]\n): Promise<void> {\n // Return cached promise if setup is in progress or completed\n if (setupPromise) {\n return setupPromise;\n }\n\n // Create the setup promise\n setupPromise = (async () => {\n try {\n // Normalize to array\n const configsArray = configs\n ? Array.isArray(configs)\n ? configs\n : [configs]\n : [];\n\n // Merge env and parameter configs\n const merged = mergeConfigs(configsArray);\n\n // Apply merged configs\n await applyMergedConfigs(merged);\n } catch (error) {\n // Reset promise on error to allow retry\n setupPromise = null;\n throw error;\n }\n })();\n\n return setupPromise;\n}\n","/**\n * Observability configuration types for AG-Kit Server.\n *\n * Provides a unified configuration interface for trace exporters:\n * - Console: Development/debugging output\n * - OTLP: Production export to Langfuse, Jaeger, etc.\n * - Custom: User-defined setup logic\n *\n * @packageDocumentation\n */\n\n/**\n * Trace exporter type constants.\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * { type: ExporterType.Console }\n * { type: ExporterType.OTLP }\n * { type: ExporterType.Custom }\n * ```\n *\n * @public\n */\nexport const ExporterType = {\n /** Console exporter - outputs traces to stdout */\n Console: 'console',\n /** OTLP exporter - sends traces to OTLP-compatible backend */\n OTLP: 'otlp',\n /** Custom exporter - user-defined setup logic */\n Custom: 'custom',\n} as const;\n\n/**\n * Trace exporter type literal values.\n *\n * @public\n */\nexport type ExporterType = typeof ExporterType[keyof typeof ExporterType];\n\n/**\n * Batch processing configuration for span exporters.\n *\n * Used by BatchSpanProcessor to optimize performance:\n * - Collects spans in memory and exports them in batches\n * - Reduces I/O operations (console) or network requests (OTLP)\n * - Recommended for production environments\n *\n * @public\n */\nexport interface BatchConfig {\n /** Maximum number of spans per export batch (default: 100) */\n maxExportBatchSize?: number;\n /** Maximum delay in milliseconds before exporting (default: 5000) */\n scheduledDelayMillis?: number;\n /** Maximum queue size (default: 2048) */\n maxQueueSize?: number;\n /** Export timeout in milliseconds (default: 30000) */\n exportTimeoutMillis?: number;\n}\n\n/**\n * Console trace exporter configuration.\n *\n * Outputs traces to stdout in JSON format using ConsoleSpanExporter.\n * Useful for development and debugging.\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * { type: ExporterType.Console }\n * { type: ExporterType.Console, batch: { maxExportBatchSize: 200 } }\n * ```\n *\n * @public\n */\nexport interface ConsoleTraceConfig {\n /** Discriminator for console exporter */\n type: typeof ExporterType.Console;\n /** Optional batch processing configuration */\n batch?: BatchConfig;\n}\n\n/**\n * OTLP trace exporter configuration.\n *\n * Exports traces via OTLP protocol to any compatible backend:\n * - Langfuse: https://cloud.langfuse.com/api/public/otlp/v1/traces\n * - Jaeger: http://localhost:4318/v1/traces\n * - OTel Collector: custom endpoint\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * {\n * type: ExporterType.OTLP,\n * url: 'https://cloud.langfuse.com/api/public/otlp/v1/traces',\n * headers: {\n * 'Authorization': 'Basic ' + btoa('pk-lf-xxx:sk-lf-xxx')\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface OTLPTraceConfig {\n /** Discriminator for OTLP exporter */\n type: typeof ExporterType.OTLP;\n /** OTLP endpoint URL (http/https) */\n url: string;\n /** Optional HTTP headers for authentication */\n headers?: Record<string, string>;\n /** Request timeout in milliseconds (default: 10000) */\n timeout?: number;\n /** Optional batch processing configuration */\n batch?: BatchConfig;\n}\n\n/**\n * Custom trace exporter configuration.\n *\n * Allows users to provide custom trace setup logic.\n * Useful for integrations not covered by console/otlp.\n *\n * @example\n * ```typescript\n * import { ExporterType } from '@cloudbase/agent-observability/server';\n *\n * {\n * type: ExporterType.Custom,\n * setup: async () => {\n * const exporter = new MyCustomExporter();\n * const provider = new BasicTracerProvider();\n * provider.addSpanProcessor(new SimpleSpanProcessor(exporter));\n * provider.register();\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface CustomTraceConfig {\n /** Discriminator for custom setup */\n type: typeof ExporterType.Custom;\n /** User-defined setup function */\n setup: () => Promise<void> | void;\n}\n\n/**\n * Union type of all supported trace exporter configurations.\n *\n * @public\n */\nexport type ObservabilityConfig =\n | ConsoleTraceConfig\n | OTLPTraceConfig\n | CustomTraceConfig;\n"],"mappings":";;;AA6BA,IAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC;AAgB5D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