diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json index 78b618d..dec702f 100644 --- a/.agents/plugins/marketplace.json +++ b/.agents/plugins/marketplace.json @@ -1,14 +1,14 @@ { - "name": "codex-observability-plugin", + "name": "donadio-codex-observability", "interface": { - "displayName": "Langfuse" + "displayName": "Langfuse realtime tracing" }, "plugins": [ { "name": "tracing", "source": { - "source": "npm", - "package": "@langfuse/codex-observability-plugin" + "source": "local", + "path": "./plugins/tracing" }, "policy": { "installation": "AVAILABLE", diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f59b844 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +plugins/tracing/dist/index.mjs linguist-generated=true diff --git a/.github/codeql/config.yml b/.github/codeql/config.yml new file mode 100644 index 0000000..36d3b57 --- /dev/null +++ b/.github/codeql/config.yml @@ -0,0 +1,5 @@ +name: Plugin source analysis +# The standalone artifact embeds unchanged npm dependencies. CI rebuilds it +# byte-for-byte from the scanned TypeScript and the integrity-pinned lockfile. +paths-ignore: + - plugins/tracing/dist diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 022728f..49373a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,22 +19,25 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - name: Install pnpm - uses: pnpm/action-setup@v5 + uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5 - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version: 22.x + node-version: 22.22.2 cache: "pnpm" - name: Install dependencies - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --ignore-scripts --network-concurrency=4 --child-concurrency=1 - name: Lint run: pnpm run lint - name: Test run: pnpm test + + - name: Verify shipped bundle matches source + run: git diff --exit-code -- plugins/tracing/dist/index.mjs diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..93c0254 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,32 @@ +name: CodeQL source + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: codeql-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + analyze: + name: Analyze plugin source + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + security-events: write + actions: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4 + with: + languages: javascript-typescript + config-file: ./.github/codeql/config.yml + - uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4 + with: + category: /language:javascript-typescript diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dcbee3a..f882646 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,7 +22,7 @@ jobs: id-token: write steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - name: Validate release version @@ -38,15 +38,15 @@ jobs: exit 1 fi - name: Setup pnpm - uses: pnpm/action-setup@v5 + uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5 - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version: 22.x + node-version: 22.22.2 registry-url: https://registry.npmjs.org package-manager-cache: false - name: Install dependencies - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --ignore-scripts --network-concurrency=4 --child-concurrency=1 - name: Lint run: pnpm run lint - name: Test diff --git a/.gitignore b/.gitignore index 04b55b7..2db6910 100644 --- a/.gitignore +++ b/.gitignore @@ -4,12 +4,14 @@ node_modules/ # Codex writes a per-rollout dedup sidecar next to each transcript at runtime. *.jsonl.langfuse +*.jsonl.langfuse-* # Local debugging debug.log # Build output -plugins/tracing/dist/ +plugins/tracing/dist/* +!plugins/tracing/dist/index.mjs # Claude Code scratch space; globbed so a later `!` negation works. .claude/* diff --git a/README.md b/README.md index 774f3e7..a1d28a2 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,19 @@ -# Langfuse Codex Plugin +# Langfuse Codex Plugin — Donadio fork Codex plugin that sends OpenAI Codex session telemetry to Langfuse. It traces agent turns, model generations, reasoning summaries, system prompts, tool calls, images, subagent threads, skills, and token usage. -Langfuse also documents this integration on the [Codex integration page](https://langfuse.com/integrations/developer-tools/codex). +This fork uploads activity incrementally across all 12 supported Codex hooks. +The upstream project is [langfuse/codex-observability-plugin](https://github.com/langfuse/codex-observability-plugin). + +Langfuse also documents the upstream integration on the [Codex integration page](https://langfuse.com/integrations/developer-tools/codex). ## Quick Start Add the plugin marketplace: ```bash -codex plugin marketplace add langfuse/codex-observability-plugin +codex plugin marketplace add donadiosolutions/codex-observability-plugin --ref +codex plugin add tracing@donadio-codex-observability --json ``` Then enable hooks and the plugin in `~/.codex/config.toml`, or only for one project in `/.codex/config.toml`: @@ -18,19 +22,47 @@ Then enable hooks and the plugin in `~/.codex/config.toml`, or only for one proj [features] hooks = true -[plugins."tracing@codex-observability-plugin"] +[plugins."tracing@donadio-codex-observability"] enabled = true ``` -Restart Codex after changing the config. When **Hooks need review** appears, review the Langfuse `Stop` hook in `/hooks` and trust it. An installed and enabled plugin is not yet a trusted hook, and no traces are uploaded before you trust it. Codex records trust against the current hook hash, so a plugin update can require another review. +Restart Codex after changing the config. When **Hooks need review** appears, review the tracing hooks in `/hooks` and trust them. An installed and enabled plugin is not yet a trusted hook, and no traces are uploaded before you trust it. Codex records trust against the current hook hash, so a plugin update can require another review. ## Supported Versions -- Codex `0.143` and newer +- A Codex build supporting all hooks below and `async: true` command hooks + (the local `0.162.1` hook contract was inspected during validation) - Node.js `22` and newer -- The `npm` CLI on your `PATH`, which Codex uses to fetch the plugin from the npm registry +- Linux with the supplied `flock` command for exclusive uploader ownership +- Git access to this fork; the marketplace uses the shipped standalone bundle - Langfuse Cloud, or self-hosted Langfuse `3.95.0` and newer +## Delivery + +Every invocation records a hook event and uploads changed observations. Active +turns keep stable observation IDs as their input, output, usage, and completion +state change. Hook payloads cover transcript-flush races; child uploads resolve +their parent trace so a child can finish after its parent turn. + +Live activity hooks run asynchronously. `Stop`, `SubagentStop`, `Interrupt`, +and `SessionEnd` flush synchronously because Codex cancels outstanding async +hooks before invoking its session-end handlers. Codex limits `SessionEnd` +and `Interrupt` to three seconds; pending payloads are saved before transcript +discovery and remain retryable if that deadline interrupts delivery. The supported events +are `PreToolUse`, `PermissionRequest`, `PostToolUse`, `PreCompact`, `PostCompact`, +`SessionStart`, `SessionEnd`, `UserPromptSubmit`, `SubagentStart`, `SubagentStop`, +`Stop`, and `Interrupt`. + +Exports flush at 16 observations, an 8 MiB encoded request budget, or one second, +whichever comes first. A larger individual observation uses a single request +up to 256 MiB without truncation. Requests run sequentially. Failed or partially +acknowledged uploads remain retryable. Pending hook payloads and acknowledged +observation fingerprints are stored privately beside the root transcript; +concurrent invocations serialize delivery with a bounded lock. + +Delivery follows hook events; Codex currently has no hook for each streamed +model token. Langfuse visibility also includes its ingestion processing time. + ## Langfuse Credentials Create `~/.codex/langfuse.json` (global) or `/.codex/langfuse.json` (per-project) with your Langfuse credentials. @@ -70,6 +102,14 @@ The remaining options are settable both ways, as a `langfuse.json` key or as the Everything the plugin traces is uploaded to Langfuse, including prompts and tool inputs and outputs, so do not enable it for sessions containing data you do not want stored there. +## Build and review + +The Git marketplace ships `dist/index.mjs`. CI rebuilds it and requires byte +identity with the committed artifact. CodeQL analyzes the TypeScript source +and tests; the generated dependency bundle is excluded from duplicate source +analysis. Dependency integrity remains pinned in `pnpm-lock.yaml` and checked +by Socket. + ## Contributing See the [contributing guide](./CONTRIBUTING.md). diff --git a/package.json b/package.json index bcdba64..f78a0f0 100644 --- a/package.json +++ b/package.json @@ -10,20 +10,20 @@ "tracing", "opentelemetry" ], - "homepage": "https://github.com/langfuse/codex-observability-plugin#readme", + "homepage": "https://github.com/donadiosolutions/codex-observability-plugin#readme", "bugs": { - "url": "https://github.com/langfuse/codex-observability-plugin/issues" + "url": "https://github.com/donadiosolutions/codex-observability-plugin/issues" }, "license": "MIT", "author": "Langfuse", "repository": { "type": "git", - "url": "https://github.com/langfuse/codex-observability-plugin.git" + "url": "https://github.com/donadiosolutions/codex-observability-plugin.git" }, "type": "module", "scripts": { "build": "tsdown --config plugins/tracing/tsdown.config.ts", - "test": "pnpm run build && vitest run", + "test": "pnpm run build && vitest run --maxWorkers=1 --no-file-parallelism", "test:watch": "pnpm run build && vitest", "format": "prettier --write .", "format:check": "prettier --check .", @@ -36,6 +36,7 @@ "@opentelemetry/api": "^1.9.0", "@opentelemetry/core": "^2.11.0", "@opentelemetry/exporter-trace-otlp-http": "^0.222.0", + "@opentelemetry/otlp-transformer": "0.222.0", "@opentelemetry/resources": "^2.11.0", "@opentelemetry/sdk-trace-base": "^2.11.0", "@opentelemetry/sdk-trace-node": "^2.11.0", diff --git a/plugins/tracing/.codex-plugin/plugin.json b/plugins/tracing/.codex-plugin/plugin.json index 67a41fe..27df81e 100644 --- a/plugins/tracing/.codex-plugin/plugin.json +++ b/plugins/tracing/.codex-plugin/plugin.json @@ -1,21 +1,21 @@ { "name": "tracing", - "version": "0.4.2", + "version": "0.5.0-donadio.2", "description": "Trace OpenAI Codex sessions to Langfuse.", "author": { "name": "Langfuse", "email": "support@langfuse.com", "url": "https://langfuse.com" }, - "homepage": "https://github.com/langfuse/codex-observability-plugin#readme", - "repository": "https://github.com/langfuse/codex-observability-plugin", + "homepage": "https://github.com/donadiosolutions/codex-observability-plugin#readme", + "repository": "https://github.com/donadiosolutions/codex-observability-plugin", "license": "MIT", "keywords": ["codex", "hooks", "langfuse", "observability", "tracing"], "hooks": "./hooks/hooks.json", "interface": { "displayName": "Tracing", "shortDescription": "Trace Codex sessions to Langfuse", - "longDescription": "Uploads completed OpenAI Codex rollout transcripts to Langfuse so teams can inspect Codex sessions as traces: agent turns, model calls, tool executions, token usage, and subagent threads.", + "longDescription": "Uploads Codex activity incrementally across all supported hooks, with asynchronous delivery and acknowledged observation checkpoints.", "developerName": "Langfuse", "category": "Coding", "capabilities": ["Read"], diff --git a/plugins/tracing/dist/index.mjs b/plugins/tracing/dist/index.mjs new file mode 100644 index 0000000..49fb81a --- /dev/null +++ b/plugins/tracing/dist/index.mjs @@ -0,0 +1,36286 @@ +import { createRequire } from "node:module"; +import { createHash, randomBytes, randomUUID } from "node:crypto"; +import * as fs$1 from "node:fs/promises"; +import * as os$1 from "node:os"; +import * as path$1 from "node:path"; +import * as fs from "fs"; +import * as zlib from "zlib"; +import { Readable } from "stream"; +import * as path from "path"; +import { spawn } from "node:child_process"; +import { createReadStream } from "node:fs"; +import { createInterface } from "node:readline"; + +//#region \0rolldown/runtime.js +var __create = Object.create; +var __defProp$1 = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esmMin = (fn, res, err) => () => { + if (err) throw err[0]; + try { + return fn && (res = fn(fn = 0)), res; + } catch (e) { + throw err = [e], e; + } +}; +var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports); +var __exportAll = (all, no_symbols) => { + let target = {}; + for (var name in all) { + __defProp$1(target, name, { + get: all[name], + enumerable: true + }); + } + if (!no_symbols) { + __defProp$1(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp$1(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp$1(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); +var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp$1({}, "__esModule", { value: true }), mod); +var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))(); + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/util.js +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") return value.toString(); + return value; +} +var Cached = class { + constructor(getter) { + this._getter = getter; + this._value = void 0; + } + get value() { + const getter = this._getter; + if (getter !== void 0) { + this._value = getter(); + this._getter = void 0; + } + return this._value; + } +}; +function cached(getter) { + return new Cached(getter); +} +function nullish(input) { + return input === null || input === void 0; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); +} +/** +* Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. +* +* Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none. +*/ +function rawShape(def) { + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + return desc?.get ? desc.get.raw : desc?.value; +} +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true + }); +} +function putProp(target, key, value) { + if (key in target) assignProp(target, key, value); + else target[key] = value; +} +/** +* Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`. +* +* A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema. +*/ +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc = Object.getOwnPropertyDescriptor(raw, key); + if (!desc.enumerable) continue; + if (desc.get) deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + else putProp(target, key, wrap ? wrap(desc.value, key) : desc.value); + } +} +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc = Object.getOwnPropertyDescriptor(source, key); + if (!desc.enumerable) continue; + if (desc.get) deferProp(target, key, () => source[key]); + else putProp(target, key, desc.value); + } +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {}; +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const allowsEval = /* @__PURE__*/ cached(() => { + if (globalConfig.jitless) return false; + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false; + try { + new Function(""); + return true; + } catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (isObject(o) === false) return false; + const ctor = o.constructor; + if (ctor === void 0) return true; + if (typeof ctor !== "function") return true; + const prot = ctor.prototype; + if (isObject(prot) === false) return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false; + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) return { ...o }; + if (Array.isArray(o)) return [...o]; + if (o instanceof Map) return new Map(o); + if (o instanceof Set) return new Set(o); + return o; +} +const propertyKeyTypes = /* @__PURE__*/ new Set([ + "string", + "number", + "symbol" +]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) return {}; + if (typeof params === "string") return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") return { + ...params, + error: () => params.error + }; + return params; +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") return value.toString() + "n"; + if (typeof value === "string") return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; + }); +} +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")] +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements"); + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { + shape: newShape, + checks: [] + })); +} +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) throw new Error(`Unrecognized key: "${String(key)}"`); + if (mask[key]) keys.push(key); + } + return keys; +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements"); + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { + shape: newShape, + checks: [] + })); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object"); + const checks = schema._zod.def.checks; + if (checks && checks.length > 0) { + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object"); + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function merge(a, b) { + if (!b?._zod?.def) throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + if (a._zod.def.checks?.length) throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b))); + return clone(a, mergeDefs(a._zod.def, { + shape: newShape, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [] + })); +} +function partial(Class, schema, mask, name = "partial") { + const checks = schema._zod.def.checks; + if (checks && checks.length > 0) throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class && ((value, key) => selected && !selected.has(key) ? value : new Class({ + type: "optional", + innerType: value + }))); + return clone(schema, mergeDefs(schema._zod.def, { + shape: newShape, + checks: [] + })); +} +function required(Class, schema, mask) { + const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => selected && !selected.has(key) ? value : new Class({ + type: "nonoptional", + innerType: value + })); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); +} +function aborted(x, startIndex = 0) { + if (x.aborted === true) return true; + for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true; + return false; +} +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) return true; + for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true; + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst); +} +function finalizeIssue(iss, ctx, config) { + var _a; + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) (_a = iss).schema ?? (_a.schema = iss.inst); + else iss.schema = iss.inst; + } + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; + const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message; + if (ctx?.reportInput) full.input = iss.input; + return full; +} +const highSurrogate = /[\uD800-\uDBFF]/; +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) return units; + let count = units; + for (let i = 0; i < units - 1; i++) if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { + count--; + i++; + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) return "array"; + if (typeof input === "string") return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": return Number.isNaN(data) ? "nan" : "number"; + case "object": { + if (data === null) return "null"; + if (Array.isArray(data)) return "array"; + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) return obj.constructor.name; + } + } + return t; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") return { + message: iss, + code: "custom", + input, + inst + }; + return { ...iss }; +} +/** +* Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. +* +* Call this from a `proto` initializer, which runs once per prototype — never per instance. +*/ +function members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + if (desc.get) Object.defineProperty(proto, key, { + ...desc, + enumerable: false + }); + else defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { + configurable: true, + writable: true, + enumerable, + value + }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return own(inst, key, value, false); +} +/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */ +function derived(computes, table) { + for (const key in computes) { + const compute = computes[key]; + Object.defineProperty(table, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + } + }); + } + return table; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + } + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + return sentinel in proto ? void 0 : proto; +} +let installing; +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + } +}; +/** +* Installs a lazily-derived internal on the `_zod` prototype of `inst`'s +* constructor, computed from the internals object itself and cached there on +* first read. One accessor per constructor rather than one per instance. +*/ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + installing = void 0; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + if (broke) delete this[key]; + else Object.defineProperty(this, key, { + configurable: true, + writable: true, + value + }); + broke = broke || outer; + return value; + } catch (err) { + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { + configurable: true, + writable: true, + value + }); + } + }); +} +/** +* Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own +* data property. One accessor per constructor rather than one per instance, because an own accessor +* puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. +*/ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + const desc = { + configurable: true, + writable: true, + enumerable, + value: void 0 + }; + Object.defineProperty(this, key, desc); + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { + configurable: true, + writable: true, + enumerable, + value + }); + } + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/core.js +var _a$2; +const _zodDesc = { + value: void 0, + enumerable: false +}; +let _E = "captureStackTrace" in Error ? Error : null; +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, proto, params) { + const zodProto = {}; + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = /* @__PURE__ */ new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } finally { + _zodDesc.value = void 0; + } + } else if (inst._zod.traits.has(name)) return; + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + members(target, protoMembers); + } + } + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) continue; + if (!(k in inst)) inst[k] = proto[k].bind(inst); + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent {} + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) fn(); + inst._zod.deferred = void 0; + } + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) return true; + return inst?._zod?.traits?.has(name); + } }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a$2 = globalThis).__zod_globalConfig ?? (_a$2.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) Object.assign(globalConfig, newConfig); + return globalConfig; +} + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/errors.js +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true +}; +const _issuesDesc = { + value: void 0, + enumerable: false +}; +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const initializer$1 = (inst, def) => { + inst.name = "$ZodError"; + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + _issuesDesc.value = void 0; + Object.defineProperty(inst, "message", _messageDesc); + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { + value, + configurable: true, + writable: true + }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { + value, + configurable: true, + writable: true + }); + } + }); + } +}; +const $ZodError = $constructor("$ZodError", initializer$1); +const $ZodRealError = $constructor("$ZodError", initializer$1, void 0, { Parent: Error }); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member +* ("toString", "constructor") would otherwise read through to the prototype, and assigning +* "__proto__" would hit the setter instead of creating a key. */ +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") Object.defineProperty(obj, key, { + value: make(), + writable: true, + enumerable: true, + configurable: true + }); + else obj[key] = make(); + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) if (sub.path.length > 0) node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + else formErrors.push(mapper(sub)); + return { + formErrors, + fieldErrors + }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + else if (issue.code === "invalid_key") processError({ issues: issue.issues }, [...path, ...issue.path]); + else if (issue.code === "invalid_element") processError({ issues: issue.issues }, [...path, ...issue.path]); + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue)); + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (el === "_errors") { + if (terminal) curr._errors.push(mapper(issue)); + i++; + continue; + } + if (!Object.prototype.hasOwnProperty.call(curr, el)) Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true + }); + const node = curr[el]; + if (terminal) node._errors.push(mapper(issue)); + curr = node; + i++; + } + } + } + }; + processError(error); + return fieldErrors; +} + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/parse.js +function finalizeParams(callee, params) { + return { + callee: params?.callee ?? callee, + Err: params?.Err + }; +} +const _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { + ..._ctx, + async: false + } : { async: false }; + const result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) throw new $ZodAsyncError(); + if (result.issues.length) { + const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { + ..._ctx, + async: true + } : { async: true }; + let result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) result = await result; + if (result.issues.length) { + const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + async: false + } : { async: false }; + const result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) throw new $ZodAsyncError(); + return result.issues.length ? failure(_Err, result.issues, ctx) : { + success: true, + data: result.value + }; +}; +function failure(Err, issues, ctx) { + let error; + return { + success: false, + get error() { + if (!error) { + error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); + issues = void 0; + ctx = void 0; + } + return error; + }, + set error(e) { + error = e; + issues = void 0; + ctx = void 0; + } + }; +} +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + async: true + } : { async: true }; + let result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) result = await result; + return result.issues.length ? failure(_Err, result.issues, ctx) : { + success: true, + data: result.value + }; +}; +const COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +const COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +const validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== void 0) { + if (validator(value) !== COMPILE_INVALID) return true; + if (validator.definite === true && _ctx === void 0) return false; + } + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { + ..._ctx, + async: false, + abortEarly: true + } : { + async: false, + abortEarly: true + }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ + value, + issues: [] + }, ctx); + } else result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) throw new $ZodAsyncError(); + return result.issues.length === 0; +} +const validateAsync$1 = async (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + async: true, + abortEarly: true + } : { + async: true, + abortEarly: true + }; + let result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) result = await result; + return result.issues.length === 0; +}; +const _encode = (_Err) => { + const parse = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const _decode = (_Err) => { + const parse = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const _encodeAsync = (_Err) => { + const parseAsync = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return await parseAsync(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const _decodeAsync = (_Err) => { + const parseAsync = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/regexes.js +/** +* @deprecated CUID v1 is deprecated by its authors due to information leakage +* (timestamps embedded in the id). Use {@link cuid2} instead. +* See https://github.com/paralleldrive/cuid. +*/ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. +* +* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +/** Practical email validation */ +const email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +const _emoji$1 = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji$1, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; +const httpProtocol = /^https?$/; +const e164 = /^\+[1-9]\d{6,14}$/; +const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because +* esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it +* will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function anchor(source) { + return new RegExp(`^${source}$`); +} +const date = /*@__PURE__*/ anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const opts = ["Z"]; + if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const qualified = `${timeSource({ + precision: args.precision, + seconds: true + })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const anyString = /^[\s\S]{0,}$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const boolean$1 = /^(?:true|false)$/i; +const lowercase = /^[^A-Z]*$/; +const uppercase = /^[^a-z]*$/; + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/checks.js +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; +}; +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + if ((typeof input === "string" && units > def.maximum ? codePointLength(input) : units) <= def.maximum) return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + if ((typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units) >= def.minimum) return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units; + if (length === def.length) return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { + code: "too_big", + maximum: def.length + } : { + code: "too_small", + minimum: def.length + }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); + }); + else (_b = inst._zod).check ?? (_b.check = () => {}); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + def.pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/doc.js +var Doc = class { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + indented(fn) { + this.indent += 1; + try { + fn(this); + } finally { + this.indent -= 1; + } + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const lines = arg.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) this.content.push(line); + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + return new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`)(...Object.values(this.closed)); + } +}; + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/versions.js +const version = { + major: 4, + minor: 6, + patch: 5 +}; + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/schemas.js +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const defChecks = inst._zod.def.checks; + const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; + for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst); + if (checks.length === 0) { + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) return payload; + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) continue; + if (!ch._zod.def.when(payload)) continue; + } else if (isAborted) continue; + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError(); + if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + if (payload.issues.length === currLen) return; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) isAborted = aborted(payload, currLen); + }); + else { + if (payload.issues.length === currLen) continue; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) isAborted = aborted(payload, currLen); + } + } + if (asyncResult) return asyncResult.then(() => { + return payload; + }); + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) return inst._zod.parse(payload, ctx); + if (ctx.direction === "backward") { + const canary = inst._zod.parse({ + value: payload.value, + issues: [] + }, { + ...ctx, + skipChecks: true + }); + if (canary instanceof Promise) return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + return handleCanaryResult(canary, payload, ctx); + } + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + own(this, "~standard", value); + } +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +const toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; +async function validateAsync(inst, value) { + const ctx = { async: true }; + return toStandardResult(await inst._zod.run({ + value, + issues: [] + }, ctx), ctx); +} +function standardProps(inst) { + return { + validate: (value) => { + const ctx = { async: false }; + try { + const r = inst._zod.run({ + value, + issues: [] + }, ctx); + if (!(r instanceof Promise)) return toStandardResult(r, ctx); + } catch (_) {} + return validateAsync(inst, value); + }, + vendor: "zod", + version: 1 + }; +} +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = def.pattern ?? anyString; + inst._zod.parse = (payload, _) => { + if (def.coerce) try { + payload.value = String(payload.value); + } catch (_) {} + if (typeof payload.value === "string") return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const v = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }[def.version]; + if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL parser rejected the input. */ +const URL_UNPARSEABLE = 2; +function canParseURL(input) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") return URL.canParse(input); + new URL(input); + return true; + } catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) return canParseURL(trimmed) || 2; + return parseURLObject(trimmed, def); +} +/** Parses a URL while preserving the non-normalizing HTTP guard. */ +function parseURLObject(trimmed, def) { + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) return 1; + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") return URLStatic.parse(trimmed) ?? 2; + } + return new URL(trimmed); + } catch { + return 2; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const trimmed = payload.value.trim(); + const url = validateURL(trimmed, def); + if (url === 1) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; + } + if (url === 2) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + return; + } + if (url === true) { + payload.value = stripTabAndNewline(trimmed); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + if (def.protocol && !urlProtocolOk(url, def.protocol)) payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** +* @deprecated CUID v1 is deprecated by its authors due to information leakage +* (timestamps embedded in the id). Use {@link $ZodCUID2} instead. +* See https://github.com/paralleldrive/cuid. +*/ +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) return false; + return canParseURL(`http://[${value}]`); +} +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) return false; + const [address, prefix] = parts; + if (!prefix) return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) return false; + if (prefixNum < 0 || prefixNum > 128) return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isValidBase64(data) { + if (data === "") return true; + if (/\s/.test(data)) return false; + if (data.length % 4 !== 0) return false; + try { + atob(data); + return true; + } catch { + return false; + } +} +const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64Charset); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const base64urlCharset = /^[A-Za-z0-9_-]*$/; +function isValidBase64URL(data) { + if (!base64urlCharset.test(data)) return false; + const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64urlCharset); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) return false; + const [header] = tokensParts; + if (!header) return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; + if (!parsedHeader.alg) return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; + return true; + } catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean$1; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) try { + payload.value = Boolean(payload.value); + } catch (_) {} + const input = payload.value; + if (typeof input === "boolean") return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +function handleArrayResult(result, final, index) { + if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i))); + else { + handleArrayResult(result, payload, i); + if (abortEarly && result.issues.length !== 0 && aborted(result)) break; + } + } + if (proms.length) return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + if (!isPresent && isOptionalOut && optin === "optional") return; + if (result.issues.length) { + if (optin !== void 0 && isOptionalOut && !isPresent) return; + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && optin === void 0) { + if (!result.issues.length) final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: void 0, + path: [key] + }); + return; + } + if (result.value === void 0) { + if (isPresent || optin === "defaulted" && !isOptionalOut) final.value[key] = void 0; + } else final.value[key] = result.value; +} +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + const okeys = optionalKeys(def.shape); + return { + ...def, + allKeys, + symbolKeys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + let seen = 0; + for (const key in input) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) break; + seen = payload.issues.length; + } + if (keySet.has(key)) continue; + if (key === "__proto__") { + if (t === "never") unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ + value: input[key], + issues: [] + }, ctx); + if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + else handlePropertyResult(r, payload, key, input, optin, optout); + } + if (unrecognized.length) payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + continue: true + }); + if (!proms.length) return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + const sh = desc?.get ? desc.get.raw : def.shape ?? {}; + if (sh) { + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); + } + const _normalized = cached(() => normalizeDef(def)); + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) assignProp(propValues, key, /* @__PURE__ */ new Set()); + for (const v of field.values) propValues[key].add(v); + if (field.optin !== void 0) propValues[key].add(void 0); + } + } + return propValues; + }); + const isObject$2 = isObject; + const catchall = def.catchall; + let value; + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject$2(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (aborted(payload, seen)) break; + seen = payload.issues.length; + } + if (key === "__proto__") continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + else handlePropertyResult(r, payload, key, input, optin, optout); + } + if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload; + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def)); + const memo = globalConfig.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + const doc = new Doc(["payload", "ctx"], { + shape, + inst, + memo, + syms + }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) ids[key] = `key_${counter++}`; + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== void 0; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } else if (!isOptionalIn) doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + `); + if (optin === "defaulted") doc.write(`newResult[${k}] = ${id}.value;`); + else doc.write(` + if (${id}.value !== undefined || ${isPresent}) { + newResult[${k}] = ${id}.value; + } + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + return doc.compile(); + }; + let fastpass; + const isObject$1 = isObject; + const jit = !globalConfig.jitless; + const allowsEval$1 = allowsEval; + const fastEnabled = jit && allowsEval$1.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject$1(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) return payload; + return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) if (result.issues.length === 0) { + final.value = result.value; + return final; + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + }); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) return first(payload, ctx); + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) return result; + results.push(result); + } + } + if (!async) return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ + value: input, + issues: [] + }, ctx); + const right = def.right._zod.run({ + value: input, + issues: [] + }, ctx); + if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + return handleIntersectionResults(payload, left, right); + }; +}); +function mergeValues(a, b) { + if (a === b) return { + valid: true, + data: a + }; + if (a instanceof Date && b instanceof Date && +a === +b) return { + valid: true, + data: a + }; + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { + ...a, + ...b + }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") continue; + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + newObj[key] = sharedValue.data; + } + return { + valid: true, + data: newObj + }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) return { + valid: false, + mergeErrorPath: [] + }; + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath] + }; + newArray.push(sharedValue.data); + } + return { + valid: true, + data: newArray + }; + } + return { + valid: false, + mergeErrorPath: [] + }; +} +function handleIntersectionResults(result, left, right) { + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + const keyIssues = /* @__PURE__ */ new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) keyIssues.set(k, iss); + keys = [k]; + } else return false; + for (const k of keys) { + if (!unrecKeys.has(k)) unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) if (!collect(iss, "l")) result.issues.push(iss); + for (const iss of right.issues) if (!collect(iss, "r")) result.issues.push(iss); + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) result.issues.push({ + ...unrecIssue, + keys: aggregated + }); + for (const k of bothKeys) if (!aggregated.includes(k) && keyIssues.has(k)) result.issues.push(keyIssues.get(k)); + } + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + if (aborted(result)) return result; + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = /* @__PURE__ */ new Set(); + for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + if (key === "__proto__") continue; + const keyResult = def.keyType._zod.run({ + value: key, + issues: [] + }, ctx); + if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") continue; + const result = def.valueType._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result) => { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[outKey] = result.value; + })); + else { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[outKey] = result.value; + } + } + let unrecognized; + for (const key in input) if (!recordKeys.has(key)) { + if (def.mode === "loose") { + if (key === "__proto__") continue; + payload.value[key] = input[key]; + } else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true + }); + } else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + let unrecognized; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue; + let keyResult = def.keyType._zod.run({ + value: key, + issues: [] + }, ctx); + if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + if (typeof key === "string" && number.test(key) && keyResult.issues.length) { + const retryResult = def.keyType._zod.run({ + value: Number(key), + issues: [] + }, ctx); + if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + if (retryResult.issues.length === 0) keyResult = retryResult; + } + if (keyResult.issues.length) { + if (def.mode === "loose") payload.value[key] = input[key]; + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } else payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") continue; + const result = def.valueType._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result) => { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[outKey] = result.value; + })); + else { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true + }); + } + if (proms.length) return Promise.all(proms).then(() => payload); + return payload; + }; +}); +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + defineLazyInternal(inst, "pattern", (zod) => { + const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) return payload; + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; +}); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); + const _out = def.transform(payload.value, payload); + if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => { + payload.value = output; + return payload; + }); + if (_out instanceof Promise) throw new $ZodAsyncError(); + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + payload.value = result.issues.length ? void 0 : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + defineLazyInternal(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? /* @__PURE__ */ new Set([...values, void 0]) : void 0; + }); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === void 0) { + if (def.innerType._zod.optin !== "defaulted") return payload; + const result = def.innerType._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + $ZodOptional.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + if (payload.value === void 0) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def)); + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === void 0) payload.value = def.defaultValue; + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + if (payload.value === void 0) payload.value = def.defaultValue; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst)); + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + return payload; +} +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + if (result.memo) payload.memo = true; + return payload; + } + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, + input: payload.value + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) return result.then((result) => handleCatchResult(payload, result, def, ctx)); + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx)); + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx)); + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + left.aborted = true; + return left; + } + return next._zod.run({ + value: left.value, + issues: left.issues + }, ctx); +} +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then(handleReadonlyResult); + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + if (!payload.memo) payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst)); + handleRefineResult(r, payload, input, inst); + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + path: [...inst._zod.def.path ?? []], + continue: !inst._zod.def.abort + }; + if (inst._zod.def.params) _iss.params = inst._zod.def.params; + payload.issues.push(issue(_iss)); + } +} + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/memoizer.js +var $ZodCyclicError = class extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +}; +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +function isRef(value) { + return value !== null && typeof value === "object"; +} +function cloneIssues(issues) { + return issues.map((iss) => iss.path ? { + ...iss, + path: iss.path.slice() + } : { ...iss }); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */ +const NONE = 0; +const ASSUMED = 1; +const PROVEN = 2; +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack, resolve) { + const cached = recursive.get(inst); + if (cached !== void 0) return cached ? PROVEN : NONE; + if (stack.has(inst)) return PROVEN; + stack.add(inst); + let result = NONE; + const check = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) result = answer; + } + }; + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc = Object.getOwnPropertyDescriptor(sh, key); + if (spread && !desc.enumerable) continue; + const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE; + if (child > answer) answer = child; + } + return answer; + }; + const merge = (answer) => { + if (answer > result) result = answer; + }; + const def = inst._zod.def; + switch (def.type) { + case "object": { + const raw = rawShape(def); + merge(raw ? shape(raw, true) : ASSUMED); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0); + merge(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + case "template_literal": + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": break; + default: for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) continue; + const value = desc.value; + if (!value || typeof value !== "object") continue; + if (value._zod) check(value); + else if (Array.isArray(value)) for (const el of value) check(el); + } + } + stack.delete(inst); + return settle(inst, result); +} +/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */ +function settle(inst, answer) { + if (answer !== ASSUMED) recursive.set(inst, answer === PROVEN); + return answer; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = /* @__PURE__ */ new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +let handoff; +const open = []; +const memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) return empty; + handoff = void 0; + const entry = { + value: empty, + issues: null + }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + let rechecked = false; + let lastCtx; + let lastBucket; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === void 0) { + const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false); + if (walked === NONE) { + inst._zod.parse = base; + if (inst._zod.run === wrapped) inst._zod.run = base; + return base(payload, ctx); + } + if (walked === PROVEN || rechecked) isRecursiveInst = true; + else rechecked = true; + } + const input = payload.value; + if (!isRef(input)) return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { + buckets: /* @__PURE__ */ new WeakMap(), + backEdges: void 0 + }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) bucket = lastBucket; + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) payload.issues.push(...cloneIssues(hit.issues)); + } else { + payload.memo = true; + state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = void 0; + const entry = open.length > depth ? open.pop() : void 0; + if (result instanceof Promise) return result.then((r) => { + if (entry) entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + if (entry) entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) inst._zod.run = wrapped; + }); + } +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== void 0 && isRef(value) && backEdges.has(value); +} + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/locales/en.js +const error = () => { + const Sizable = { + string: { + unit: "characters", + verb: "to have" + }, + file: { + unit: "bytes", + verb: "to have" + }, + array: { + unit: "items", + verb: "to have" + }, + set: { + unit: "items", + verb: "to have" + }, + map: { + unit: "entries", + verb: "to have" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { nan: "NaN" }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) return String(input); + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": return `Invalid input: expected ${getTypeName(issue.expected)}, received ${getTypeName(parsedType(issue.input), issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") return `Invalid string: must start with "${_issue.prefix}"`; + if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) return `Invalid discriminator value. Expected ${issue.options.map((o) => `'${o}'`).join(" | ")}`; + if (issue.inclusive === false) return "Invalid input: more than one option matched"; + return "Invalid input"; + case "invalid_element": return `Invalid value in ${issue.origin}`; + default: return `Invalid input`; + } + }; +}; +function en_default() { + return { localeError: error() }; +} + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/registries.js +var _a$1; +var $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema); + return this; + } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id); + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + const f = { + ...pm, + ...this._map.get(schema) + }; + return Object.keys(f).length ? f : void 0; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +}; +function registry() { + return new $ZodRegistry(); +} +(_a$1 = globalThis).__zod_globalRegistry ?? (_a$1.__zod_globalRegistry = registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/api.js +function snapshotChecks(def) { + if (def.checks) def.checks = [...def.checks]; + return def; +} +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class(snapshotChecks({ + type: "string", + ...normalizeParams(params) + })); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +/** +* @deprecated CUID v1 is deprecated by its authors due to information leakage +* (timestamps embedded in the id). Use {@link _cuid2} instead. +* See https://github.com/paralleldrive/cuid. +*/ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ type: "unknown" }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + return new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); +} +// @__NO_SIDE_EFFECTS__ +function _trim() { + return /* @__PURE__ */ _overwrite((input) => input.trim()); +} +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +} +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +} +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + return new Class({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = /* @__PURE__ */ _check((payload) => { + payload.addIssue = (issue$2) => { + if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def)); + else { + const _issue = issue$2; + if (_issue.fatal) _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) + }); + ch._zod.check = fn; + return ch; +} + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/to-json-schema.js +function assignProps(target, ...sources) { + for (const source of sources) for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProp(target, key, source[key]); + return target; +} +function initializeContext(params) { + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") target = "draft-04"; + if (target === "draft-7") target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => {}), + io: params?.io ?? "output", + counter: 0, + seen: /* @__PURE__ */ new Map(), + sharedDefsExtractedFor: void 0, + sharedEmitDoneFor: void 0, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? void 0 + }; +} +/** +* Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws +* `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a +* custom JSON Schema was written into `json`, in which case the caller must not write its own. +*/ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ + zodSchema: schema, + path: params.path, + message + }) : ctx.unrepresentable; + if (result === "any") return false; + if (result === void 0 || result === "throw") throw new Error(message); + Object.assign(json, result); + return true; +} +function processSchema(schema, ctx, _params = { + path: [], + schemaPath: [] +}) { + var _a; + const def = schema._zod.def; + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + if (_params.schemaPath.includes(schema)) seen.cycle = _params.path; + return seen.schema; + } + const result = { + schema: {}, + count: 1, + cycle: void 0, + path: _params.path + }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = void 0; + ctx.sharedEmitDoneFor = void 0; + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) result.schema = overrideSchema; + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params); + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + if (!result.ref) result.ref = parent; + processSchema(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta = ctx.metadataRegistry.get(schema); + if (meta) assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && "_prefault" in result.schema) (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + return ctx.seen.get(schema).schema; +} +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) return; + const idToSchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + idToSchema.set(id, entry[0]); + } + } + const makeURI = (entry) => { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) return { ref: uriGenerator(externalId) }; + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; + return { + defId: id, + ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` + }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + if (entry[1] === root && !entry[1].schema.id) return { ref: uriPrefix }; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { + defId, + ref: defUriPrefix + encodeJSONPointerSegment(defId) + }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) return; + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) seen.defId = defId; + const schema = seen.schema; + for (const key in schema) delete schema[key]; + schema.$ref = ref; + }; + if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + if (ctx.metadataRegistry.get(entry[0])?.id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") extractToDef(entry); + } + } + if (ctx.external) ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") return; + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") return; + if (!types.includes(member)) types.push(member); + } + } + delete schema.anyOf; + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, +* an annotation like `description` — makes a member unfoldable, so a constraint this does not +* understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = /* @__PURE__ */ new Set([ + "type", + "properties", + "required", + "additionalProperties" +]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + if (typeof member !== "object" || member.type !== "object") return null; + for (const key in member) if (!FOLDABLE_KEYS.has(key)) return null; + objects.push(member); + } + const properties = {}; + const required = /* @__PURE__ */ new Set(); + for (const object of objects) { + for (const key in object.properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) continue; + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === void 0) continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) parts.push(part); + } + const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts }; + assignProp(properties, key, merged); + } + for (const key of object.required ?? []) required.add(key); + } + const folded = { + type: "object", + properties + }; + if (required.size) folded.required = [...required]; + if (objects.every((object) => object.additionalProperties === false)) folded.additionalProperties = false; + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) constraints.push(constraint); + } + if (constraints.length === 1) folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two +* closed object members reject each other's keys and the schema validates nothing. Zod's parser +* pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when +* *every* side rejects it — so the emitted schema has to pool them too, and folding the members +* into one object is the encoding that says so on every target. +* +* This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` +* machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it +* keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) return; + for (const key of FOLDABLE_KEYS) if (key in json) return; + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) folded = foldObjects(allOf); + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) return; + folded = { [keyword]: branches }; + } + if (!folded) return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } else assignProps(schema, refSchema); + assignProps(schema, _cached); + if (zodSchema._zod.parent === ref) for (const key in schema) { + if (key === "$ref" || key === "allOf") continue; + if (!(key in _cached)) delete schema[key]; + } + if (refSchema.$ref && refSeen.def) for (const key in schema) { + if (key === "$ref" || key === "allOf") continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key]; + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + if (parentSeen.def) for (const key in schema) { + if (key === "$ref" || key === "allOf") continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key]; + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema, + path: seen.path ?? [] + }); + }; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]); + if (ctx.target !== "openapi-3.0") for (const entry of ctx.seen.entries()) compactTypeUnion(entry[1].def ?? entry[1].schema); + for (const rewrite of ctx.deferred) rewrite(); + if (ctx.intersections.length) { + const carriers = /* @__PURE__ */ new Map(); + for (const seen of ctx.seen.values()) for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) continue; + const existing = carriers.get(allOf); + if (existing) existing.push(json); + else carriers.set(allOf, [json]); + } + for (const allOf of ctx.intersections) for (const json of carriers.get(allOf) ?? []) foldIntersection(json); + } + } + const result = {}; + if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema"; + else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#"; + else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#"; + else if (ctx.target === "openapi-3.0") {} + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + assignProps(result, root.defId ? root.schema : root.def ?? root.schema); + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } + } + if (ctx.external) ctx.sharedEmitDoneFor = ctx.external; + if (ctx.external) {} else if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") result.$defs = defs; + else result.definitions = defs; + } + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") return true; + if (def.type === "array") return isTransforming(def.element, ctx); + if (def.type === "set") return isTransforming(def.valueType, ctx); + if (def.type === "lazy") return isTransforming(def.getter(), ctx); + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") return isTransforming(def.innerType, ctx); + if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true; + return false; + } + if (def.type === "union") { + for (const option of def.options) if (isTransforming(option, ctx)) return true; + return false; + } + if (def.type === "tuple") { + for (const item of def.items) if (isTransforming(item, ctx)) return true; + if (def.rest && isTransforming(def.rest, ctx)) return true; + return false; + } + return false; +} +/** +* Creates a toJSONSchema method for a schema instance. +* This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. +*/ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ + ...params, + processors + }); + processSchema(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ + ...libraryOptions ?? {}, + target, + io, + processors + }); + processSchema(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/json-schema-processors.js +const narrowMin = (agg, key, value) => { + if (agg[key] === void 0 || value > agg[key]) agg[key] = value; +}; +const narrowMax = (agg, key, value) => { + if (agg[key] === void 0 || value < agg[key]) agg[key] = value; +}; +const narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +const addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) agg.multipleOf.push(value); +}; +const addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set()); + agg.patterns.add(pattern); +}; +const intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +const setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) agg.isInt = true; +}; +const minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +const maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +const formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +const contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(NUMBER_FORMAT_RANGES), + bigint_format: formatContributor(BIGINT_FORMAT_RANGES), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") agg.contentEncoding = def.format; + if (def.local || def.precision === -1) agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime) +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? []; + for (const ch of list) contributors[ch._zod.def.check]?.(agg, ch._zod.def); + const bag = schema._zod.bag; + if (bag.minimum !== void 0) narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== void 0) narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== void 0) narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== void 0) narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== void 0) addDivisor(agg, bag.multipleOf); + if (bag.format !== void 0) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) agg.isInt = true; + } + if (bag.mime) intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) addPattern(agg, pattern); + return agg; +} +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" +}; +const exactPatterns = /* @__PURE__ */ new Map([[base64Charset, base64], [base64urlCharset, base64url]]); +const exactPattern = (p) => exactPatterns.get(p) ?? p; +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); + if (typeof minimum === "number") json.minLength = minimum; + if (typeof maximum === "number") json.maxLength = maximum; + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") delete json.format; + if (format === "time" || laxFormat) delete json.format; + } + if (contentEncoding) json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) json.pattern = patternList[0].source; + else if (patternList.length > 1) json.allOf = [...patternList.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + }))]; + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => {}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + if (values.length === 0) { + json.not = {}; + return; + } + if (values.every((v) => typeof v === "number")) json.type = "number"; + if (values.every((v) => typeof v === "string")) json.type = "string"; + json.enum = values; +}; +const customProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = aggregateChecks(schema); + if (typeof minimum === "number") json.minItems = minimum; + if (typeof maximum === "number") json.maxItems = maximum; + json.type = "array"; + json.items = processSchema(def.element, ctx, { + ...params, + path: [...params.path, "items"] + }); +}; +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) return inputOptin(def.out); + if (def.type === "catch") return inputOptin(def.innerType); + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + if (Object.getOwnPropertySymbols(shape).length && handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) return; + json.type = "object"; + json.properties = {}; + for (const key in shape) assignProp(json.properties, key, processSchema(shape[key], ctx, { + ...params, + path: [ + ...params.path, + "properties", + key + ] + })); + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) requiredKeys.push(key); + } + if (requiredKeys.length > 0) json.required = requiredKeys; + if (def.catchall?._zod.def.type === "never") json.additionalProperties = false; + else if (!def.catchall) { + if (ctx.io === "output") json.additionalProperties = false; + } else if (def.catchall) json.additionalProperties = processSchema(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => processSchema(x, ctx, { + ...params, + path: [ + ...params.path, + isExclusive ? "oneOf" : "anyOf", + i + ] + })); + if (isExclusive) json.oneOf = options; + else json.anyOf = options; +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = processSchema(def.left, ctx, { + ...params, + path: [ + ...params.path, + "allOf", + 0 + ] + }); + const b = processSchema(def.right, ctx, { + ...params, + path: [ + ...params.path, + "allOf", + 1 + ] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]]; + json.allOf = allOf; + ctx.intersections.push(allOf); +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the +* numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key +* behind a wrapper only carries its own `type` before then, and a union key only has its branches. +* +* A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather +* than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this +* exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` +* accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema +* outright. */ +function stringifyKeyNames(bySchema, json, visited) { + if (json.$ref) { + if (visited.has(json)) return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + if (mapped.some((branch, i) => branch !== branches[i])) json = { + ...json, + [keyword]: mapped + }; + } + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + const values = json.enum ?? (json.const !== void 0 ? [json.const] : void 0); + if (!numericType && !values?.some((v) => typeof v === "number")) return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v); + else if (typeof rest.const === "number") rest.const = String(rest.const); + if (!numericType) return rest; + rest.type = "string"; + if (!values) rest.pattern = (types.includes("number") ? number : integer).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = /* @__PURE__ */ new WeakMap(); +function rewriteKeyNames(ctx) { + const bySchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.values()) if (entry.def && !bySchema.has(entry.schema)) bySchema.set(entry.schema, entry); + const rewrites = /* @__PURE__ */ new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) continue; + const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set()); + if (rewritten !== names) rewrites.set(names, rewritten); + } + if (!rewrites.size) return; + for (const entry of ctx.seen.values()) for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) carrier.propertyNames = rewritten; + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + const keyType = def.keyType; + const patterns = aggregateChecks(keyType).patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = processSchema(def.valueType, ctx, { + ...params, + path: [ + ...params.path, + "patternProperties", + "*" + ] + }); + json.patternProperties = {}; + for (const pattern of patterns) assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema); + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = processSchema(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = processSchema(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + const keyValues = keyType._zod.values; + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) json.required = validKeyValues.map(String); + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } else json.anyOf = [inner, { type: "null" }]; +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. +* A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other +* unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; + processSchema(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/errors.js +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { + value, + configurable: true, + writable: true + }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { + value, + configurable: true, + writable: true + }); + } + }); +} +const initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + } + }); +}; +const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, void 0, { Parent: Error }); + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/parse.js +const parse = /* @__PURE__ */ _parse(ZodRealError); +const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); +const safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); +const encode = /* @__PURE__ */ _encode(ZodRealError); +const decode = /* @__PURE__ */ _decode(ZodRealError); +const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); +const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); +const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + +//#endregion +//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/schemas.js +function _ensureDefaultLocale() { + if (!globalConfig.localeError) config(en_default()); +} +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) config({ memoizer: memoizer() }); +} +const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: { + check: ch, + def: { check: "custom" }, + onattach: [] + } } : ch)] }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + get "~standard"() { + return hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output") + } + }); + }, + set "~standard"(value) { + own(this, "~standard", value); + }, + parse: function _parse(data, params) { + return parse(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await parseAsync(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return safeParse(this, data, params); + }, + async safeParseAsync(data, params) { + return safeParseAsync(this, data, params); + }, + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + own(this, "spa", value); + }, + validate(data, params) { + return validate(this, data, params); + }, + validateAsync(data, params) { + return validateAsync$1(this, data, params); + }, + encode: function _encode(data, params) { + return encode(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return decode(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await encodeAsync(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await decodeAsync(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return safeEncode(this, data, params); + }, + safeDecode(data, params) { + return safeDecode(this, data, params); + }, + async safeEncodeAsync(data, params) { + return safeEncodeAsync(this, data, params); + }, + async safeDecodeAsync(data, params) { + return safeDecodeAsync(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + get description() { + return globalRegistry.get(this)?.description; + }, + get _def() { + return this._zod.def; + } +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); +}, /*@__PURE__*/ derived({ + format: (inst) => aggregateChecks(inst).format ?? null, + minLength: (inst) => aggregateChecks(inst).minimum ?? null, + maxLength: (inst) => aggregateChecks(inst).maximum ?? null +}, { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + } +})); +const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(_emoji(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(ZodISODuration, params)); + } +}); +function string(params) { + return _string(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** +* @deprecated CUID v1 is deprecated by its authors due to information leakage +* (timestamps embedded in the id). Use {@link ZodCUID2} instead. +* See https://github.com/paralleldrive/cuid. +*/ +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function boolean(params) { + return _boolean(ZodBoolean, params); +} +const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return _never(ZodNever, params); +} +const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } +}); +function array(element, params) { + return _array(ZodArray, element, params); +} +const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return _enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone(mergeDefs(this._zod.def, { catchall })); + }, + passthrough() { + return this.clone(mergeDefs(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(mergeDefs(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(mergeDefs(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(mergeDefs(this._zod.def, { catchall: void 0 })); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return required(ZodNonOptional, this, args[0]); + } +}); +function object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params) + }; + return new ZodObject(def); +} +const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function union(options, params) { + return new ZodUnion({ + type: "union", + options, + ...normalizeParams(params) + }); +} +const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left, + right + }); +} +const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function record(keyType, valueType, params) { + if (!valueType || !valueType._zod) return new ZodRecord({ + type: "record", + keyType: string(), + valueType: keyType, + ...normalizeParams(valueType) + }); + return new ZodRecord({ + type: "record", + keyType, + valueType, + ...normalizeParams(params) + }); +} +const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = [...inst._zod.values]; + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value]; + else throw new Error(`Key ${value} not found in enum`); + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) if (keys.has(value)) delete newEntries[value]; + else throw new Error(`Key ${value} not found in enum`); + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries + }); + }; +}); +function _enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); + payload.addIssue = (issue$1) => { + if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def)); + else { + const _issue = issue$1; + if (_issue.fatal) _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + payload.issues.push(issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) return output.then((output) => { + payload.value = output; + return payload; + }); + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType + }); +} +const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType + }); +} +const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType + }); +} +const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function _default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...normalizeParams(params) + }); +} +const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function _catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue) + }); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + }); +} +const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType + }); +} +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +function superRefine(fn, params) { + return _superRefine(fn, params); +} + +//#endregion +//#region src/config.ts +/** +* Resolved tracer configuration. +* +* Resolution order (lowest → highest precedence): +* defaults → ~/.codex/langfuse.json → /.codex/langfuse.json → env +* +* For each env var, the `LANGFUSE_CODEX_*` form takes precedence over the +* matching standard `LANGFUSE_*` form so you can scope credentials to Codex +* without disturbing other Langfuse tooling on the same machine. +*/ +const ConfigSchema = object({ + enabled: boolean(), + public_key: string().optional(), + secret_key: string().optional(), + base_url: string(), + environment: string().optional(), + user_id: string().optional(), + tags: array(string()).optional(), + metadata: record(string(), string()).optional(), + skill_tags: boolean(), + trace_seed: string().optional(), + debug: boolean(), + fail_on_error: boolean() +}); +const PartialConfigSchema = ConfigSchema.partial(); +const DEFAULTS = { + enabled: false, + base_url: "https://cloud.langfuse.com", + skill_tags: true, + debug: false, + fail_on_error: false +}; +const CodexAuthSchema = object({ tokens: object({ id_token: string().optional() }).optional() }).loose(); +function parseBoolean(value) { + if (typeof value === "boolean") return value; + if (typeof value !== "string") return void 0; + const normalized = value.trim().toLowerCase(); + if ([ + "1", + "true", + "yes", + "on" + ].includes(normalized)) return true; + if ([ + "0", + "false", + "no", + "off" + ].includes(normalized)) return false; +} +function parseTags(value) { + if (Array.isArray(value)) return value.map(String); + if (typeof value !== "string" || value.trim().length === 0) return void 0; + const trimmed = value.trim(); + if (trimmed.startsWith("[")) try { + const parsed = JSON.parse(trimmed); + if (Array.isArray(parsed)) return parsed.map(String); + } catch {} + return trimmed.split(",").map((t) => t.trim()).filter(Boolean); +} +function parseMetadata(value) { + let obj = value; + if (typeof value === "string") { + if (value.trim().length === 0) return void 0; + try { + obj = JSON.parse(value); + } catch { + return; + } + } + if (obj == null || typeof obj !== "object" || Array.isArray(obj)) return; + const out = {}; + for (const [k, v] of Object.entries(obj)) out[k] = typeof v === "string" ? v : JSON.stringify(v); + return out; +} +function stripUndefined(value) { + return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0)); +} +async function readConfigFile(file) { + try { + const raw = JSON.parse(await fs$1.readFile(file, "utf-8")); + return PartialConfigSchema.parse(stripUndefined({ + ...raw, + enabled: raw.enabled != null ? parseBoolean(raw.enabled) : void 0, + tags: raw.tags != null ? parseTags(raw.tags) : void 0, + metadata: raw.metadata != null ? parseMetadata(raw.metadata) : void 0, + skill_tags: raw.skill_tags != null ? parseBoolean(raw.skill_tags) : void 0, + debug: raw.debug != null ? parseBoolean(raw.debug) : void 0, + fail_on_error: raw.fail_on_error != null ? parseBoolean(raw.fail_on_error) : void 0 + })); + } catch { + return; + } +} +function readJwtPayload(token) { + const payload = token.split(".")[1]; + if (!payload) return void 0; + try { + const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8")); + if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return void 0; + return parsed; + } catch { + return; + } +} +async function readCodexUserEmail(authFile) { + try { + const raw = JSON.parse(await fs$1.readFile(authFile, "utf-8")); + const token = CodexAuthSchema.parse(raw).tokens?.id_token; + if (!token) return void 0; + const email = readJwtPayload(token)?.email; + if (typeof email !== "string") return void 0; + const trimmed = email.trim(); + return trimmed.length > 0 ? trimmed : void 0; + } catch { + return; + } +} +function getVar(suffix, env) { + return env[`LANGFUSE_CODEX_${suffix}`] ?? env[`LANGFUSE_${suffix}`]; +} +function readEnvConfig(env) { + return PartialConfigSchema.parse(stripUndefined({ + enabled: parseBoolean(env.TRACE_TO_LANGFUSE), + public_key: getVar("PUBLIC_KEY", env), + secret_key: getVar("SECRET_KEY", env), + base_url: getVar("BASE_URL", env), + environment: env.LANGFUSE_CODEX_ENVIRONMENT ?? env.LANGFUSE_TRACING_ENVIRONMENT, + user_id: env.LANGFUSE_CODEX_USER_ID, + tags: parseTags(env.LANGFUSE_CODEX_TAGS), + metadata: parseMetadata(env.LANGFUSE_CODEX_METADATA), + skill_tags: parseBoolean(env.LANGFUSE_CODEX_SKILL_TAGS), + trace_seed: env.LANGFUSE_CODEX_TRACE_SEED, + debug: parseBoolean(env.LANGFUSE_CODEX_DEBUG), + fail_on_error: parseBoolean(env.LANGFUSE_CODEX_FAIL_ON_ERROR) + })); +} +const getHomeDir = () => process.env.HOME ?? os$1.homedir(); +function getCodexAuthFile(home, env) { + const codexHome = env.CODEX_HOME?.trim(); + return codexHome ? path$1.join(codexHome, "auth.json") : path$1.join(home, ".codex", "auth.json"); +} +async function getConfig(options) { + const home = options?.home ?? getHomeDir(); + const cwd = options?.cwd ?? process.cwd(); + const env = options?.env ?? process.env; + const [globalConfig, localConfig] = await Promise.all([readConfigFile(path$1.join(home, ".codex", "langfuse.json")), readConfigFile(path$1.join(cwd, ".codex", "langfuse.json"))]); + const envConfig = readEnvConfig(env); + const codexUserId = globalConfig?.user_id ?? localConfig?.user_id ?? envConfig.user_id ? void 0 : await readCodexUserEmail(getCodexAuthFile(home, env)); + return ConfigSchema.parse({ + ...DEFAULTS, + ...codexUserId ? { user_id: codexUserId } : {}, + ...globalConfig, + ...localConfig, + ...envConfig + }); +} + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/version.js +var VERSION$1; +var init_version$1 = __esmMin((() => { + VERSION$1 = "1.9.1"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/semver.js +/** +* Create a function to test an API version to see if it is compatible with the provided ownVersion. +* +* The returned function has the following semantics: +* - Exact match is always compatible +* - Major versions must match exactly +* - 1.x package cannot use global 2.x package +* - 2.x package cannot use global 1.x package +* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API +* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects +* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 +* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor +* - Patch and build tag differences are not considered at this time +* +* @param ownVersion version which should be checked against +*/ +function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); + const rejectedVersions = /* @__PURE__ */ new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) return () => false; + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4] + }; + if (ownVersionParsed.prerelease != null) return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) return true; + if (rejectedVersions.has(globalVersion)) return false; + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) return _reject(globalVersion); + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4] + }; + if (globalVersionParsed.prerelease != null) return _reject(globalVersion); + if (ownVersionParsed.major !== globalVersionParsed.major) return _reject(globalVersion); + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) return _accept(globalVersion); + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) return _accept(globalVersion); + return _reject(globalVersion); + }; +} +var re, isCompatible; +var init_semver = __esmMin((() => { + init_version$1(); + re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + isCompatible = _makeCompatibilityCheck(VERSION$1); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js +function registerGlobal(type, instance, diag, allowOverride = false) { + var _a; + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: VERSION$1 }; + if (!allowOverride && api[type]) { + const err = /* @__PURE__ */ new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== "1.9.1") { + const err = /* @__PURE__ */ new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION$1}`); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION$1}.`); + return true; +} +function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !isCompatible(globalVersion)) return; + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; +} +function unregisterGlobal(type, diag) { + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION$1}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) delete api[type]; +} +var major, GLOBAL_OPENTELEMETRY_API_KEY, _global; +var init_global_utils = __esmMin((() => { + init_version$1(); + init_semver(); + major = VERSION$1.split(".")[0]; + GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); + _global = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {}; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js +function logProxy(funcName, namespace, args) { + const logger = getGlobal("diag"); + if (!logger) return; + return logger[funcName](namespace, ...args); +} +var DiagComponentLogger; +var init_ComponentLogger = __esmMin((() => { + init_global_utils(); + DiagComponentLogger = class { + constructor(props) { + this._namespace = props.namespace || "DiagComponentLogger"; + } + debug(...args) { + return logProxy("debug", this._namespace, args); + } + error(...args) { + return logProxy("error", this._namespace, args); + } + info(...args) { + return logProxy("info", this._namespace, args); + } + warn(...args) { + return logProxy("warn", this._namespace, args); + } + verbose(...args) { + return logProxy("verbose", this._namespace, args); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/types.js +var DiagLogLevel; +var init_types$1 = __esmMin((() => { + ; + (function(DiagLogLevel) { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + /** Identifies an error scenario */ + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + /** Identifies a warning scenario */ + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + /** General informational log message */ + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + /** General debug log message */ + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + /** Used to set the logging level to include all logging */ + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; + })(DiagLogLevel || (DiagLogLevel = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js +function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < DiagLogLevel.NONE) maxLevel = DiagLogLevel.NONE; + else if (maxLevel > DiagLogLevel.ALL) maxLevel = DiagLogLevel.ALL; + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === "function" && maxLevel >= theLevel) return theFunc.bind(logger); + return function() {}; + } + return { + error: _filterFunc("error", DiagLogLevel.ERROR), + warn: _filterFunc("warn", DiagLogLevel.WARN), + info: _filterFunc("info", DiagLogLevel.INFO), + debug: _filterFunc("debug", DiagLogLevel.DEBUG), + verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE) + }; +} +var init_logLevelLogger = __esmMin((() => { + init_types$1(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/diag.js +var API_NAME$4, DiagAPI; +var init_diag = __esmMin((() => { + init_ComponentLogger(); + init_logLevelLogger(); + init_types$1(); + init_global_utils(); + API_NAME$4 = "diag"; + DiagAPI = class DiagAPI { + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) this._instance = new DiagAPI(); + return this._instance; + } + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function(...args) { + const logger = getGlobal("diag"); + if (!logger) return; + return logger[funcName](...args); + }; + } + const self = this; + const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger === self) { + const err = /* @__PURE__ */ new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === "number") optionsOrLogLevel = { logLevel: optionsOrLogLevel }; + const oldLogger = getGlobal("diag"); + const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = (/* @__PURE__ */ new Error()).stack) !== null && _c !== void 0 ? _c : ""; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return registerGlobal("diag", newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = () => { + unregisterGlobal(API_NAME$4, self); + }; + self.createComponentLogger = (options) => { + return new DiagComponentLogger(options); + }; + self.verbose = _logProxy("verbose"); + self.debug = _logProxy("debug"); + self.info = _logProxy("info"); + self.warn = _logProxy("warn"); + self.error = _logProxy("error"); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js +var BaggageImpl; +var init_baggage_impl = __esmMin((() => { + BaggageImpl = class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) return; + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) newBaggage._entries.delete(key); + return newBaggage; + } + clear() { + return new BaggageImpl(); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js +var baggageEntryMetadataSymbol; +var init_symbol = __esmMin((() => { + baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata"); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/utils.js +/** +* Create a new Baggage with optional entries +* +* @param entries An array of baggage entries the new baggage should contain +*/ +function createBaggage(entries = {}) { + return new BaggageImpl(new Map(Object.entries(entries))); +} +/** +* Create a serializable BaggageEntryMetadata object from a string. +* +* @param str string metadata. Format is currently not defined by the spec and has no special meaning. +* +* @since 1.0.0 +*/ +function baggageEntryMetadataFromString(str) { + if (typeof str !== "string") { + diag$1.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ""; + } + return { + __TYPE__: baggageEntryMetadataSymbol, + toString() { + return str; + } + }; +} +var diag$1; +var init_utils$2 = __esmMin((() => { + init_diag(); + init_baggage_impl(); + init_symbol(); + diag$1 = DiagAPI.instance(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/context.js +/** +* Get a key to uniquely identify a context value +* +* @since 1.0.0 +*/ +function createContextKey(description) { + return Symbol.for(description); +} +var BaseContext, ROOT_CONTEXT; +var init_context$1 = __esmMin((() => { + BaseContext = class BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + const self = this; + self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); + context._currentContext.delete(key); + return context; + }; + } + }; + ROOT_CONTEXT = new BaseContext(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js +var consoleMap, _originalConsoleMethods, DiagConsoleLogger; +var init_consoleLogger = __esmMin((() => { + consoleMap = [ + { + n: "error", + c: "error" + }, + { + n: "warn", + c: "warn" + }, + { + n: "info", + c: "info" + }, + { + n: "debug", + c: "debug" + }, + { + n: "verbose", + c: "trace" + } + ]; + _originalConsoleMethods = {}; + if (typeof console !== "undefined") { + for (const key of [ + "error", + "warn", + "info", + "debug", + "trace", + "log" + ]) if (typeof console[key] === "function") _originalConsoleMethods[key] = console[key]; + } + DiagConsoleLogger = class { + constructor() { + function _consoleFunc(funcName) { + return function(...args) { + let theFunc = _originalConsoleMethods[funcName]; + if (typeof theFunc !== "function") theFunc = _originalConsoleMethods["log"]; + if (typeof theFunc !== "function" && console) { + theFunc = console[funcName]; + if (typeof theFunc !== "function") theFunc = console.log; + } + if (typeof theFunc === "function") return theFunc.apply(console, args); + }; + } + for (let i = 0; i < consoleMap.length; i++) this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js +/** +* Create a no-op Meter +* +* @since 1.3.0 +*/ +function createNoopMeter() { + return NOOP_METER; +} +var NoopMeter, NoopMetric, NoopCounterMetric, NoopUpDownCounterMetric, NoopGaugeMetric, NoopHistogramMetric, NoopObservableMetric, NoopObservableCounterMetric, NoopObservableGaugeMetric, NoopObservableUpDownCounterMetric, NOOP_METER, NOOP_COUNTER_METRIC, NOOP_GAUGE_METRIC, NOOP_HISTOGRAM_METRIC, NOOP_UP_DOWN_COUNTER_METRIC, NOOP_OBSERVABLE_COUNTER_METRIC, NOOP_OBSERVABLE_GAUGE_METRIC, NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; +var init_NoopMeter = __esmMin((() => { + NoopMeter = class { + constructor() {} + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) {} + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) {} + }; + NoopMetric = class {}; + NoopCounterMetric = class extends NoopMetric { + add(_value, _attributes) {} + }; + NoopUpDownCounterMetric = class extends NoopMetric { + add(_value, _attributes) {} + }; + NoopGaugeMetric = class extends NoopMetric { + record(_value, _attributes) {} + }; + NoopHistogramMetric = class extends NoopMetric { + record(_value, _attributes) {} + }; + NoopObservableMetric = class { + addCallback(_callback) {} + removeCallback(_callback) {} + }; + NoopObservableCounterMetric = class extends NoopObservableMetric {}; + NoopObservableGaugeMetric = class extends NoopObservableMetric {}; + NoopObservableUpDownCounterMetric = class extends NoopObservableMetric {}; + NOOP_METER = new NoopMeter(); + NOOP_COUNTER_METRIC = new NoopCounterMetric(); + NOOP_GAUGE_METRIC = new NoopGaugeMetric(); + NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); + NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); + NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); + NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); + NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/Metric.js +var ValueType; +var init_Metric = __esmMin((() => { + ; + (function(ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; + })(ValueType || (ValueType = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js +var defaultTextMapGetter, defaultTextMapSetter; +var init_TextMapPropagator = __esmMin((() => { + defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) return; + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) return []; + return Object.keys(carrier); + } + }; + defaultTextMapSetter = { set(carrier, key, value) { + if (carrier == null) return; + carrier[key] = value; + } }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js +var NoopContextManager; +var init_NoopContextManager = __esmMin((() => { + init_context$1(); + NoopContextManager = class { + active() { + return ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/context.js +var API_NAME$3, NOOP_CONTEXT_MANAGER, ContextAPI; +var init_context = __esmMin((() => { + init_NoopContextManager(); + init_global_utils(); + init_diag(); + API_NAME$3 = "context"; + NOOP_CONTEXT_MANAGER = new NoopContextManager(); + ContextAPI = class ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() {} + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) this._instance = new ContextAPI(); + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return registerGlobal(API_NAME$3, contextManager, DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context, target) { + return this._getContextManager().bind(context, target); + } + _getContextManager() { + return getGlobal(API_NAME$3) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + unregisterGlobal(API_NAME$3, DiagAPI.instance()); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js +var TraceFlags; +var init_trace_flags = __esmMin((() => { + ; + (function(TraceFlags) { + /** Represents no flag set. */ + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + /** Bit to represent whether trace is sampled in trace flags. */ + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; + })(TraceFlags || (TraceFlags = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js +var INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT; +var init_invalid_span_constants = __esmMin((() => { + init_trace_flags(); + INVALID_SPANID = "0000000000000000"; + INVALID_TRACEID = "00000000000000000000000000000000"; + INVALID_SPAN_CONTEXT = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: TraceFlags.NONE + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js +var NonRecordingSpan; +var init_NonRecordingSpan = __esmMin((() => { + init_invalid_span_constants(); + NonRecordingSpan = class { + constructor(spanContext = INVALID_SPAN_CONTEXT) { + this._spanContext = spanContext; + } + spanContext() { + return this._spanContext; + } + setAttribute(_key, _value) { + return this; + } + setAttributes(_attributes) { + return this; + } + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + setStatus(_status) { + return this; + } + updateName(_name) { + return this; + } + end(_endTime) {} + isRecording() { + return false; + } + recordException(_exception, _time) {} + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js +/** +* Return the span if one exists +* +* @param context context to get span from +*/ +function getSpan(context) { + return context.getValue(SPAN_KEY) || void 0; +} +/** +* Gets the span from the current context, if one exists. +*/ +function getActiveSpan() { + return getSpan(ContextAPI.getInstance().active()); +} +/** +* Set the span on a context +* +* @param context context to use as parent +* @param span span to set active +*/ +function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +/** +* Remove current span stored in the context +* +* @param context context to delete span from +*/ +function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +/** +* Wrap span context in a NoopSpan and set as span in a new +* context +* +* @param context context to set active span on +* @param spanContext span context to be wrapped +*/ +function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan(spanContext)); +} +/** +* Get the span context of the span if it exists. +* +* @param context context to get values from +*/ +function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +var SPAN_KEY; +var init_context_utils = __esmMin((() => { + init_context$1(); + init_NonRecordingSpan(); + init_context(); + SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN"); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js +function isValidHex(id, length) { + if (typeof id !== "string" || id.length !== length) return false; + let r = 0; + for (let i = 0; i < id.length; i += 4) r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0); + return r === length; +} +/** +* @since 1.0.0 +*/ +function isValidTraceId(traceId) { + return isValidHex(traceId, 32) && traceId !== "00000000000000000000000000000000"; +} +/** +* @since 1.0.0 +*/ +function isValidSpanId(spanId) { + return isValidHex(spanId, 16) && spanId !== "0000000000000000"; +} +/** +* Returns true if this {@link SpanContext} is valid. +* @return true if this {@link SpanContext} is valid. +* +* @since 1.0.0 +*/ +function isSpanContextValid(spanContext) { + return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); +} +/** +* Wrap the given {@link SpanContext} in a new non-recording {@link Span} +* +* @param spanContext span context to be wrapped +* @returns a new non-recording {@link Span} with the provided context +*/ +function wrapSpanContext(spanContext) { + return new NonRecordingSpan(spanContext); +} +var isHex; +var init_spancontext_utils = __esmMin((() => { + init_invalid_span_constants(); + init_NonRecordingSpan(); + isHex = new Uint8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1 + ]); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js +function isSpanContext(spanContext) { + return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number"; +} +var contextApi, NoopTracer; +var init_NoopTracer = __esmMin((() => { + init_context(); + init_context_utils(); + init_NonRecordingSpan(); + init_spancontext_utils(); + contextApi = ContextAPI.getInstance(); + NoopTracer = class { + startSpan(name, options, context = contextApi.active()) { + if (Boolean(options === null || options === void 0 ? void 0 : options.root)) return new NonRecordingSpan(); + const parentFromContext = context && getSpanContext(context); + if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan(parentFromContext); + else return new NonRecordingSpan(); + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) return; + else if (arguments.length === 2) fn = arg2; + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = setSpan(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, void 0, span); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js +var NOOP_TRACER, ProxyTracer; +var init_ProxyTracer = __esmMin((() => { + init_NoopTracer(); + NOOP_TRACER = new NoopTracer(); + ProxyTracer = class { + constructor(provider, name, version, options) { + this._provider = provider; + this.name = name; + this.version = version; + this.options = options; + } + startSpan(name, options, context) { + return this._getTracer().startSpan(name, options, context); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) return this._delegate; + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) return NOOP_TRACER; + this._delegate = tracer; + return this._delegate; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js +var NoopTracerProvider; +var init_NoopTracerProvider = __esmMin((() => { + init_NoopTracer(); + NoopTracerProvider = class { + getTracer(_name, _version, _options) { + return new NoopTracer(); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js +var NOOP_TRACER_PROVIDER, ProxyTracerProvider; +var init_ProxyTracerProvider = __esmMin((() => { + init_ProxyTracer(); + init_NoopTracerProvider(); + NOOP_TRACER_PROVIDER = new NoopTracerProvider(); + ProxyTracerProvider = class { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version, options) { + var _a; + return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js +var SamplingDecision; +var init_SamplingResult = __esmMin((() => { + ; + (function(SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(SamplingDecision || (SamplingDecision = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js +var SpanKind; +var init_span_kind = __esmMin((() => { + ; + (function(SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; + })(SpanKind || (SpanKind = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/status.js +var SpanStatusCode; +var init_status = __esmMin((() => { + ; + (function(SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; + })(SpanStatusCode || (SpanStatusCode = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js +/** +* Key is opaque string up to 256 characters printable. It MUST begin with a +* lowercase letter, and can only contain lowercase letters a-z, digits 0-9, +* underscores _, dashes -, asterisks *, and forward slashes /. +* For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the +* vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. +* see https://www.w3.org/TR/trace-context/#key +*/ +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +/** +* Value is opaque string up to 256 characters printable ASCII RFC0020 +* characters (i.e., the range 0x20 to 0x7E) except comma , and =. +*/ +function validateValue(value) { + return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value); +} +var VALID_KEY_CHAR_RANGE, VALID_KEY_REGEX, VALID_VALUE_BASE_REGEX, INVALID_VALUE_COMMA_EQUAL_REGEX; +var init_tracestate_validators = __esmMin((() => { + VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]"; + VALID_KEY_REGEX = new RegExp(`^(?:${`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`}|${`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`})$`); + VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; + INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js +var MAX_TRACE_STATE_ITEMS, MAX_TRACE_STATE_LEN, LIST_MEMBERS_SEPARATOR, LIST_MEMBER_KEY_VALUE_SPLITTER, TraceStateImpl; +var init_tracestate_impl = __esmMin((() => { + init_tracestate_validators(); + MAX_TRACE_STATE_ITEMS = 32; + MAX_TRACE_STATE_LEN = 512; + LIST_MEMBERS_SEPARATOR = ","; + LIST_MEMBER_KEY_VALUE_SPLITTER = "="; + TraceStateImpl = class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = /* @__PURE__ */ new Map(); + if (rawTraceState) this._parse(rawTraceState); + } + set(key, value) { + const traceState = this._clone(); + if (traceState._internalState.has(key)) traceState._internalState.delete(key); + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return Array.from(this._internalState.keys()).reduceRight((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []).join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) return; + this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reduceRight((agg, part) => { + const listMember = part.trim(); + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if (validateKey(key) && validateValue(value)) agg.set(key, value); + } + return agg; + }, /* @__PURE__ */ new Map()); + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS)); + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js +/** +* @since 1.1.0 +*/ +function createTraceState(rawTraceState) { + return new TraceStateImpl(rawTraceState); +} +var init_utils$1 = __esmMin((() => { + init_tracestate_impl(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context-api.js +var context; +var init_context_api = __esmMin((() => { + init_context(); + context = ContextAPI.getInstance(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag-api.js +var diag; +var init_diag_api = __esmMin((() => { + init_diag(); + diag = DiagAPI.instance(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js +var NoopMeterProvider, NOOP_METER_PROVIDER; +var init_NoopMeterProvider = __esmMin((() => { + init_NoopMeter(); + NoopMeterProvider = class { + getMeter(_name, _version, _options) { + return NOOP_METER; + } + }; + NOOP_METER_PROVIDER = new NoopMeterProvider(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/metrics.js +var API_NAME$2, MetricsAPI; +var init_metrics = __esmMin((() => { + init_NoopMeterProvider(); + init_global_utils(); + init_diag(); + API_NAME$2 = "metrics"; + MetricsAPI = class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() {} + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) this._instance = new MetricsAPI(); + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return registerGlobal(API_NAME$2, provider, DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return getGlobal(API_NAME$2) || NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + unregisterGlobal(API_NAME$2, DiagAPI.instance()); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/metrics-api.js +var metrics; +var init_metrics_api = __esmMin((() => { + init_metrics(); + metrics = MetricsAPI.getInstance(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js +var NoopTextMapPropagator; +var init_NoopTextMapPropagator = __esmMin((() => { + NoopTextMapPropagator = class { + /** Noop inject function does nothing */ + inject(_context, _carrier) {} + /** Noop extract function does nothing and returns the input context */ + extract(context, _carrier) { + return context; + } + fields() { + return []; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js +/** +* Retrieve the current baggage from the given context +* +* @param {Context} Context that manage all context values +* @returns {Baggage} Extracted baggage from the context +*/ +function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || void 0; +} +/** +* Retrieve the current baggage from the active/current context +* +* @returns {Baggage} Extracted baggage from the context +*/ +function getActiveBaggage() { + return getBaggage(ContextAPI.getInstance().active()); +} +/** +* Store a baggage in the given context +* +* @param {Context} Context that manage all context values +* @param {Baggage} baggage that will be set in the actual context +*/ +function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +/** +* Delete the baggage stored in the given context +* +* @param {Context} Context that manage all context values +*/ +function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +var BAGGAGE_KEY; +var init_context_helpers = __esmMin((() => { + init_context(); + init_context$1(); + BAGGAGE_KEY = createContextKey("OpenTelemetry Baggage Key"); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/propagation.js +var API_NAME$1, NOOP_TEXT_MAP_PROPAGATOR, PropagationAPI; +var init_propagation = __esmMin((() => { + init_global_utils(); + init_NoopTextMapPropagator(); + init_TextMapPropagator(); + init_context_helpers(); + init_utils$2(); + init_diag(); + API_NAME$1 = "propagation"; + NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); + PropagationAPI = class PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = createBaggage; + this.getBaggage = getBaggage; + this.getActiveBaggage = getActiveBaggage; + this.setBaggage = setBaggage; + this.deleteBaggage = deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) this._instance = new PropagationAPI(); + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return registerGlobal(API_NAME$1, propagator, DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context, carrier, setter = defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context, carrier, getter = defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + unregisterGlobal(API_NAME$1, DiagAPI.instance()); + } + _getGlobalPropagator() { + return getGlobal(API_NAME$1) || NOOP_TEXT_MAP_PROPAGATOR; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/propagation-api.js +var propagation; +var init_propagation_api = __esmMin((() => { + init_propagation(); + propagation = PropagationAPI.getInstance(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/trace.js +var API_NAME, TraceAPI; +var init_trace$1 = __esmMin((() => { + init_global_utils(); + init_ProxyTracerProvider(); + init_spancontext_utils(); + init_context_utils(); + init_diag(); + API_NAME = "trace"; + TraceAPI = class TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider(); + this.wrapSpanContext = wrapSpanContext; + this.isSpanContextValid = isSpanContextValid; + this.deleteSpan = deleteSpan; + this.getSpan = getSpan; + this.getActiveSpan = getActiveSpan; + this.getSpanContext = getSpanContext; + this.setSpan = setSpan; + this.setSpanContext = setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) this._instance = new TraceAPI(); + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance()); + if (success) this._proxyTracerProvider.setDelegate(provider); + return success; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return getGlobal(API_NAME) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version) { + return this.getTracerProvider().getTracer(name, version); + } + /** Remove the global tracer provider */ + disable() { + unregisterGlobal(API_NAME, DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider(); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace-api.js +var trace; +var init_trace_api = __esmMin((() => { + init_trace$1(); + trace = TraceAPI.getInstance(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/index.js +var esm_exports$2 = /* @__PURE__ */ __exportAll({ + DiagConsoleLogger: () => DiagConsoleLogger, + DiagLogLevel: () => DiagLogLevel, + INVALID_SPANID: () => INVALID_SPANID, + INVALID_SPAN_CONTEXT: () => INVALID_SPAN_CONTEXT, + INVALID_TRACEID: () => INVALID_TRACEID, + ProxyTracer: () => ProxyTracer, + ProxyTracerProvider: () => ProxyTracerProvider, + ROOT_CONTEXT: () => ROOT_CONTEXT, + SamplingDecision: () => SamplingDecision, + SpanKind: () => SpanKind, + SpanStatusCode: () => SpanStatusCode, + TraceFlags: () => TraceFlags, + ValueType: () => ValueType, + baggageEntryMetadataFromString: () => baggageEntryMetadataFromString, + context: () => context, + createContextKey: () => createContextKey, + createNoopMeter: () => createNoopMeter, + createTraceState: () => createTraceState, + default: () => esm_default, + defaultTextMapGetter: () => defaultTextMapGetter, + defaultTextMapSetter: () => defaultTextMapSetter, + diag: () => diag, + isSpanContextValid: () => isSpanContextValid, + isValidSpanId: () => isValidSpanId, + isValidTraceId: () => isValidTraceId, + metrics: () => metrics, + propagation: () => propagation, + trace: () => trace +}); +var esm_default; +var init_esm$2 = __esmMin((() => { + init_utils$2(); + init_context$1(); + init_consoleLogger(); + init_types$1(); + init_NoopMeter(); + init_Metric(); + init_TextMapPropagator(); + init_ProxyTracer(); + init_ProxyTracerProvider(); + init_SamplingResult(); + init_span_kind(); + init_status(); + init_trace_flags(); + init_utils$1(); + init_spancontext_utils(); + init_invalid_span_constants(); + init_context_api(); + init_diag_api(); + init_metrics_api(); + init_propagation_api(); + init_trace_api(); + esm_default = { + context, + diag, + metrics, + propagation, + trace + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@langfuse+core@5.11.1_@opentelemetry+api@1.9.1/node_modules/@langfuse/core/dist/index.mjs +init_esm$2(); +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) __defProp(target, name, { + get: all[name], + enumerable: true + }); +}; +function getEnv(key) { + if (typeof process !== "undefined" && process.env[key]) return process.env[key]; + else if (typeof globalThis !== "undefined") return globalThis[key]; +} +function base64ToBytes(base64) { + const binString = atob(base64); + return Uint8Array.from(binString, (m) => m.codePointAt(0)); +} +function bytesToBase64(bytes) { + const binString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""); + return btoa(binString); +} +function base64Encode(input) { + if (typeof Buffer !== "undefined") return Buffer.from(input, "utf8").toString("base64"); + return bytesToBase64(new TextEncoder().encode(input)); +} +var LogLevel = /* @__PURE__ */ ((LogLevel2) => { + LogLevel2[LogLevel2["NONE"] = 4] = "NONE"; + LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR"; + LogLevel2[LogLevel2["WARN"] = 2] = "WARN"; + LogLevel2[LogLevel2["INFO"] = 1] = "INFO"; + LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG"; + return LogLevel2; +})(LogLevel || {}); +function parseLogLevelFromEnv() { + var _a2; + if (typeof process === "object" && "env" in process) { + if (((_a2 = getEnv("LANGFUSE_DEBUG")) == null ? void 0 : _a2.toLowerCase()) === "true") return 0; + const envValue = getEnv("LANGFUSE_LOG_LEVEL"); + switch ((envValue != null ? envValue : "").toUpperCase()) { + case "NONE": return 4; + case "ERROR": return 3; + case "WARN": return 2; + case "INFO": return 1; + case "DEBUG": return 0; + default: return; + } + } +} +var Logger = class { + /** + * Creates a new Logger instance. + * + * @param config - Configuration options for the logger + */ + constructor(config = { level: 1 }) { + this.config = { + enableTimestamp: true, + ...config + }; + } + /** + * Determines if a message should be logged based on the current log level. + * + * @param level - The log level to check + * @returns True if the message should be logged, false otherwise + */ + shouldLog(level) { + return level >= this.config.level; + } + /** + * Formats a log message with timestamp, prefix, and log level. + * + * @param level - The log level string + * @param message - The message to format + * @returns The formatted message string + */ + formatMessage(level, message) { + return [ + this.config.enableTimestamp ? (/* @__PURE__ */ new Date()).toISOString() : "", + this.config.prefix || "[Langfuse SDK]", + `[${level}]`, + message + ].filter(Boolean).join(" "); + } + /** + * Logs an error message. + * + * @param message - The error message to log + * @param args - Additional arguments to pass to console.error + */ + error(message, ...args) { + if (this.shouldLog(3)) console.error(this.formatMessage("ERROR", message), ...args); + } + /** + * Logs a warning message. + * + * @param message - The warning message to log + * @param args - Additional arguments to pass to console.warn + */ + warn(message, ...args) { + if (this.shouldLog(2)) console.warn(this.formatMessage("WARN", message), ...args); + } + /** + * Logs an informational message. + * + * @param message - The info message to log + * @param args - Additional arguments to pass to console.info + */ + info(message, ...args) { + if (this.shouldLog(1)) console.info(this.formatMessage("INFO", message), ...args); + } + /** + * Logs a debug message. + * + * @param message - The debug message to log + * @param args - Additional arguments to pass to console.debug + */ + debug(message, ...args) { + if (this.shouldLog(0)) console.debug(this.formatMessage("DEBUG", message), ...args); + } + /** + * Sets the minimum log level. + * + * @param level - The new log level + */ + setLevel(level) { + this.config.level = level; + } + /** + * Gets the current log level. + * + * @returns The current log level + */ + getLevel() { + return this.config.level; + } + /** + * Checks if a given log level is enabled. + * Use this to guard expensive operations (like JSON.stringify) before debug logging. + * + * @param level - The log level to check + * @returns True if the level is enabled, false otherwise + * + * @example + * ```typescript + * if (logger.isLevelEnabled(LogLevel.DEBUG)) { + * logger.debug('Expensive data:', JSON.stringify(largeObject)); + * } + * ``` + */ + isLevelEnabled(level) { + return this.shouldLog(level); + } +}; +var _a; +var _LoggerSingleton = class _LoggerSingleton { + /** + * Gets the singleton logger instance, creating it if it doesn't exist. + * + * @returns The singleton logger instance + */ + static getInstance() { + if (!_LoggerSingleton.instance) _LoggerSingleton.instance = new Logger(_LoggerSingleton.defaultConfig); + return _LoggerSingleton.instance; + } + /** + * Configures the global logger with new settings. + * This will replace the existing logger instance. + * + * @param config - The new logger configuration + */ + static configure(config) { + _LoggerSingleton.defaultConfig = config; + _LoggerSingleton.instance = new Logger(config); + } + /** + * Resets the singleton logger instance and configuration. + * Useful for testing or reinitializing the logger. + */ + static reset() { + _LoggerSingleton.instance = null; + _LoggerSingleton.defaultConfig = { level: 1 }; + } +}; +_LoggerSingleton.instance = null; +_LoggerSingleton.defaultConfig = { level: (_a = parseLogLevelFromEnv()) != null ? _a : 1 }; +var LoggerSingleton = _LoggerSingleton; +var getGlobalLogger = () => { + return LoggerSingleton.getInstance(); +}; +var package_default = { + name: "@langfuse/core", + version: "5.11.1", + description: "Core functions and utilities for Langfuse packages", + type: "module", + sideEffects: false, + main: "./dist/index.cjs", + module: "./dist/index.mjs", + types: "./dist/index.d.ts", + exports: { ".": { + import: { + types: "./dist/index.d.ts", + default: "./dist/index.mjs" + }, + require: { + types: "./dist/index.d.cts", + default: "./dist/index.cjs" + } + } }, + scripts: { + build: "tsup", + test: "vitest run", + "test:watch": "vitest", + format: "prettier --write \"src/**/*.ts\"", + "format:check": "prettier --check \"src/**/*.ts\"", + clean: "rm -rf dist" + }, + author: "Langfuse", + license: "MIT", + repository: { + type: "git", + url: "https://github.com/langfuse/langfuse-js.git", + directory: "packages/core" + }, + files: ["dist"], + peerDependencies: { "@opentelemetry/api": "^1.9.0" }, + devDependencies: { "@types/node": "^24.1.0" } +}; +var LANGFUSE_TRACER_NAME = "langfuse-sdk"; +var LANGFUSE_SDK_VERSION = package_default.version; +var LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT = "sdk-experiment"; +var LangfuseOtelSpanAttributes = /* @__PURE__ */ ((LangfuseOtelSpanAttributes2) => { + LangfuseOtelSpanAttributes2["TRACE_NAME"] = "langfuse.trace.name"; + LangfuseOtelSpanAttributes2["TRACE_USER_ID"] = "user.id"; + LangfuseOtelSpanAttributes2["TRACE_SESSION_ID"] = "session.id"; + LangfuseOtelSpanAttributes2["TRACE_TAGS"] = "langfuse.trace.tags"; + LangfuseOtelSpanAttributes2["TRACE_PUBLIC"] = "langfuse.trace.public"; + LangfuseOtelSpanAttributes2["TRACE_METADATA"] = "langfuse.trace.metadata"; + LangfuseOtelSpanAttributes2["TRACE_INPUT"] = "langfuse.trace.input"; + LangfuseOtelSpanAttributes2["TRACE_OUTPUT"] = "langfuse.trace.output"; + LangfuseOtelSpanAttributes2["OBSERVATION_TYPE"] = "langfuse.observation.type"; + LangfuseOtelSpanAttributes2["OBSERVATION_METADATA"] = "langfuse.observation.metadata"; + LangfuseOtelSpanAttributes2["OBSERVATION_LEVEL"] = "langfuse.observation.level"; + LangfuseOtelSpanAttributes2["OBSERVATION_STATUS_MESSAGE"] = "langfuse.observation.status_message"; + LangfuseOtelSpanAttributes2["OBSERVATION_INPUT"] = "langfuse.observation.input"; + LangfuseOtelSpanAttributes2["OBSERVATION_OUTPUT"] = "langfuse.observation.output"; + LangfuseOtelSpanAttributes2["OBSERVATION_COMPLETION_START_TIME"] = "langfuse.observation.completion_start_time"; + LangfuseOtelSpanAttributes2["OBSERVATION_MODEL"] = "langfuse.observation.model.name"; + LangfuseOtelSpanAttributes2["OBSERVATION_MODEL_PARAMETERS"] = "langfuse.observation.model.parameters"; + LangfuseOtelSpanAttributes2["OBSERVATION_USAGE_DETAILS"] = "langfuse.observation.usage_details"; + LangfuseOtelSpanAttributes2["OBSERVATION_COST_DETAILS"] = "langfuse.observation.cost_details"; + LangfuseOtelSpanAttributes2["OBSERVATION_PROMPT_NAME"] = "langfuse.observation.prompt.name"; + LangfuseOtelSpanAttributes2["OBSERVATION_PROMPT_VERSION"] = "langfuse.observation.prompt.version"; + LangfuseOtelSpanAttributes2["ENVIRONMENT"] = "langfuse.environment"; + LangfuseOtelSpanAttributes2["RELEASE"] = "langfuse.release"; + LangfuseOtelSpanAttributes2["VERSION"] = "langfuse.version"; + LangfuseOtelSpanAttributes2["AS_ROOT"] = "langfuse.internal.as_root"; + LangfuseOtelSpanAttributes2["IS_APP_ROOT"] = "langfuse.internal.is_app_root"; + LangfuseOtelSpanAttributes2["EXPERIMENT_ID"] = "langfuse.experiment.id"; + LangfuseOtelSpanAttributes2["EXPERIMENT_NAME"] = "langfuse.experiment.name"; + LangfuseOtelSpanAttributes2["EXPERIMENT_DESCRIPTION"] = "langfuse.experiment.description"; + LangfuseOtelSpanAttributes2["EXPERIMENT_METADATA"] = "langfuse.experiment.metadata"; + LangfuseOtelSpanAttributes2["EXPERIMENT_DATASET_ID"] = "langfuse.experiment.dataset.id"; + LangfuseOtelSpanAttributes2["EXPERIMENT_ITEM_ID"] = "langfuse.experiment.item.id"; + LangfuseOtelSpanAttributes2["EXPERIMENT_ITEM_EXPECTED_OUTPUT"] = "langfuse.experiment.item.expected_output"; + LangfuseOtelSpanAttributes2["EXPERIMENT_ITEM_METADATA"] = "langfuse.experiment.item.metadata"; + LangfuseOtelSpanAttributes2["EXPERIMENT_ITEM_ROOT_OBSERVATION_ID"] = "langfuse.experiment.item.root_observation_id"; + LangfuseOtelSpanAttributes2["TRACE_COMPAT_USER_ID"] = "langfuse.user.id"; + LangfuseOtelSpanAttributes2["TRACE_COMPAT_SESSION_ID"] = "langfuse.session.id"; + return LangfuseOtelSpanAttributes2; +})(LangfuseOtelSpanAttributes || {}); +var annotationQueues_exports = {}; +__export(annotationQueues_exports, { + AnnotationQueueObjectType: () => AnnotationQueueObjectType, + AnnotationQueueStatus: () => AnnotationQueueStatus +}); +var AnnotationQueueStatus = { + Pending: "PENDING", + Completed: "COMPLETED" +}; +var AnnotationQueueObjectType = { + Trace: "TRACE", + Observation: "OBSERVATION", + Session: "SESSION" +}; +var blobStorageIntegrations_exports = {}; +__export(blobStorageIntegrations_exports, { + BlobStorageExportFieldGroup: () => BlobStorageExportFieldGroup, + BlobStorageExportFrequency: () => BlobStorageExportFrequency, + BlobStorageExportMode: () => BlobStorageExportMode, + BlobStorageExportSource: () => BlobStorageExportSource, + BlobStorageIntegrationFileType: () => BlobStorageIntegrationFileType, + BlobStorageIntegrationFileTypeResponse: () => BlobStorageIntegrationFileTypeResponse, + BlobStorageIntegrationType: () => BlobStorageIntegrationType, + BlobStorageSyncStatus: () => BlobStorageSyncStatus +}); +var BlobStorageIntegrationType = { + S3: "S3", + S3Compatible: "S3_COMPATIBLE", + AzureBlobStorage: "AZURE_BLOB_STORAGE" +}; +var BlobStorageIntegrationFileType = { + Json: "JSON", + Csv: "CSV", + Jsonl: "JSONL", + Parquet: "PARQUET" +}; +var BlobStorageIntegrationFileTypeResponse = { + Json: "JSON", + Csv: "CSV", + Jsonl: "JSONL", + Parquet: "PARQUET" +}; +var BlobStorageExportMode = { + FullHistory: "FULL_HISTORY", + FromToday: "FROM_TODAY", + FromCustomDate: "FROM_CUSTOM_DATE" +}; +var BlobStorageExportFrequency = { + Every20Minutes: "every_20_minutes", + Hourly: "hourly", + Daily: "daily", + Weekly: "weekly" +}; +var BlobStorageExportSource = { + LegacyTracesObservations: "LEGACY_TRACES_OBSERVATIONS", + ObservationsV2: "OBSERVATIONS_V2", + LegacyTracesAndEnrichedObservations: "LEGACY_TRACES_AND_ENRICHED_OBSERVATIONS" +}; +var BlobStorageExportFieldGroup = { + Core: "core", + Basic: "basic", + Time: "time", + Io: "io", + Metadata: "metadata", + Model: "model", + Usage: "usage", + Prompt: "prompt", + Metrics: "metrics", + Tools: "tools", + TraceContext: "trace_context" +}; +var BlobStorageSyncStatus = { + Idle: "idle", + Running: "running", + Queued: "queued", + UpToDate: "up_to_date", + Disabled: "disabled", + Error: "error" +}; +var commons_exports = {}; +__export(commons_exports, { + AccessDeniedError: () => AccessDeniedError, + CommentObjectType: () => CommentObjectType, + DatasetItemMediaReferenceField: () => DatasetItemMediaReferenceField, + DatasetStatus: () => DatasetStatus, + Error: () => Error2, + MethodNotAllowedError: () => MethodNotAllowedError, + ModelUsageUnit: () => ModelUsageUnit, + NotFoundError: () => NotFoundError, + ObservationLevel: () => ObservationLevel, + PricingTierAttributeSource: () => PricingTierAttributeSource, + PricingTierOperator: () => PricingTierOperator, + ScoreConfigDataType: () => ScoreConfigDataType, + ScoreDataType: () => ScoreDataType, + ScoreSource: () => ScoreSource, + UnauthorizedError: () => UnauthorizedError +}); +var DatasetItemMediaReferenceField = { + Input: "input", + ExpectedOutput: "expectedOutput", + Metadata: "metadata" +}; +var PricingTierAttributeSource = { + ModelParameters: "model_parameters", + Metadata: "metadata" +}; +var PricingTierOperator = { + Gt: "gt", + Gte: "gte", + Lt: "lt", + Lte: "lte", + Eq: "eq", + Neq: "neq" +}; +var ModelUsageUnit = { + Characters: "CHARACTERS", + Tokens: "TOKENS", + Milliseconds: "MILLISECONDS", + Seconds: "SECONDS", + Images: "IMAGES", + Requests: "REQUESTS" +}; +var ObservationLevel = { + Debug: "DEBUG", + Default: "DEFAULT", + Warning: "WARNING", + Error: "ERROR" +}; +var CommentObjectType = { + Trace: "TRACE", + Observation: "OBSERVATION", + Session: "SESSION", + Prompt: "PROMPT" +}; +var DatasetStatus = { + Active: "ACTIVE", + Archived: "ARCHIVED" +}; +var ScoreSource = { + Annotation: "ANNOTATION", + Api: "API", + Eval: "EVAL" +}; +var ScoreConfigDataType = { + Numeric: "NUMERIC", + Boolean: "BOOLEAN", + Categorical: "CATEGORICAL", + Text: "TEXT" +}; +var ScoreDataType = { + Numeric: "NUMERIC", + Boolean: "BOOLEAN", + Categorical: "CATEGORICAL", + Correction: "CORRECTION", + Text: "TEXT" +}; +var toJson = (value, replacer, space) => { + return JSON.stringify(value, replacer, space); +}; +function fromJson(text, reviver) { + return JSON.parse(text, reviver); +} +var LangfuseAPIError = class _LangfuseAPIError extends Error { + constructor({ message, statusCode, body, rawResponse }) { + super(buildMessage({ + message, + statusCode, + body + })); + Object.setPrototypeOf(this, _LangfuseAPIError.prototype); + this.statusCode = statusCode; + this.body = body; + this.rawResponse = rawResponse; + } +}; +function buildMessage({ message, statusCode, body }) { + let lines = []; + if (message != null) lines.push(message); + if (statusCode != null) lines.push(`Status code: ${statusCode.toString()}`); + if (body != null) lines.push(`Body: ${toJson(body, void 0, 2)}`); + return lines.join("\n"); +} +var LangfuseAPITimeoutError = class _LangfuseAPITimeoutError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, _LangfuseAPITimeoutError.prototype); + } +}; +var Error2 = class _Error extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "Error", + statusCode: 400, + body, + rawResponse + }); + Object.setPrototypeOf(this, _Error.prototype); + } +}; +var UnauthorizedError = class _UnauthorizedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "UnauthorizedError", + statusCode: 401, + body, + rawResponse + }); + Object.setPrototypeOf(this, _UnauthorizedError.prototype); + } +}; +var AccessDeniedError = class _AccessDeniedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "AccessDeniedError", + statusCode: 403, + body, + rawResponse + }); + Object.setPrototypeOf(this, _AccessDeniedError.prototype); + } +}; +var NotFoundError = class _NotFoundError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "NotFoundError", + statusCode: 404, + body, + rawResponse + }); + Object.setPrototypeOf(this, _NotFoundError.prototype); + } +}; +var MethodNotAllowedError = class _MethodNotAllowedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "MethodNotAllowedError", + statusCode: 405, + body, + rawResponse + }); + Object.setPrototypeOf(this, _MethodNotAllowedError.prototype); + } +}; +var evaluationCommons_exports = {}; +__export(evaluationCommons_exports, { + CodeEvaluatorSourceCodeLanguage: () => CodeEvaluatorSourceCodeLanguage, + EvaluationRuleArrayOptionsFilterOperator: () => EvaluationRuleArrayOptionsFilterOperator, + EvaluationRuleBooleanFilterOperator: () => EvaluationRuleBooleanFilterOperator, + EvaluationRuleNullFilterOperator: () => EvaluationRuleNullFilterOperator, + EvaluationRuleNumberFilterOperator: () => EvaluationRuleNumberFilterOperator, + EvaluationRuleOptionsFilterOperator: () => EvaluationRuleOptionsFilterOperator, + EvaluationRuleStringFilterOperator: () => EvaluationRuleStringFilterOperator, + EvaluatorOutputScoreType: () => EvaluatorOutputScoreType, + EvaluatorType: () => EvaluatorType, + LegacyEvaluationObject: () => LegacyEvaluationObject, + PromptVariableMappingSource: () => PromptVariableMappingSource +}); +var EvaluatorType = { + LlmAsJudge: "llm_as_judge", + Code: "code" +}; +var CodeEvaluatorSourceCodeLanguage = { + Python: "PYTHON", + Typescript: "TYPESCRIPT" +}; +var PromptVariableMappingSource = { + Input: "input", + Output: "output", + Metadata: "metadata", + ToolCalls: "tool_calls", + ExpectedOutput: "expected_output", + ExperimentItemMetadata: "experiment_item_metadata" +}; +var EvaluatorOutputScoreType = { + Numeric: "NUMERIC", + Boolean: "BOOLEAN", + Categorical: "CATEGORICAL" +}; +var EvaluationRuleStringFilterOperator = { + Equals: "=", + Contains: "contains", + DoesNotContain: "does not contain", + StartsWith: "starts with", + EndsWith: "ends with" +}; +var EvaluationRuleNumberFilterOperator = { + Equals: "=", + GreaterThan: ">", + LessThan: "<", + GreaterThanOrEqual: ">=", + LessThanOrEqual: "<=" +}; +var EvaluationRuleOptionsFilterOperator = { + AnyOf: "any of", + NoneOf: "none of" +}; +var EvaluationRuleArrayOptionsFilterOperator = { + AnyOf: "any of", + NoneOf: "none of", + AllOf: "all of" +}; +var EvaluationRuleBooleanFilterOperator = { + Equals: "=", + NotEquals: "<>" +}; +var EvaluationRuleNullFilterOperator = { + IsNull: "is null", + IsNotNull: "is not null" +}; +var LegacyEvaluationObject = { + Trace: "trace", + Span: "span", + Generation: "generation", + Event: "event", + Agent: "agent", + Tool: "tool", + Chain: "chain", + Retriever: "retriever", + Evaluator: "evaluator", + Embedding: "embedding", + Guardrail: "guardrail", + DatasetItem: "dataset_item" +}; +var evaluationErrors_exports = {}; +__export(evaluationErrors_exports, { + BadRequestError: () => BadRequestError, + ConflictError: () => ConflictError, + EvaluationAccessDeniedError: () => EvaluationAccessDeniedError, + EvaluationMethodNotAllowedError: () => EvaluationMethodNotAllowedError, + EvaluationNotFoundError: () => EvaluationNotFoundError, + EvaluationUnauthorizedError: () => EvaluationUnauthorizedError, + InternalServerError: () => InternalServerError, + PreconditionFailedError: () => PreconditionFailedError, + PublicApiErrorCode: () => PublicApiErrorCode, + TooManyRequestsError: () => TooManyRequestsError +}); +var PublicApiErrorCode = { + AuthenticationFailed: "authentication_failed", + AccessDenied: "access_denied", + InvalidRequest: "invalid_request", + InvalidQuery: "invalid_query", + InvalidBody: "invalid_body", + ResourceNotFound: "resource_not_found", + Conflict: "conflict", + RateLimited: "rate_limited", + MethodNotAllowed: "method_not_allowed", + InternalError: "internal_error" +}; +var BadRequestError = class _BadRequestError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "BadRequestError", + statusCode: 400, + body, + rawResponse + }); + Object.setPrototypeOf(this, _BadRequestError.prototype); + } +}; +var EvaluationUnauthorizedError = class _EvaluationUnauthorizedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "EvaluationUnauthorizedError", + statusCode: 401, + body, + rawResponse + }); + Object.setPrototypeOf(this, _EvaluationUnauthorizedError.prototype); + } +}; +var EvaluationAccessDeniedError = class _EvaluationAccessDeniedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "EvaluationAccessDeniedError", + statusCode: 403, + body, + rawResponse + }); + Object.setPrototypeOf(this, _EvaluationAccessDeniedError.prototype); + } +}; +var EvaluationNotFoundError = class _EvaluationNotFoundError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "EvaluationNotFoundError", + statusCode: 404, + body, + rawResponse + }); + Object.setPrototypeOf(this, _EvaluationNotFoundError.prototype); + } +}; +var EvaluationMethodNotAllowedError = class _EvaluationMethodNotAllowedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "EvaluationMethodNotAllowedError", + statusCode: 405, + body, + rawResponse + }); + Object.setPrototypeOf(this, _EvaluationMethodNotAllowedError.prototype); + } +}; +var ConflictError = class _ConflictError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "ConflictError", + statusCode: 409, + body, + rawResponse + }); + Object.setPrototypeOf(this, _ConflictError.prototype); + } +}; +var PreconditionFailedError = class _PreconditionFailedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "PreconditionFailedError", + statusCode: 412, + body, + rawResponse + }); + Object.setPrototypeOf(this, _PreconditionFailedError.prototype); + } +}; +var TooManyRequestsError = class _TooManyRequestsError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "TooManyRequestsError", + statusCode: 429, + body, + rawResponse + }); + Object.setPrototypeOf(this, _TooManyRequestsError.prototype); + } +}; +var InternalServerError = class _InternalServerError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "InternalServerError", + statusCode: 500, + body, + rawResponse + }); + Object.setPrototypeOf(this, _InternalServerError.prototype); + } +}; +var evaluators_exports = {}; +__export(evaluators_exports, { + EvaluatorChatMessageRole: () => EvaluatorChatMessageRole, + EvaluatorStatus: () => EvaluatorStatus +}); +var EvaluatorChatMessageRole = { + System: "system", + User: "user", + Assistant: "assistant" +}; +var EvaluatorStatus = { + Active: "active", + Paused: "paused" +}; +var feedback_exports = {}; +__export(feedback_exports, { + FeedbackNotConfiguredError: () => FeedbackNotConfiguredError, + FeedbackTargetType: () => FeedbackTargetType +}); +var FeedbackTargetType = { + Skill: "skill", + McpTool: "mcp-tool", + Cli: "cli", + Docs: "docs", + PublicApi: "public-api", + Other: "other" +}; +var FeedbackNotConfiguredError = class _FeedbackNotConfiguredError extends LangfuseAPIError { + constructor(rawResponse) { + super({ + message: "FeedbackNotConfiguredError", + statusCode: 409, + rawResponse + }); + Object.setPrototypeOf(this, _FeedbackNotConfiguredError.prototype); + } +}; +var health_exports = {}; +__export(health_exports, { ServiceUnavailableError: () => ServiceUnavailableError }); +var ServiceUnavailableError = class _ServiceUnavailableError extends LangfuseAPIError { + constructor(rawResponse) { + super({ + message: "ServiceUnavailableError", + statusCode: 503, + rawResponse + }); + Object.setPrototypeOf(this, _ServiceUnavailableError.prototype); + } +}; +var ingestion_exports = {}; +__export(ingestion_exports, { ObservationType: () => ObservationType }); +var ObservationType = { + Span: "SPAN", + Generation: "GENERATION", + Event: "EVENT", + Agent: "AGENT", + Tool: "TOOL", + Chain: "CHAIN", + Retriever: "RETRIEVER", + Evaluator: "EVALUATOR", + Embedding: "EMBEDDING", + Guardrail: "GUARDRAIL" +}; +var legacy_exports = {}; +__export(legacy_exports, { + CreateScoreSource: () => CreateScoreSource, + metricsV1: () => metricsV1_exports, + observationsV1: () => observationsV1_exports, + scoreV1: () => scoreV1_exports +}); +var metricsV1_exports = {}; +var observationsV1_exports = {}; +var scoreV1_exports = {}; +__export(scoreV1_exports, { CreateScoreSource: () => CreateScoreSource }); +var CreateScoreSource = { + Api: "API", + Annotation: "ANNOTATION" +}; +var llmConnections_exports = {}; +__export(llmConnections_exports, { LlmAdapter: () => LlmAdapter }); +var LlmAdapter = { + Anthropic: "anthropic", + OpenAi: "openai", + Azure: "azure", + Bedrock: "bedrock", + GoogleVertexAi: "google-vertex-ai", + GoogleAiStudio: "google-ai-studio" +}; +var media_exports = {}; +__export(media_exports, { MediaContentType: () => MediaContentType }); +var MediaContentType = { + ImagePng: "image/png", + ImageJpeg: "image/jpeg", + ImageJpg: "image/jpg", + ImageWebp: "image/webp", + ImageGif: "image/gif", + ImageSvgXml: "image/svg+xml", + ImageTiff: "image/tiff", + ImageBmp: "image/bmp", + ImageAvif: "image/avif", + ImageHeic: "image/heic", + AudioMpeg: "audio/mpeg", + AudioMp3: "audio/mp3", + AudioWav: "audio/wav", + AudioOgg: "audio/ogg", + AudioOga: "audio/oga", + AudioAac: "audio/aac", + AudioMp4: "audio/mp4", + AudioFlac: "audio/flac", + AudioOpus: "audio/opus", + AudioWebm: "audio/webm", + VideoMp4: "video/mp4", + VideoWebm: "video/webm", + VideoOgg: "video/ogg", + VideoMpeg: "video/mpeg", + VideoQuicktime: "video/quicktime", + VideoXMsvideo: "video/x-msvideo", + VideoXMatroska: "video/x-matroska", + TextPlain: "text/plain", + TextHtml: "text/html", + TextCss: "text/css", + TextCsv: "text/csv", + TextMarkdown: "text/markdown", + TextXPython: "text/x-python", + ApplicationJavascript: "application/javascript", + TextXTypescript: "text/x-typescript", + ApplicationXYaml: "application/x-yaml", + ApplicationPdf: "application/pdf", + ApplicationMsword: "application/msword", + ApplicationMsExcel: "application/vnd.ms-excel", + ApplicationOpenxmlSpreadsheet: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ApplicationZip: "application/zip", + ApplicationJson: "application/json", + ApplicationXml: "application/xml", + ApplicationOctetStream: "application/octet-stream", + ApplicationOpenxmlWord: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ApplicationOpenxmlPresentation: "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ApplicationRtf: "application/rtf", + ApplicationXNdjson: "application/x-ndjson", + ApplicationParquet: "application/vnd.apache.parquet", + ApplicationGzip: "application/gzip", + ApplicationXTar: "application/x-tar", + ApplicationX7ZCompressed: "application/x-7z-compressed" +}; +var models_exports = {}; +__export(models_exports, { ModelTokenizerId: () => ModelTokenizerId }); +var ModelTokenizerId = { + Openai: "openai", + Claude: "claude" +}; +var organizations_exports = {}; +__export(organizations_exports, { MembershipRole: () => MembershipRole }); +var MembershipRole = { + Owner: "OWNER", + Admin: "ADMIN", + Member: "MEMBER", + Viewer: "VIEWER" +}; +var prompts_exports = {}; +__export(prompts_exports, { + ChatMessageType: () => ChatMessageType, + CreateChatPromptType: () => CreateChatPromptType, + CreateTextPromptType: () => CreateTextPromptType, + PlaceholderMessageType: () => PlaceholderMessageType, + PromptType: () => PromptType +}); +var PromptType = { + Chat: "chat", + Text: "text" +}; +var ChatMessageType = { Chatmessage: "chatmessage" }; +var PlaceholderMessageType = { Placeholder: "placeholder" }; +var CreateChatPromptType = { Chat: "chat" }; +var CreateTextPromptType = { Text: "text" }; +var scores_exports = {}; +__export(scores_exports, { CreateScoreSource: () => CreateScoreSource }); +var unstable_exports = {}; +__export(unstable_exports, { + AccessDeniedError: () => AccessDeniedError2, + BadRequestError: () => BadRequestError2, + ConflictError: () => ConflictError2, + DashboardWidgetChartType: () => DashboardWidgetChartType, + DashboardWidgetMetricAggregation: () => DashboardWidgetMetricAggregation, + DashboardWidgetSortOrder: () => DashboardWidgetSortOrder, + DashboardWidgetView: () => DashboardWidgetView, + DashboardWidgetViewWithLegacy: () => DashboardWidgetViewWithLegacy, + InternalServerError: () => InternalServerError2, + MethodNotAllowedError: () => MethodNotAllowedError2, + NotFoundError: () => NotFoundError2, + PublicApiErrorCode: () => PublicApiErrorCode2, + TooManyRequestsError: () => TooManyRequestsError2, + UnauthorizedError: () => UnauthorizedError2, + dashboardWidgets: () => dashboardWidgets_exports, + dashboards: () => dashboards_exports, + errors: () => errors_exports2 +}); +var dashboardWidgets_exports = {}; +__export(dashboardWidgets_exports, { + DashboardWidgetChartType: () => DashboardWidgetChartType, + DashboardWidgetMetricAggregation: () => DashboardWidgetMetricAggregation, + DashboardWidgetSortOrder: () => DashboardWidgetSortOrder, + DashboardWidgetView: () => DashboardWidgetView, + DashboardWidgetViewWithLegacy: () => DashboardWidgetViewWithLegacy +}); +var DashboardWidgetView = { + Observations: "observations", + ScoresNumeric: "scores-numeric", + ScoresBoolean: "scores-boolean", + ScoresCategorical: "scores-categorical" +}; +var DashboardWidgetViewWithLegacy = { + Observations: "observations", + ScoresNumeric: "scores-numeric", + ScoresBoolean: "scores-boolean", + ScoresCategorical: "scores-categorical", + Traces: "traces" +}; +var DashboardWidgetChartType = { + LineTimeSeries: "LINE_TIME_SERIES", + AreaTimeSeries: "AREA_TIME_SERIES", + BarTimeSeries: "BAR_TIME_SERIES", + HorizontalBar: "HORIZONTAL_BAR", + VerticalBar: "VERTICAL_BAR", + Pie: "PIE", + Number: "NUMBER", + Histogram: "HISTOGRAM", + PivotTable: "PIVOT_TABLE" +}; +var DashboardWidgetMetricAggregation = { + Sum: "sum", + Avg: "avg", + Count: "count", + Max: "max", + Min: "min", + P50: "p50", + P75: "p75", + P90: "p90", + P95: "p95", + P99: "p99", + Histogram: "histogram", + Uniq: "uniq" +}; +var DashboardWidgetSortOrder = { + Asc: "ASC", + Desc: "DESC" +}; +var dashboards_exports = {}; +var errors_exports2 = {}; +__export(errors_exports2, { + AccessDeniedError: () => AccessDeniedError2, + BadRequestError: () => BadRequestError2, + ConflictError: () => ConflictError2, + InternalServerError: () => InternalServerError2, + MethodNotAllowedError: () => MethodNotAllowedError2, + NotFoundError: () => NotFoundError2, + PublicApiErrorCode: () => PublicApiErrorCode2, + TooManyRequestsError: () => TooManyRequestsError2, + UnauthorizedError: () => UnauthorizedError2 +}); +var PublicApiErrorCode2 = { + AuthenticationFailed: "authentication_failed", + AccessDenied: "access_denied", + InvalidRequest: "invalid_request", + InvalidQuery: "invalid_query", + InvalidBody: "invalid_body", + ResourceNotFound: "resource_not_found", + Conflict: "conflict", + RateLimited: "rate_limited", + MethodNotAllowed: "method_not_allowed", + InternalError: "internal_error" +}; +var BadRequestError2 = class _BadRequestError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "BadRequestError", + statusCode: 400, + body, + rawResponse + }); + Object.setPrototypeOf(this, _BadRequestError.prototype); + } +}; +var UnauthorizedError2 = class _UnauthorizedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "UnauthorizedError", + statusCode: 401, + body, + rawResponse + }); + Object.setPrototypeOf(this, _UnauthorizedError.prototype); + } +}; +var AccessDeniedError2 = class _AccessDeniedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "AccessDeniedError", + statusCode: 403, + body, + rawResponse + }); + Object.setPrototypeOf(this, _AccessDeniedError.prototype); + } +}; +var NotFoundError2 = class _NotFoundError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "NotFoundError", + statusCode: 404, + body, + rawResponse + }); + Object.setPrototypeOf(this, _NotFoundError.prototype); + } +}; +var MethodNotAllowedError2 = class _MethodNotAllowedError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "MethodNotAllowedError", + statusCode: 405, + body, + rawResponse + }); + Object.setPrototypeOf(this, _MethodNotAllowedError.prototype); + } +}; +var ConflictError2 = class _ConflictError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "ConflictError", + statusCode: 409, + body, + rawResponse + }); + Object.setPrototypeOf(this, _ConflictError.prototype); + } +}; +var TooManyRequestsError2 = class _TooManyRequestsError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "TooManyRequestsError", + statusCode: 429, + body, + rawResponse + }); + Object.setPrototypeOf(this, _TooManyRequestsError.prototype); + } +}; +var InternalServerError2 = class _InternalServerError extends LangfuseAPIError { + constructor(body, rawResponse) { + super({ + message: "InternalServerError", + statusCode: 500, + body, + rawResponse + }); + Object.setPrototypeOf(this, _InternalServerError.prototype); + } +}; +var utils_exports = {}; +__export(utils_exports, { pagination: () => pagination_exports }); +var pagination_exports = {}; +function mergeHeaders$1(...headersArray) { + const result = {}; + for (const [key, value] of headersArray.filter((headers) => headers != null).flatMap((headers) => Object.entries(headers))) if (value != null) result[key] = value; + else if (key in result) delete result[key]; + return result; +} +function mergeOnlyDefinedHeaders(...headersArray) { + const result = {}; + for (const [key, value] of headersArray.filter((headers) => headers != null).flatMap((headers) => Object.entries(headers))) if (value != null) result[key] = value; + return result; +} +var defaultQsOptions = { + arrayFormat: "indices", + encode: true +}; +function encodeValue(value, shouldEncode) { + if (value === void 0) return ""; + if (value === null) return ""; + const stringValue = String(value); + return shouldEncode ? encodeURIComponent(stringValue) : stringValue; +} +function stringifyObject(obj, prefix = "", options) { + const parts = []; + for (const [key, value] of Object.entries(obj)) { + const fullKey = prefix ? `${prefix}[${key}]` : key; + if (value === void 0) continue; + if (Array.isArray(value)) { + if (value.length === 0) continue; + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (item === void 0) continue; + if (typeof item === "object" && !Array.isArray(item) && item !== null) { + const arrayKey = options.arrayFormat === "indices" ? `${fullKey}[${i}]` : fullKey; + parts.push(...stringifyObject(item, arrayKey, options)); + } else { + const arrayKey = options.arrayFormat === "indices" ? `${fullKey}[${i}]` : fullKey; + const encodedKey = options.encode ? encodeURIComponent(arrayKey) : arrayKey; + parts.push(`${encodedKey}=${encodeValue(item, options.encode)}`); + } + } + } else if (typeof value === "object" && value !== null) { + if (Object.keys(value).length === 0) continue; + parts.push(...stringifyObject(value, fullKey, options)); + } else { + const encodedKey = options.encode ? encodeURIComponent(fullKey) : fullKey; + parts.push(`${encodedKey}=${encodeValue(value, options.encode)}`); + } + } + return parts; +} +function toQueryString(obj, options) { + if (obj == null || typeof obj !== "object") return ""; + return stringifyObject(obj, "", { + ...defaultQsOptions, + ...options + }).join("&"); +} +function createRequestUrl(baseUrl, queryParameters) { + const queryString = toQueryString(queryParameters, { arrayFormat: "repeat" }); + return queryString ? `${baseUrl}?${queryString}` : baseUrl; +} +function getBinaryResponse(response) { + const binaryResponse = { + get bodyUsed() { + return response.bodyUsed; + }, + stream: () => response.body, + arrayBuffer: response.arrayBuffer.bind(response), + blob: response.blob.bind(response) + }; + if ("bytes" in response && typeof response.bytes === "function") binaryResponse.bytes = response.bytes.bind(response); + return binaryResponse; +} +function isResponseWithBody(response) { + return response.body != null; +} +async function getResponseBody(response, responseType) { + if (!isResponseWithBody(response)) return; + switch (responseType) { + case "binary-response": return getBinaryResponse(response); + case "blob": return await response.blob(); + case "arrayBuffer": return await response.arrayBuffer(); + case "sse": return response.body; + case "streaming": return response.body; + case "text": return await response.text(); + } + const text = await response.text(); + if (text.length > 0) try { + return fromJson(text); + } catch (err) { + return { + ok: false, + error: { + reason: "non-json", + statusCode: response.status, + rawBody: text + } + }; + } +} +async function getErrorResponseBody(response) { + var _a2, _b, _c; + let contentType = (_a2 = response.headers.get("Content-Type")) == null ? void 0 : _a2.toLowerCase(); + if (contentType == null || contentType.length === 0) return getResponseBody(response); + if (contentType.indexOf(";") !== -1) contentType = (_c = (_b = contentType.split(";")[0]) == null ? void 0 : _b.trim()) != null ? _c : ""; + switch (contentType) { + case "application/hal+json": + case "application/json": + case "application/ld+json": + case "application/problem+json": + case "application/vnd.api+json": + case "text/json": + const text = await response.text(); + return text.length > 0 ? fromJson(text) : void 0; + default: + if (contentType.startsWith("application/vnd.") && contentType.endsWith("+json")) { + const text2 = await response.text(); + return text2.length > 0 ? fromJson(text2) : void 0; + } + return await response.text(); + } +} +async function getFetchFn() { + return fetch; +} +async function getRequestBody({ body, type }) { + if (type.includes("json")) return toJson(body); + else return body; +} +var TIMEOUT = "timeout"; +function getTimeoutSignal(timeoutMs) { + const controller = new AbortController(); + const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs); + return { + signal: controller.signal, + abortId + }; +} +function anySignal(...args) { + const signals = args.length === 1 && Array.isArray(args[0]) ? args[0] : args; + const controller = new AbortController(); + for (const signal of signals) { + if (signal.aborted) { + controller.abort(signal == null ? void 0 : signal.reason); + break; + } + signal.addEventListener("abort", () => controller.abort(signal == null ? void 0 : signal.reason), { signal: controller.signal }); + } + return controller.signal; +} +var makeRequest = async (fetchFn, url, method, headers, requestBody, timeoutMs, abortSignal, withCredentials, duplex) => { + const signals = []; + let timeoutAbortId = void 0; + if (timeoutMs != null) { + const { signal, abortId } = getTimeoutSignal(timeoutMs); + timeoutAbortId = abortId; + signals.push(signal); + } + if (abortSignal != null) signals.push(abortSignal); + const response = await fetchFn(url, { + method, + headers, + body: requestBody, + signal: anySignal(signals), + credentials: withCredentials ? "include" : void 0, + duplex + }); + if (timeoutAbortId != null) clearTimeout(timeoutAbortId); + return response; +}; +var Headers; +if (typeof globalThis.Headers !== "undefined") Headers = globalThis.Headers; +else Headers = class Headers2 { + constructor(init) { + this.headers = /* @__PURE__ */ new Map(); + if (init) { + if (init instanceof Headers2) init.forEach((value, key) => this.append(key, value)); + else if (Array.isArray(init)) for (const [key, value] of init) if (typeof key === "string" && typeof value === "string") this.append(key, value); + else throw new TypeError("Each header entry must be a [string, string] tuple"); + else for (const [key, value] of Object.entries(init)) if (typeof value === "string") this.append(key, value); + else throw new TypeError("Header values must be strings"); + } + } + append(name, value) { + const key = name.toLowerCase(); + const existing = this.headers.get(key) || []; + this.headers.set(key, [...existing, value]); + } + delete(name) { + const key = name.toLowerCase(); + this.headers.delete(key); + } + get(name) { + const key = name.toLowerCase(); + const values = this.headers.get(key); + return values ? values.join(", ") : null; + } + has(name) { + const key = name.toLowerCase(); + return this.headers.has(key); + } + set(name, value) { + const key = name.toLowerCase(); + this.headers.set(key, [value]); + } + forEach(callbackfn, thisArg) { + const boundCallback = thisArg ? callbackfn.bind(thisArg) : callbackfn; + this.headers.forEach((values, key) => boundCallback(values.join(", "), key, this)); + } + getSetCookie() { + return this.headers.get("set-cookie") || []; + } + *entries() { + for (const [key, values] of this.headers.entries()) yield [key, values.join(", ")]; + } + *keys() { + yield* this.headers.keys(); + } + *values() { + for (const values of this.headers.values()) yield values.join(", "); + } + [Symbol.iterator]() { + return this.entries(); + } +}; +var abortRawResponse = { + headers: new Headers(), + redirected: false, + status: 499, + statusText: "Client Closed Request", + type: "error", + url: "" +}; +var unknownRawResponse = { + headers: new Headers(), + redirected: false, + status: 0, + statusText: "Unknown Error", + type: "error", + url: "" +}; +function toRawResponse(response) { + return { + headers: response.headers, + redirected: response.redirected, + status: response.status, + statusText: response.statusText, + type: response.type, + url: response.url + }; +} +var INITIAL_RETRY_DELAY = 1e3; +var MAX_RETRY_DELAY = 6e4; +var DEFAULT_MAX_RETRIES = 2; +var JITTER_FACTOR = .2; +function addPositiveJitter(delay) { + return delay * (1 + Math.random() * JITTER_FACTOR); +} +function addSymmetricJitter(delay) { + return delay * (1 + (Math.random() - .5) * JITTER_FACTOR); +} +function getRetryDelayFromHeaders(response, retryAttempt) { + const retryAfter = response.headers.get("Retry-After"); + if (retryAfter) { + const retryAfterSeconds = parseInt(retryAfter, 10); + if (!isNaN(retryAfterSeconds) && retryAfterSeconds > 0) return Math.min(retryAfterSeconds * 1e3, MAX_RETRY_DELAY); + const retryAfterDate = new Date(retryAfter); + if (!isNaN(retryAfterDate.getTime())) { + const delay = retryAfterDate.getTime() - Date.now(); + if (delay > 0) return Math.min(Math.max(delay, 0), MAX_RETRY_DELAY); + } + } + const rateLimitReset = response.headers.get("X-RateLimit-Reset"); + if (rateLimitReset) { + const resetTime = parseInt(rateLimitReset, 10); + if (!isNaN(resetTime)) { + const delay = resetTime * 1e3 - Date.now(); + if (delay > 0) return addPositiveJitter(Math.min(delay, MAX_RETRY_DELAY)); + } + } + return addSymmetricJitter(Math.min(INITIAL_RETRY_DELAY * Math.pow(2, retryAttempt), MAX_RETRY_DELAY)); +} +async function requestWithRetries(requestFn, maxRetries = DEFAULT_MAX_RETRIES) { + let response = await requestFn(); + for (let i = 0; i < maxRetries; ++i) if ([408, 429].includes(response.status) || response.status >= 500) { + const delay = getRetryDelayFromHeaders(response, i); + await new Promise((resolve) => setTimeout(resolve, delay)); + response = await requestFn(); + } else break; + return response; +} +var Supplier = { get: async (supplier) => { + if (typeof supplier === "function") return supplier(); + else return supplier; +} }; +async function getHeaders(args) { + const newHeaders = {}; + if (args.body !== void 0 && args.contentType != null) newHeaders["Content-Type"] = args.contentType; + if (args.headers == null) return newHeaders; + for (const [key, value] of Object.entries(args.headers)) { + const result = await Supplier.get(value); + if (typeof result === "string") { + newHeaders[key] = result; + continue; + } + if (result == null) continue; + newHeaders[key] = `${result}`; + } + return newHeaders; +} +async function fetcherImpl(args) { + const url = createRequestUrl(args.url, args.queryParameters); + const requestBody = await getRequestBody({ + body: args.body, + type: args.requestType === "json" ? "json" : "other" + }); + const fetchFn = await getFetchFn(); + try { + const response = await requestWithRetries(async () => makeRequest(fetchFn, url, args.method, await getHeaders(args), requestBody, args.timeoutMs, args.abortSignal, args.withCredentials, args.duplex), args.maxRetries); + if (response.status >= 200 && response.status < 400) return { + ok: true, + body: await getResponseBody(response, args.responseType), + headers: response.headers, + rawResponse: toRawResponse(response) + }; + else return { + ok: false, + error: { + reason: "status-code", + statusCode: response.status, + body: await getErrorResponseBody(response) + }, + rawResponse: toRawResponse(response) + }; + } catch (error) { + if (args.abortSignal != null && args.abortSignal.aborted) return { + ok: false, + error: { + reason: "unknown", + errorMessage: "The user aborted a request" + }, + rawResponse: abortRawResponse + }; + else if (error instanceof Error && error.name === "AbortError") return { + ok: false, + error: { reason: "timeout" }, + rawResponse: abortRawResponse + }; + else if (error instanceof Error) return { + ok: false, + error: { + reason: "unknown", + errorMessage: error.message + }, + rawResponse: unknownRawResponse + }; + return { + ok: false, + error: { + reason: "unknown", + errorMessage: toJson(error) + }, + rawResponse: unknownRawResponse + }; + } +} +var fetcher = fetcherImpl; +var HttpResponsePromise = class _HttpResponsePromise extends Promise { + constructor(promise) { + super((resolve) => { + resolve(void 0); + }); + this.innerPromise = promise; + } + /** + * Creates an `HttpResponsePromise` from a function that returns a promise. + * + * @param fn - A function that returns a promise resolving to a `WithRawResponse` object. + * @param args - Arguments to pass to the function. + * @returns An `HttpResponsePromise` instance. + */ + static fromFunction(fn, ...args) { + return new _HttpResponsePromise(fn(...args)); + } + /** + * Creates a function that returns an `HttpResponsePromise` from a function that returns a promise. + * + * @param fn - A function that returns a promise resolving to a `WithRawResponse` object. + * @returns A function that returns an `HttpResponsePromise` instance. + */ + static interceptFunction(fn) { + return (...args) => { + return _HttpResponsePromise.fromPromise(fn(...args)); + }; + } + /** + * Creates an `HttpResponsePromise` from an existing promise. + * + * @param promise - A promise resolving to a `WithRawResponse` object. + * @returns An `HttpResponsePromise` instance. + */ + static fromPromise(promise) { + return new _HttpResponsePromise(promise); + } + /** + * Creates an `HttpResponsePromise` from an executor function. + * + * @param executor - A function that takes resolve and reject callbacks to create a promise. + * @returns An `HttpResponsePromise` instance. + */ + static fromExecutor(executor) { + const promise = new Promise(executor); + return new _HttpResponsePromise(promise); + } + /** + * Creates an `HttpResponsePromise` from a resolved result. + * + * @param result - A `WithRawResponse` object to resolve immediately. + * @returns An `HttpResponsePromise` instance. + */ + static fromResult(result) { + const promise = Promise.resolve(result); + return new _HttpResponsePromise(promise); + } + unwrap() { + if (!this.unwrappedPromise) this.unwrappedPromise = this.innerPromise.then(({ data }) => data); + return this.unwrappedPromise; + } + /** @inheritdoc */ + then(onfulfilled, onrejected) { + return this.unwrap().then(onfulfilled, onrejected); + } + /** @inheritdoc */ + catch(onrejected) { + return this.unwrap().catch(onrejected); + } + /** @inheritdoc */ + finally(onfinally) { + return this.unwrap().finally(onfinally); + } + /** + * Retrieves the data and raw response. + * + * @returns A promise resolving to a `WithRawResponse` object. + */ + async withRawResponse() { + return await this.innerPromise; + } +}; +var url_exports = {}; +__export(url_exports, { + join: () => join, + toQueryString: () => toQueryString +}); +function join(base, ...segments) { + if (!base) return ""; + if (segments.length === 0) return base; + if (base.includes("://")) { + let url; + try { + url = new URL(base); + } catch { + return joinPath(base, ...segments); + } + const lastSegment = segments[segments.length - 1]; + const shouldPreserveTrailingSlash = lastSegment && lastSegment.endsWith("/"); + for (const segment of segments) { + const cleanSegment = trimSlashes(segment); + if (cleanSegment) url.pathname = joinPathSegments(url.pathname, cleanSegment); + } + if (shouldPreserveTrailingSlash && !url.pathname.endsWith("/")) url.pathname += "/"; + return url.toString(); + } + return joinPath(base, ...segments); +} +function joinPath(base, ...segments) { + if (segments.length === 0) return base; + let result = base; + const lastSegment = segments[segments.length - 1]; + const shouldPreserveTrailingSlash = lastSegment && lastSegment.endsWith("/"); + for (const segment of segments) { + const cleanSegment = trimSlashes(segment); + if (cleanSegment) result = joinPathSegments(result, cleanSegment); + } + if (shouldPreserveTrailingSlash && !result.endsWith("/")) result += "/"; + return result; +} +function joinPathSegments(left, right) { + if (left.endsWith("/")) return left + right; + return left + "/" + right; +} +function trimSlashes(str) { + if (!str) return str; + let start = 0; + let end = str.length; + if (str.startsWith("/")) start = 1; + if (str.endsWith("/")) end = str.length - 1; + return start === 0 && end === str.length ? str : str.slice(start, end); +} +function base64ToBytes2(base64) { + const binString = atob(base64); + return Uint8Array.from(binString, (m) => m.codePointAt(0)); +} +function bytesToBase642(bytes) { + const binString = String.fromCodePoint(...bytes); + return btoa(binString); +} +function base64Encode2(input) { + if (typeof Buffer !== "undefined") return Buffer.from(input, "utf8").toString("base64"); + return bytesToBase642(new TextEncoder().encode(input)); +} +function base64Decode2(input) { + if (typeof Buffer !== "undefined") return Buffer.from(input, "base64").toString("utf8"); + const bytes = base64ToBytes2(input); + return new TextDecoder().decode(bytes); +} +var BASIC_AUTH_HEADER_PREFIX = /^Basic /i; +var BasicAuth = { + toAuthorizationHeader: (basicAuth) => { + if (basicAuth == null) return; + return `Basic ${base64Encode2(`${basicAuth.username}:${basicAuth.password}`)}`; + }, + fromAuthorizationHeader: (header) => { + const [username, password] = base64Decode2(header.replace(BASIC_AUTH_HEADER_PREFIX, "")).split(":", 2); + if (username == null || password == null) throw new Error("Invalid basic auth"); + return { + username, + password + }; + } +}; +var AnnotationQueues = class { + constructor(_options) { + this._options = _options; + } + /** + * Get all annotation queues + * + * @param {LangfuseAPI.GetAnnotationQueuesRequest} request + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.listQueues() + */ + listQueues(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__listQueues(request, requestOptions)); + } + async __listQueues(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/annotation-queues"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/annotation-queues."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create an annotation queue + * + * @param {LangfuseAPI.CreateAnnotationQueueRequest} request + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.createQueue({ + * name: "name", + * description: undefined, + * scoreConfigIds: ["scoreConfigIds", "scoreConfigIds"] + * }) + */ + createQueue(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__createQueue(request, requestOptions)); + } + async __createQueue(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/annotation-queues"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/annotation-queues."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get an annotation queue by ID + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.getQueue("queueId") + */ + getQueue(queueId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getQueue(queueId, requestOptions)); + } + async __getQueue(queueId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/annotation-queues/{queueId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get items for a specific annotation queue + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {LangfuseAPI.GetAnnotationQueueItemsRequest} request + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.listQueueItems("queueId") + */ + listQueueItems(queueId, request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__listQueueItems(queueId, request, requestOptions)); + } + async __listQueueItems(queueId, request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { status, page, limit } = request; + const _queryParams = {}; + if (status != null) _queryParams["status"] = status; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}/items`), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/annotation-queues/{queueId}/items."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a specific item from an annotation queue + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {string} itemId - The unique identifier of the annotation queue item + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.getQueueItem("queueId", "itemId") + */ + getQueueItem(queueId, itemId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getQueueItem(queueId, itemId, requestOptions)); + } + async __getQueueItem(queueId, itemId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}/items/${encodeURIComponent(itemId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/annotation-queues/{queueId}/items/{itemId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Add an item to an annotation queue + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {LangfuseAPI.CreateAnnotationQueueItemRequest} request + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.createQueueItem("queueId", { + * objectId: "objectId", + * objectType: "TRACE", + * status: undefined + * }) + */ + createQueueItem(queueId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__createQueueItem(queueId, request, requestOptions)); + } + async __createQueueItem(queueId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}/items`), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/annotation-queues/{queueId}/items."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Update an annotation queue item + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {string} itemId - The unique identifier of the annotation queue item + * @param {LangfuseAPI.UpdateAnnotationQueueItemRequest} request + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.updateQueueItem("queueId", "itemId", { + * status: undefined + * }) + */ + updateQueueItem(queueId, itemId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__updateQueueItem(queueId, itemId, request, requestOptions)); + } + async __updateQueueItem(queueId, itemId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}/items/${encodeURIComponent(itemId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/annotation-queues/{queueId}/items/{itemId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Remove an item from an annotation queue + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {string} itemId - The unique identifier of the annotation queue item + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.deleteQueueItem("queueId", "itemId") + */ + deleteQueueItem(queueId, itemId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteQueueItem(queueId, itemId, requestOptions)); + } + async __deleteQueueItem(queueId, itemId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}/items/${encodeURIComponent(itemId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/annotation-queues/{queueId}/items/{itemId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create an assignment for a user to an annotation queue + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {LangfuseAPI.AnnotationQueueAssignmentRequest} request + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.createQueueAssignment("queueId", { + * userId: "userId" + * }) + */ + createQueueAssignment(queueId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__createQueueAssignment(queueId, request, requestOptions)); + } + async __createQueueAssignment(queueId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}/assignments`), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/annotation-queues/{queueId}/assignments."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete an assignment for a user to an annotation queue + * + * @param {string} queueId - The unique identifier of the annotation queue + * @param {LangfuseAPI.AnnotationQueueAssignmentRequest} request + * @param {AnnotationQueues.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.annotationQueues.deleteQueueAssignment("queueId", { + * userId: "userId" + * }) + */ + deleteQueueAssignment(queueId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteQueueAssignment(queueId, request, requestOptions)); + } + async __deleteQueueAssignment(queueId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/annotation-queues/${encodeURIComponent(queueId)}/assignments`), + method: "DELETE", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/annotation-queues/{queueId}/assignments."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var BlobStorageIntegrations = class { + constructor(_options) { + this._options = _options; + } + /** + * Get all blob storage integrations for the organization (requires organization-scoped API key) + * + * @param {BlobStorageIntegrations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.blobStorageIntegrations.getBlobStorageIntegrations() + */ + getBlobStorageIntegrations(requestOptions) { + return HttpResponsePromise.fromPromise(this.__getBlobStorageIntegrations(requestOptions)); + } + async __getBlobStorageIntegrations(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/integrations/blob-storage"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/integrations/blob-storage."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket. + * + * @param {LangfuseAPI.CreateBlobStorageIntegrationRequest} request + * @param {BlobStorageIntegrations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.blobStorageIntegrations.upsertBlobStorageIntegration({ + * projectId: "projectId", + * type: "S3", + * bucketName: "bucketName", + * endpoint: undefined, + * region: "region", + * accessKeyId: undefined, + * secretAccessKey: undefined, + * prefix: undefined, + * exportFrequency: "every_20_minutes", + * enabled: true, + * forcePathStyle: true, + * fileType: "JSON", + * exportMode: "FULL_HISTORY", + * exportStartDate: undefined, + * compressed: undefined, + * exportSource: undefined, + * exportFieldGroups: undefined + * }) + */ + upsertBlobStorageIntegration(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__upsertBlobStorageIntegration(request, requestOptions)); + } + async __upsertBlobStorageIntegration(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/integrations/blob-storage"), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PUT /api/public/integrations/blob-storage."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get the sync status of a blob storage integration by integration ID (requires organization-scoped API key) + * + * @param {string} id + * @param {BlobStorageIntegrations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.blobStorageIntegrations.getBlobStorageIntegrationStatus("id") + */ + getBlobStorageIntegrationStatus(id, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getBlobStorageIntegrationStatus(id, requestOptions)); + } + async __getBlobStorageIntegrationStatus(id, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/integrations/blob-storage/${encodeURIComponent(id)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/integrations/blob-storage/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a blob storage integration by ID (requires organization-scoped API key) + * + * @param {string} id + * @param {BlobStorageIntegrations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.blobStorageIntegrations.deleteBlobStorageIntegration("id") + */ + deleteBlobStorageIntegration(id, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteBlobStorageIntegration(id, requestOptions)); + } + async __deleteBlobStorageIntegration(id, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/integrations/blob-storage/${encodeURIComponent(id)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/integrations/blob-storage/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Comments = class { + constructor(_options) { + this._options = _options; + } + /** + * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). + * + * @param {LangfuseAPI.CreateCommentRequest} request + * @param {Comments.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.comments.create({ + * projectId: "projectId", + * objectType: "objectType", + * objectId: "objectId", + * content: "content", + * authorUserId: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/comments"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/comments."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get all comments + * + * @param {LangfuseAPI.GetCommentsRequest} request + * @param {Comments.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.comments.get() + */ + get(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + async __get(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit, objectType, objectId, authorUserId } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + if (objectType != null) _queryParams["objectType"] = objectType; + if (objectId != null) _queryParams["objectId"] = objectId; + if (authorUserId != null) _queryParams["authorUserId"] = authorUserId; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/comments"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/comments."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a comment by id + * + * @param {string} commentId - The unique langfuse identifier of a comment + * @param {Comments.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.comments.getById("commentId") + */ + getById(commentId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getById(commentId, requestOptions)); + } + async __getById(commentId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/comments/${encodeURIComponent(commentId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/comments/{commentId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var DatasetItems = class { + constructor(_options) { + this._options = _options; + } + /** + * Create a dataset item + * + * @param {LangfuseAPI.CreateDatasetItemRequest} request + * @param {DatasetItems.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasetItems.create({ + * datasetName: "datasetName", + * input: undefined, + * expectedOutput: undefined, + * metadata: undefined, + * sourceTraceId: undefined, + * sourceObservationId: undefined, + * id: undefined, + * status: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/dataset-items"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/dataset-items."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a dataset item + * + * @param {string} id + * @param {DatasetItems.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasetItems.get("id") + */ + get(id, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(id, requestOptions)); + } + async __get(id, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/dataset-items/${encodeURIComponent(id)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/dataset-items/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + * + * @param {LangfuseAPI.GetDatasetItemsRequest} request + * @param {DatasetItems.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasetItems.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { datasetName, sourceTraceId, sourceObservationId, version, page, limit } = request; + const _queryParams = {}; + if (datasetName != null) _queryParams["datasetName"] = datasetName; + if (sourceTraceId != null) _queryParams["sourceTraceId"] = sourceTraceId; + if (sourceObservationId != null) _queryParams["sourceObservationId"] = sourceObservationId; + if (version != null) _queryParams["version"] = version; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/dataset-items"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/dataset-items."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a dataset item and all its run items. This action is irreversible. + * + * @param {string} id + * @param {DatasetItems.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasetItems.delete("id") + */ + delete(id, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(id, requestOptions)); + } + async __delete(id, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/dataset-items/${encodeURIComponent(id)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/dataset-items/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var DatasetRunItems = class { + constructor(_options) { + this._options = _options; + } + /** + * Create a dataset run item + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, create experiment data via the SDK experiment runner or the OpenTelemetry endpoint at POST /api/public/otel/v1/traces. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.CreateDatasetRunItemRequest} request + * @param {DatasetRunItems.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasetRunItems.create({ + * runName: "runName", + * runDescription: undefined, + * metadata: undefined, + * datasetItemId: "datasetItemId", + * observationId: undefined, + * traceId: undefined, + * datasetVersion: undefined, + * createdAt: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/dataset-run-items"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/dataset-run-items."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * List dataset run items + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, dataset run items are replaced by experiment items; use `GET /api/public/experiment-items?fromStartTime=&toStartTime=` instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.ListDatasetRunItemsRequest} request + * @param {DatasetRunItems.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasetRunItems.list({ + * datasetId: "datasetId", + * runName: "runName" + * }) + */ + list(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { datasetId, runName, page, limit } = request; + const _queryParams = {}; + _queryParams["datasetId"] = datasetId; + _queryParams["runName"] = runName; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/dataset-run-items"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/dataset-run-items."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Datasets = class { + constructor(_options) { + this._options = _options; + } + /** + * Get all datasets + * + * @param {LangfuseAPI.GetDatasetsRequest} request + * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasets.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/datasets"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/datasets."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a dataset + * + * @param {string} datasetName + * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasets.get("datasetName") + */ + get(datasetName, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(datasetName, requestOptions)); + } + async __get(datasetName, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/datasets/${encodeURIComponent(datasetName)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/datasets/{datasetName}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create a dataset + * + * @param {LangfuseAPI.CreateDatasetRequest} request + * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasets.create({ + * name: "name", + * description: undefined, + * metadata: undefined, + * inputSchema: undefined, + * expectedOutputSchema: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/datasets"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/v2/datasets."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a dataset run and its items + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, dataset runs are replaced by experiments; use GET /api/public/experiments instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {string} datasetName + * @param {string} runName + * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasets.getRun("datasetName", "runName") + */ + getRun(datasetName, runName, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getRun(datasetName, runName, requestOptions)); + } + async __getRun(datasetName, runName, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/datasets/${encodeURIComponent(datasetName)}/runs/${encodeURIComponent(runName)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/datasets/{datasetName}/runs/{runName}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a dataset run and all its run items. This action is irreversible. + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, dataset runs are replaced by experiments. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {string} datasetName + * @param {string} runName + * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasets.deleteRun("datasetName", "runName") + */ + deleteRun(datasetName, runName, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteRun(datasetName, runName, requestOptions)); + } + async __deleteRun(datasetName, runName, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/datasets/${encodeURIComponent(datasetName)}/runs/${encodeURIComponent(runName)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/datasets/{datasetName}/runs/{runName}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get dataset runs + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, dataset runs are replaced by experiments; use GET /api/public/experiments instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {string} datasetName + * @param {LangfuseAPI.GetDatasetRunsRequest} request + * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.datasets.getRuns("datasetName") + */ + getRuns(datasetName, request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getRuns(datasetName, request, requestOptions)); + } + async __getRuns(datasetName, request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/datasets/${encodeURIComponent(datasetName)}/runs`), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/datasets/{datasetName}/runs."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var EvaluationRules = class { + constructor(_options) { + this._options = _options; + } + /** + * Create an evaluation rule using stable evaluator identifiers. + * + * An evaluation rule defines **which** incoming observations should be evaluated and how prompt variables should be populated. + * + * Key behavior: + * - rule names are not identifiers and do not need to be unique + * - rules always use the latest version of each associated evaluator + * - an enabled rule requires at least one evaluator assignment + * - omit `sampling` to evaluate every matching observation + * - omit `filter` to match every incoming observation + * - `datasetId` is the public filter name for selecting experiment datasets + * + * @param {LangfuseAPI.CreateEvaluationRuleRequest} request + * @param {EvaluationRules.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.BadRequestError} + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.ConflictError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluationRules.create({ + * name: "name", + * enabled: true, + * sampling: undefined, + * filter: undefined, + * evaluatorAssignments: [{ + * evaluatorId: "evaluatorId", + * variableMapping: undefined + * }, { + * evaluatorId: "evaluatorId", + * variableMapping: undefined + * }] + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/evaluation-rules"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 409: throw new ConflictError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/v2/evaluation-rules."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * List evaluation rules in newest-first creation order. + * + * This includes legacy trace and dataset rules so they can be inspected and migrated. Treat the cursor as opaque and return it unchanged. + * + * @param {LangfuseAPI.ListEvaluationRulesRequest} request + * @param {EvaluationRules.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.BadRequestError} + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluationRules.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { limit, cursor } = request; + const _queryParams = {}; + if (limit != null) _queryParams["limit"] = limit.toString(); + if (cursor != null) _queryParams["cursor"] = cursor; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/evaluation-rules"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/evaluation-rules."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get one evaluation rule, including a legacy trace or dataset rule, by its stable identifier. + * + * @param {string} evaluationRuleId - Stable evaluation-rule identifier returned by the evaluation-rule endpoints. + * @param {EvaluationRules.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluationRules.get("evaluationRuleId") + */ + get(evaluationRuleId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(evaluationRuleId, requestOptions)); + } + async __get(evaluationRuleId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/evaluation-rules/${encodeURIComponent(evaluationRuleId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/evaluation-rules/{evaluationRuleId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Update an evaluation rule by its stable identifier. + * + * Provide only the fields to change. Providing `evaluatorAssignments` replaces the complete assignment list. Replacing the list with an empty array disables the rule. Setting `enabled=true` is rejected when the resulting assignment list is empty, including when both fields are sent in the same request. + * + * Legacy trace and dataset rules follow the existing lifecycle restrictions: they can be deactivated with `enabled=false`, but their name, filters, sampling, and evaluator assignments cannot be changed. + * + * @param {string} evaluationRuleId - Stable evaluation-rule identifier returned by the evaluation-rule endpoints. + * @param {LangfuseAPI.UpdateEvaluationRuleRequest} request + * @param {EvaluationRules.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.BadRequestError} + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.ConflictError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluationRules.update("evaluationRuleId", { + * name: undefined, + * enabled: undefined, + * sampling: undefined, + * filter: undefined, + * evaluatorAssignments: undefined + * }) + */ + update(evaluationRuleId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__update(evaluationRuleId, request, requestOptions)); + } + async __update(evaluationRuleId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/evaluation-rules/${encodeURIComponent(evaluationRuleId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 409: throw new ConflictError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/v2/evaluation-rules/{evaluationRuleId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete an evaluation rule. + * + * This removes the live-ingestion rule only. It does not delete associated evaluators or scores already produced by them. + * + * Legacy trace and dataset rules can also be deleted. Their evaluators and previously produced scores are preserved. + * + * @param {string} evaluationRuleId - Stable evaluation-rule identifier returned by the evaluation-rule endpoints. + * @param {EvaluationRules.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluationRules.delete("evaluationRuleId") + */ + delete(evaluationRuleId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(evaluationRuleId, requestOptions)); + } + async __delete(evaluationRuleId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/evaluation-rules/${encodeURIComponent(evaluationRuleId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/v2/evaluation-rules/{evaluationRuleId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Evaluators = class { + constructor(_options) { + this._options = _options; + } + /** + * Create an evaluator in the authenticated project. + * + * An evaluator defines **how** Langfuse should score data. LLM-as-a-judge evaluators define a prompt, expected structured output, and optional model configuration. Code evaluators define source code and a runtime language. + * + * This always creates a new evaluator with version `1`. Names are not identifiers and do not need to be unique. + * + * @param {LangfuseAPI.CreateEvaluatorRequest} request + * @param {Evaluators.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.BadRequestError} + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.PreconditionFailedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluators.create({ + * type: "llm_as_judge", + * name: "name", + * description: undefined, + * type: "llm_as_judge", + * prompt: "prompt", + * modelConfig: undefined, + * variableMapping: undefined, + * outputDefinition: { + * dataType: "NUMERIC", + * dataType: "NUMERIC", + * minValue: undefined, + * maxValue: undefined, + * scoreReasoningInstructions: undefined, + * scoreValueInstructions: undefined + * } + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/evaluators"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 412: throw new PreconditionFailedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/v2/evaluators."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * List evaluators in newest-first creation order. + * + * Every evaluator includes its latest definition and version metadata flattened into the evaluator object, plus associated evaluation rules. Treat the cursor as opaque and return it unchanged. + * + * @param {LangfuseAPI.ListEvaluatorsRequest} request + * @param {Evaluators.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.BadRequestError} + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluators.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { limit, cursor } = request; + const _queryParams = {}; + if (limit != null) _queryParams["limit"] = limit.toString(); + if (cursor != null) _queryParams["cursor"] = cursor; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/evaluators"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/evaluators."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get one evaluator by its stable identifier. + * + * The response includes the evaluator's latest definition and version metadata flattened into the evaluator object, plus associated evaluation rules. Use the version-history endpoint when older definitions are needed. + * + * @param {string} evaluatorId - Stable evaluator identifier returned by the evaluator endpoints. + * @param {Evaluators.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluators.get("evaluatorId") + */ + get(evaluatorId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(evaluatorId, requestOptions)); + } + async __get(evaluatorId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/evaluators/${encodeURIComponent(evaluatorId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/evaluators/{evaluatorId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Update an evaluator by its stable identifier. + * + * Provide only the top-level fields to change. Metadata-only changes do not create a version. Evaluator type cannot change. + * + * Definition fields are flattened into the request. To replace a definition, include `type` and every definition field for that type. Definition fields are replaced as a complete unit rather than merged. For LLM-as-a-judge evaluators, omitting or setting `modelConfig` to `null` selects the project's default evaluation model. + * + * Replacing a definition automatically returns an evaluator paused by an invalid or missing model configuration to `active`, while preserving its id and evaluation-rule assignments. Pauses caused by provider authentication, billing, connectivity, account state, or an unknown legacy reason remain paused until the explicit reactivation check succeeds. + * + * @param {string} evaluatorId - Stable evaluator identifier returned by the evaluator endpoints. + * @param {LangfuseAPI.UpdateEvaluatorRequest} request + * @param {Evaluators.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.BadRequestError} + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.ConflictError} + * @throws {@link LangfuseAPI.PreconditionFailedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluators.update("evaluatorId", { + * name: undefined, + * description: undefined + * }) + */ + update(evaluatorId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__update(evaluatorId, request, requestOptions)); + } + async __update(evaluatorId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/evaluators/${encodeURIComponent(evaluatorId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 409: throw new ConflictError(_response.error.body, _response.rawResponse); + case 412: throw new PreconditionFailedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/v2/evaluators/{evaluatorId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete an evaluator and all of its stored versions. + * + * Associated evaluation-rule assignments are also removed. Scores already produced by the evaluator are preserved. + * + * @param {string} evaluatorId - Stable evaluator identifier returned by the evaluator endpoints. + * @param {Evaluators.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluators.delete("evaluatorId") + */ + delete(evaluatorId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(evaluatorId, requestOptions)); + } + async __delete(evaluatorId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/evaluators/${encodeURIComponent(evaluatorId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/v2/evaluators/{evaluatorId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * List an evaluator's version history in newest-first order. + * + * This endpoint is intended for history and audit use cases. Ordinary clients can use the flattened `version` and definition fields on the evaluator response. + * + * @param {string} evaluatorId - Stable evaluator identifier returned by the evaluator endpoints. + * @param {LangfuseAPI.ListEvaluatorVersionsRequest} request + * @param {Evaluators.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.BadRequestError} + * @throws {@link LangfuseAPI.EvaluationUnauthorizedError} + * @throws {@link LangfuseAPI.EvaluationAccessDeniedError} + * @throws {@link LangfuseAPI.EvaluationNotFoundError} + * @throws {@link LangfuseAPI.EvaluationMethodNotAllowedError} + * @throws {@link LangfuseAPI.TooManyRequestsError} + * @throws {@link LangfuseAPI.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.evaluators.listVersions("evaluatorId") + */ + listVersions(evaluatorId, request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__listVersions(evaluatorId, request, requestOptions)); + } + async __listVersions(evaluatorId, request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { limit, cursor } = request; + const _queryParams = {}; + if (limit != null) _queryParams["limit"] = limit.toString(); + if (cursor != null) _queryParams["cursor"] = cursor; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/evaluators/${encodeURIComponent(evaluatorId)}/versions`), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new EvaluationUnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new EvaluationAccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new EvaluationNotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new EvaluationMethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/evaluators/{evaluatorId}/versions."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Experiments = class { + constructor(_options) { + this._options = _options; + } + /** + * List experiments with cursor-based pagination. Results are ordered by + * latest experiment activity descending. + * + * @param {LangfuseAPI.ListExperimentsRequest} request + * @param {Experiments.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.experiments.list({ + * fromStartTime: "2024-01-15T09:30:00Z" + * }) + */ + list(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { fields, limit, scoreLimit, cursor, fromStartTime, toStartTime, id, name, datasetId, filter } = request; + const _queryParams = {}; + if (fields != null) _queryParams["fields"] = fields; + if (limit != null) _queryParams["limit"] = limit.toString(); + if (scoreLimit != null) _queryParams["scoreLimit"] = scoreLimit.toString(); + if (cursor != null) _queryParams["cursor"] = cursor; + _queryParams["fromStartTime"] = fromStartTime; + if (toStartTime != null) _queryParams["toStartTime"] = toStartTime; + if (id != null) _queryParams["id"] = id; + if (name != null) _queryParams["name"] = name; + if (datasetId != null) _queryParams["datasetId"] = datasetId; + if (filter != null) _queryParams["filter"] = filter; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/experiments"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/experiments."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * List experiment items with cursor-based pagination. Use this endpoint + * to export experiment item inputs, outputs, expected outputs, metadata, + * and optionally item/trace scores. Results are ordered by time + * descending. + * + * @param {LangfuseAPI.ListExperimentItemsRequest} request + * @param {Experiments.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.experiments.listItems({ + * fromStartTime: "2024-01-15T09:30:00Z" + * }) + */ + listItems(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__listItems(request, requestOptions)); + } + async __listItems(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { fields, limit, scoreLimit, cursor, fromStartTime, toStartTime, experimentId, experimentName, experimentItemId, datasetId, filter } = request; + const _queryParams = {}; + if (fields != null) _queryParams["fields"] = fields; + if (limit != null) _queryParams["limit"] = limit.toString(); + if (scoreLimit != null) _queryParams["scoreLimit"] = scoreLimit.toString(); + if (cursor != null) _queryParams["cursor"] = cursor; + _queryParams["fromStartTime"] = fromStartTime; + if (toStartTime != null) _queryParams["toStartTime"] = toStartTime; + if (experimentId != null) _queryParams["experimentId"] = experimentId; + if (experimentName != null) _queryParams["experimentName"] = experimentName; + if (experimentItemId != null) _queryParams["experimentItemId"] = experimentItemId; + if (datasetId != null) _queryParams["datasetId"] = datasetId; + if (filter != null) _queryParams["filter"] = filter; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/experiment-items"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/experiment-items."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Feedback = class { + constructor(_options) { + this._options = _options; + } + /** + * Submit explicit user-approved feedback about Langfuse skills, MCP tools, CLI, docs, or public API. Do not include secrets, credentials, customer data, trace payloads, or unrelated use-case details. + * + * Not available in the HIPAA cloud region. + * + * @param {LangfuseAPI.SubmitFeedbackRequest} request + * @param {Feedback.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.FeedbackNotConfiguredError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.feedback.submit({ + * targetType: "skill", + * target: "target", + * feedback: "feedback", + * goal: undefined, + * referenceUrl: undefined + * }) + */ + submit(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__submit(request, requestOptions)); + } + async __submit(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/feedback"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 409: throw new FeedbackNotConfiguredError(_response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/feedback."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Health = class { + constructor(_options) { + this._options = _options; + } + /** + * Check health of API and database + * + * @param {Health.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.ServiceUnavailableError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.health.health() + */ + health(requestOptions) { + return HttpResponsePromise.fromPromise(this.__health(requestOptions)); + } + async __health(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/health"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 503: throw new ServiceUnavailableError(_response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/health."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Ingestion = class { + constructor(_options) { + this._options = _options; + } + /** + * **Legacy endpoint for batch ingestion for Langfuse Observability.** + * + * -> Please use the OpenTelemetry endpoint (`/api/public/otel/v1/traces`). Learn more: https://langfuse.com/integrations/native/opentelemetry + * + * Within each batch, there can be multiple events. + * Each event has a type, an id, a timestamp, metadata and a body. + * Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace. + * We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request. + * The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App. + * I.e. if you want to update a trace, you'd use the same body id, but separate event IDs. + * + * Notes: + * - Introduction to data model: https://langfuse.com/docs/observability/data-model + * - Batch sizes are limited to 3.5 MB in total. You need to adjust the number of events per batch accordingly. + * - The API does not return a 4xx status code for input errors. Instead, it responds with a 207 status code, which includes a list of the encountered errors. + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Send data via the OpenTelemetry endpoint at `POST /api/public/otel/v1/traces` instead, see the [OpenTelemetry integration docs](https://langfuse.com/integrations/native/opentelemetry). Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.IngestionRequest} request + * @param {Ingestion.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.ingestion.batch({ + * batch: [{ + * type: "trace-create", + * id: "abcdef-1234-5678-90ab", + * timestamp: "2022-01-01T00:00:00.000Z", + * body: { + * id: "abcdef-1234-5678-90ab", + * timestamp: "2022-01-01T00:00:00.000Z", + * environment: "production", + * name: "My Trace", + * userId: "1234-5678-90ab-cdef", + * input: "My input", + * output: "My output", + * sessionId: "1234-5678-90ab-cdef", + * release: "1.0.0", + * version: "1.0.0", + * metadata: "My metadata", + * tags: ["tag1", "tag2"], + * "public": true + * } + * }] + * }) + * + * @example + * await client.ingestion.batch({ + * batch: [{ + * type: "span-create", + * id: "abcdef-1234-5678-90ab", + * timestamp: "2022-01-01T00:00:00.000Z", + * body: { + * id: "abcdef-1234-5678-90ab", + * traceId: "1234-5678-90ab-cdef", + * startTime: "2022-01-01T00:00:00.000Z", + * environment: "test" + * } + * }] + * }) + * + * @example + * await client.ingestion.batch({ + * batch: [{ + * type: "score-create", + * id: "abcdef-1234-5678-90ab", + * timestamp: "2022-01-01T00:00:00.000Z", + * body: { + * id: "abcdef-1234-5678-90ab", + * traceId: "1234-5678-90ab-cdef", + * name: "My Score", + * value: 0.9, + * environment: "default" + * } + * }] + * }) + */ + batch(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__batch(request, requestOptions)); + } + async __batch(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/ingestion"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/ingestion."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var MetricsV1 = class { + constructor(_options) { + this._options = _options; + } + /** + * Get metrics from the Langfuse project using a query object. + * + * Consider using the [v2 metrics endpoint](/api-reference#tag/metricsv2/GET/api/public/v2/metrics) for better performance. + * + * For more details, see the [Metrics API documentation](https://langfuse.com/docs/metrics/features/metrics-api). + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Use `GET /api/public/v2/metrics?query=` instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.legacy.GetMetricsRequest} request + * @param {MetricsV1.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.legacy.metricsV1.metrics({ + * query: "query" + * }) + */ + metrics(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__metrics(request, requestOptions)); + } + async __metrics(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { query } = request; + const _queryParams = {}; + _queryParams["query"] = query; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/metrics"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/metrics."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var ObservationsV1 = class { + constructor(_options) { + this._options = _options; + } + /** + * Get a observation + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Use `GET /api/public/v2/observations?fromStartTime=&toStartTime=` instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {string} observationId - The unique langfuse identifier of an observation, can be an event, span or generation + * @param {ObservationsV1.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.legacy.observationsV1.get("observationId") + */ + get(observationId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(observationId, requestOptions)); + } + async __get(observationId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/observations/${encodeURIComponent(observationId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/observations/{observationId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a list of observations. + * + * Consider using the [v2 observations endpoint](/api-reference#tag/observationsv2/GET/api/public/v2/observations) for cursor-based pagination and field selection. + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Use `GET /api/public/v2/observations?fromStartTime=&toStartTime=` instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.legacy.GetObservationsRequest} request + * @param {ObservationsV1.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.legacy.observationsV1.getMany() + */ + getMany(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getMany(request, requestOptions)); + } + async __getMany(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit, name, userId, type: type_, traceId, level, parentObservationId, environment, fromStartTime, toStartTime, version, filter } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + if (name != null) _queryParams["name"] = name; + if (userId != null) _queryParams["userId"] = userId; + if (type_ != null) _queryParams["type"] = type_; + if (traceId != null) _queryParams["traceId"] = traceId; + if (level != null) _queryParams["level"] = level; + if (parentObservationId != null) _queryParams["parentObservationId"] = parentObservationId; + if (environment != null) { + if (Array.isArray(environment)) _queryParams["environment"] = environment.map((item) => item); + else _queryParams["environment"] = environment; + } + if (fromStartTime != null) _queryParams["fromStartTime"] = fromStartTime; + if (toStartTime != null) _queryParams["toStartTime"] = toStartTime; + if (version != null) _queryParams["version"] = version; + if (filter != null) _queryParams["filter"] = filter; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/observations"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/observations."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Scores = class { + constructor(_options) { + this._options = _options; + } + /** + * Create a score (supports trace, observation, session, and dataset run scores) + * + * @param {LangfuseAPI.CreateScoreRequest} request + * @param {Scores.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scores.create({ + * id: undefined, + * traceId: undefined, + * sessionId: undefined, + * observationId: undefined, + * datasetRunId: undefined, + * name: "name", + * value: 1.1, + * comment: undefined, + * metadata: undefined, + * environment: undefined, + * queueId: undefined, + * dataType: undefined, + * configId: undefined, + * source: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/scores"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/scores."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a list of scores (supports both trace and session scores) + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Use `GET /api/public/v3/scores` instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.GetScoresRequest} request + * @param {Scores.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scores.getMany() + */ + getMany(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getMany(request, requestOptions)); + } + async __getMany(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit, userId, name, fromTimestamp, toTimestamp, environment, source, operator, value, scoreIds, configId, sessionId, datasetRunId, traceId, observationId, queueId, dataType, traceTags, fields, filter } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + if (userId != null) _queryParams["userId"] = userId; + if (name != null) _queryParams["name"] = name; + if (fromTimestamp != null) _queryParams["fromTimestamp"] = fromTimestamp; + if (toTimestamp != null) _queryParams["toTimestamp"] = toTimestamp; + if (environment != null) { + if (Array.isArray(environment)) _queryParams["environment"] = environment.map((item) => item); + else _queryParams["environment"] = environment; + } + if (source != null) _queryParams["source"] = source; + if (operator != null) _queryParams["operator"] = operator; + if (value != null) _queryParams["value"] = value.toString(); + if (scoreIds != null) _queryParams["scoreIds"] = scoreIds; + if (configId != null) _queryParams["configId"] = configId; + if (sessionId != null) _queryParams["sessionId"] = sessionId; + if (datasetRunId != null) _queryParams["datasetRunId"] = datasetRunId; + if (traceId != null) _queryParams["traceId"] = traceId; + if (observationId != null) _queryParams["observationId"] = observationId; + if (queueId != null) _queryParams["queueId"] = queueId; + if (dataType != null) _queryParams["dataType"] = dataType; + if (traceTags != null) { + if (Array.isArray(traceTags)) _queryParams["traceTags"] = traceTags.map((item) => item); + else _queryParams["traceTags"] = traceTags; + } + if (fields != null) _queryParams["fields"] = fields; + if (filter != null) _queryParams["filter"] = filter; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/scores"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/scores."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a score (supports both trace and session scores) + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Use `GET /api/public/v3/scores` with the `id` filter instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {string} scoreId - The unique langfuse identifier of a score + * @param {Scores.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scores.getById("scoreId") + */ + getById(scoreId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getById(scoreId, requestOptions)); + } + async __getById(scoreId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/scores/${encodeURIComponent(scoreId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/scores/{scoreId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var ScoreV1 = class { + constructor(_options) { + this._options = _options; + } + /** + * Create a score (supports both trace and session scores) + * + * @deprecated Use `client.scores.create()` instead. + * Compatibility alias managed by scripts/patch-generated-score-create-alias.mjs + */ + create(request, requestOptions) { + return new Scores(this._options).create(request, requestOptions); + } + /** + * Delete a score (supports both trace and session scores) + * + * @param {string} scoreId - The unique langfuse identifier of a score + * @param {ScoreV1.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.legacy.scoreV1.delete("scoreId") + */ + delete(scoreId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(scoreId, requestOptions)); + } + async __delete(scoreId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/scores/${encodeURIComponent(scoreId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: void 0, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/scores/{scoreId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Legacy = class { + constructor(_options) { + this._options = _options; + } + get metricsV1() { + var _a2; + return (_a2 = this._metricsV1) != null ? _a2 : this._metricsV1 = new MetricsV1(this._options); + } + get observationsV1() { + var _a2; + return (_a2 = this._observationsV1) != null ? _a2 : this._observationsV1 = new ObservationsV1(this._options); + } + get scoreV1() { + var _a2; + return (_a2 = this._scoreV1) != null ? _a2 : this._scoreV1 = new ScoreV1(this._options); + } +}; +var LlmConnections = class { + constructor(_options) { + this._options = _options; + } + /** + * Get all LLM connections in a project + * + * @param {LangfuseAPI.GetLlmConnectionsRequest} request + * @param {LlmConnections.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.llmConnections.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/llm-connections"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/llm-connections."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create or update an LLM connection. The connection is upserted on provider. + * + * @param {LangfuseAPI.UpsertLlmConnectionRequest} request + * @param {LlmConnections.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.llmConnections.upsert({ + * provider: "provider", + * adapter: "anthropic", + * secretKey: "secretKey", + * baseURL: undefined, + * customModels: undefined, + * withDefaultModels: undefined, + * extraHeaders: undefined, + * config: undefined + * }) + */ + upsert(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + async __upsert(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/llm-connections"), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PUT /api/public/llm-connections."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete an LLM connection by id. Evaluators that depend on the deleted connection are automatically paused. + * + * @param {string} id + * @param {LlmConnections.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.llmConnections.delete("id") + */ + delete(id, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(id, requestOptions)); + } + async __delete(id, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/llm-connections/${encodeURIComponent(id)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/llm-connections/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Media = class { + constructor(_options) { + this._options = _options; + } + /** + * Get a media record + * + * @param {string} mediaId - The unique langfuse identifier of a media record + * @param {Media.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.media.get("mediaId") + */ + get(mediaId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(mediaId, requestOptions)); + } + async __get(mediaId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/media/${encodeURIComponent(mediaId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/media/{mediaId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Patch a media record + * + * @param {string} mediaId - The unique langfuse identifier of a media record + * @param {LangfuseAPI.PatchMediaBody} request + * @param {Media.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.media.patch("mediaId", { + * uploadedAt: "2024-01-15T09:30:00Z", + * uploadHttpStatus: 1, + * uploadHttpError: undefined, + * uploadTimeMs: undefined + * }) + */ + patch(mediaId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__patch(mediaId, request, requestOptions)); + } + async __patch(mediaId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/media/${encodeURIComponent(mediaId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: void 0, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/media/{mediaId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a presigned upload URL for a media record + * + * @param {LangfuseAPI.GetMediaUploadUrlRequest} request + * @param {Media.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.media.getUploadUrl({ + * traceId: undefined, + * observationId: undefined, + * datasetId: undefined, + * datasetItemId: undefined, + * contentType: "image/png", + * contentLength: 1, + * sha256Hash: "sha256Hash", + * field: "field" + * }) + */ + getUploadUrl(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getUploadUrl(request, requestOptions)); + } + async __getUploadUrl(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/media"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/media."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Metrics = class { + constructor(_options) { + this._options = _options; + } + /** + * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. + * + * ## V2 Differences + * - Supports `observations`, `scores-numeric`, `scores-boolean`, and `scores-categorical` views only (traces view not supported) + * - Direct access to tags and release fields on observations + * - Semantic-root filtering and grouping through the v2-only `isRootObservation` dimension + * - Backwards-compatible: traceName, traceRelease, traceVersion dimensions are still available on observations view + * - High cardinality dimensions are not supported and will return a 400 error (see below) + * + * For more details, see the [Metrics API documentation](https://langfuse.com/docs/metrics/features/metrics-api). + * + * ## Available Views + * + * ### observations + * Query observation-level data (spans, generations, events). + * + * **Dimensions:** + * - `environment` - Deployment environment (e.g., production, staging) + * - `type` - Type of observation (SPAN, GENERATION, EVENT) + * - `name` - Name of the observation + * - `level` - Logging level of the observation + * - `version` - Version of the observation + * - `tags` - User-defined tags + * - `release` - Release version + * - `traceName` - Name of the parent trace (backwards-compatible) + * - `traceRelease` - Release version of the parent trace (backwards-compatible, maps to release) + * - `traceVersion` - Version of the parent trace (backwards-compatible, maps to version) + * - `providedModelName` - Name of the model used + * - `promptName` - Name of the prompt used + * - `promptVersion` - Version of the prompt used + * - `isRootObservation` - Boolean semantic-root status. `true` includes physical roots and app roots whose SDK parent is external (so `parentObservationId` may be non-null). + * - `startTimeMonth` - Month of start_time in YYYY-MM format + * + * **Measures:** + * - `count` - Total number of observations + * - `latency` - Observation latency (milliseconds) + * - `streamingLatency` - Generation latency from completion start to end (milliseconds) + * - `inputTokens` - Sum of input tokens consumed + * - `outputTokens` - Sum of output tokens produced + * - `totalTokens` - Sum of all tokens consumed + * - `outputTokensPerSecond` - Output tokens per second + * - `tokensPerSecond` - Total tokens per second + * - `inputCost` - Input cost (USD) + * - `outputCost` - Output cost (USD) + * - `totalCost` - Total cost (USD) + * - `timeToFirstToken` - Time to first token (milliseconds) + * - `countScores` - Number of scores attached to the observation + * + * ### scores-numeric + * Query numeric and boolean score data. + * + * **Dimensions:** + * - `environment` - Deployment environment + * - `name` - Name of the score (e.g., accuracy, toxicity) + * - `source` - Origin of the score (API, ANNOTATION, EVAL) + * - `dataType` - Data type (NUMERIC, BOOLEAN) + * - `configId` - Identifier of the score config + * - `timestampMonth` - Month in YYYY-MM format + * - `timestampDay` - Day in YYYY-MM-DD format + * - `value` - Numeric value of the score + * - `traceName` - Name of the parent trace + * - `tags` - Tags + * - `traceRelease` - Release version + * - `traceVersion` - Version + * - `observationName` - Name of the associated observation + * - `observationModelName` - Model name of the associated observation + * - `observationPromptName` - Prompt name of the associated observation + * - `observationPromptVersion` - Prompt version of the associated observation + * + * **Measures:** + * - `count` - Total number of scores + * - `value` - Score value (for aggregations) + * + * ### scores-boolean + * Query boolean score data. It has the same score and parent trace/observation dimensions as scores-numeric, plus: + * + * **Dimensions:** + * - `booleanValue` - Boolean value for true/false grouping and filtering + * + * **Measures:** + * - `count` - Total number of boolean scores + * - `value` - Numeric 0/1 score value; `avg` returns the true-rate + * + * ### scores-categorical + * Query categorical score data. Same dimensions as scores-numeric except uses `stringValue` instead of `value`. + * + * **Measures:** + * - `count` - Total number of scores + * + * ## High Cardinality Dimensions + * The following dimensions cannot be used as grouping dimensions in v2 metrics API as they can cause performance issues. + * Use them in filters instead. + * + * **observations view:** + * - `id` - Use traceId filter to narrow down results + * - `traceId` - Use traceId filter instead + * - `userId` - Use userId filter instead + * - `sessionId` - Use sessionId filter instead + * - `parentObservationId` - Use parentObservationId filter instead + * + * **scores-numeric / scores-boolean / scores-categorical views:** + * - `id` - Use specific filters to narrow down results + * - `traceId` - Use traceId filter instead + * - `userId` - Use userId filter instead + * - `sessionId` - Use sessionId filter instead + * - `observationId` - Use observationId filter instead + * + * ## Aggregations + * Available aggregation functions: `sum`, `avg`, `count`, `max`, `min`, `p50`, `p75`, `p90`, `p95`, `p99`, `histogram` + * + * ## Time Granularities + * Available granularities for timeDimension: `auto`, `minute`, `hour`, `day`, `week`, `month` + * - `auto` bins the data into approximately 50 buckets based on the time range + * + * @param {LangfuseAPI.GetMetricsV2Request} request + * @param {Metrics.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.metrics.metrics({ + * query: "query" + * }) + */ + metrics(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__metrics(request, requestOptions)); + } + async __metrics(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { query } = request; + const _queryParams = {}; + _queryParams["query"] = query; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/metrics"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/metrics."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Models = class { + constructor(_options) { + this._options = _options; + } + /** + * Create a model + * + * @param {LangfuseAPI.CreateModelRequest} request + * @param {Models.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.models.create({ + * modelName: "modelName", + * matchPattern: "matchPattern", + * startDate: undefined, + * unit: "CHARACTERS", + * inputPrice: undefined, + * outputPrice: undefined, + * totalPrice: undefined, + * pricingTiers: undefined, + * tokenizerId: undefined, + * tokenizerConfig: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/models"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/models."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create or replace a project-owned model using its id. Built-in models cannot be modified. + * + * @param {string} id + * @param {LangfuseAPI.CreateModelRequest} request + * @param {Models.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.models.upsert("id", { + * modelName: "modelName", + * matchPattern: "matchPattern", + * startDate: undefined, + * unit: "CHARACTERS", + * inputPrice: undefined, + * outputPrice: undefined, + * totalPrice: undefined, + * pricingTiers: undefined, + * tokenizerId: undefined, + * tokenizerConfig: undefined + * }) + */ + upsert(id, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__upsert(id, request, requestOptions)); + } + async __upsert(id, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/models/${encodeURIComponent(id)}`), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PUT /api/public/models/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get all models + * + * @param {LangfuseAPI.GetModelsRequest} request + * @param {Models.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.models.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/models"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/models."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a model + * + * @param {string} id + * @param {Models.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.models.get("id") + */ + get(id, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(id, requestOptions)); + } + async __get(id, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/models/${encodeURIComponent(id)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/models/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + * + * @param {string} id + * @param {Models.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.models.delete("id") + */ + delete(id, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(id, requestOptions)); + } + async __delete(id, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/models/${encodeURIComponent(id)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: void 0, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/models/{id}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Observations = class { + constructor(_options) { + this._options = _options; + } + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + * + * ## Cursor-based Pagination + * This endpoint uses cursor-based pagination for efficient traversal of large datasets. + * The cursor is returned in the response metadata and should be passed in subsequent requests + * to retrieve the next page of results. + * + * ## Field Selection + * Use the `fields` parameter to control which observation fields are returned: + * - `core` - Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type + * - `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId, isRootObservation + * - `time` - completionStartTime, createdAt, updatedAt + * - `io` - input, output + * - `metadata` - metadata (truncated to 200 chars by default, use `expandMetadata` to get full values) + * - `model` - model, internalModelId, modelParameters + * - `usage` - usageDetails, costDetails, totalCost, usagePricingTierName + * - `prompt` - promptId, promptName, promptVersion + * - `metrics` - latency, timeToFirstToken + * - `trace_context` - tags, release, traceName + * + * If not specified, `core` and `basic` field groups are returned. + * + * ## Filters + * Multiple filtering options are available via query parameters or the structured `filter` parameter. + * When using the `filter` parameter, it takes precedence over individual query parameter filters. + * + * @param {LangfuseAPI.GetObservationsV2Request} request + * @param {Observations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.observations.getMany() + */ + getMany(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getMany(request, requestOptions)); + } + async __getMany(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { fields, expandMetadata, limit, cursor, parseIoAsJson, name, userId, sessionId, type: type_, traceId, level, parentObservationId, isRootObservation, environment, fromStartTime, toStartTime, version, filter } = request; + const _queryParams = {}; + if (fields != null) _queryParams["fields"] = fields; + if (expandMetadata != null) _queryParams["expandMetadata"] = expandMetadata; + if (limit != null) _queryParams["limit"] = limit.toString(); + if (cursor != null) _queryParams["cursor"] = cursor; + if (parseIoAsJson != null) _queryParams["parseIoAsJson"] = parseIoAsJson.toString(); + if (name != null) _queryParams["name"] = name; + if (userId != null) _queryParams["userId"] = userId; + if (sessionId != null) _queryParams["sessionId"] = sessionId; + if (type_ != null) _queryParams["type"] = type_; + if (traceId != null) _queryParams["traceId"] = traceId; + if (level != null) _queryParams["level"] = level; + if (parentObservationId != null) _queryParams["parentObservationId"] = parentObservationId; + if (isRootObservation != null) _queryParams["isRootObservation"] = isRootObservation.toString(); + if (environment != null) { + if (Array.isArray(environment)) _queryParams["environment"] = environment.map((item) => item); + else _queryParams["environment"] = environment; + } + if (fromStartTime != null) _queryParams["fromStartTime"] = fromStartTime; + if (toStartTime != null) _queryParams["toStartTime"] = toStartTime; + if (version != null) _queryParams["version"] = version; + if (filter != null) _queryParams["filter"] = filter; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/observations"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/observations."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Opentelemetry = class { + constructor(_options) { + this._options = _options; + } + /** + * **OpenTelemetry Traces Ingestion Endpoint** + * + * This endpoint implements the OTLP/HTTP specification for trace ingestion, providing native OpenTelemetry integration for Langfuse Observability. + * + * **Supported Formats:** + * - Binary Protobuf: `Content-Type: application/x-protobuf` + * - JSON Protobuf: `Content-Type: application/json` + * - Supports gzip compression via `Content-Encoding: gzip` header + * + * **Specification Compliance:** + * - Conforms to [OTLP/HTTP Trace Export](https://opentelemetry.io/docs/specs/otlp/#otlphttp) + * - Implements `ExportTraceServiceRequest` message format + * + * **Documentation:** + * - Integration guide: https://langfuse.com/integrations/native/opentelemetry + * - Data model: https://langfuse.com/docs/observability/data-model + * + * @param {LangfuseAPI.OtelTraceRequest} request + * @param {Opentelemetry.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.opentelemetry.exportTraces({ + * resourceSpans: [{ + * resource: { + * attributes: [{ + * key: "service.name", + * value: { + * stringValue: "my-service" + * } + * }, { + * key: "service.version", + * value: { + * stringValue: "1.0.0" + * } + * }] + * }, + * scopeSpans: [{ + * scope: { + * name: "langfuse-sdk", + * version: "2.60.3" + * }, + * spans: [{ + * traceId: "0123456789abcdef0123456789abcdef", + * spanId: "0123456789abcdef", + * name: "my-operation", + * kind: 1, + * startTimeUnixNano: "1747872000000000000", + * endTimeUnixNano: "1747872001000000000", + * attributes: [{ + * key: "langfuse.observation.type", + * value: { + * stringValue: "generation" + * } + * }], + * status: {} + * }] + * }] + * }] + * }) + */ + exportTraces(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__exportTraces(request, requestOptions)); + } + async __exportTraces(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/otel/v1/traces"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/otel/v1/traces."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Organizations = class { + constructor(_options) { + this._options = _options; + } + /** + * Get all memberships for the organization associated with the API key (requires organization-scoped API key) + * + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.getOrganizationMemberships() + */ + getOrganizationMemberships(requestOptions) { + return HttpResponsePromise.fromPromise(this.__getOrganizationMemberships(requestOptions)); + } + async __getOrganizationMemberships(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/organizations/memberships"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/organizations/memberships."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) + * + * @param {LangfuseAPI.MembershipRequest} request + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.updateOrganizationMembership({ + * userId: "userId", + * role: "OWNER" + * }) + */ + updateOrganizationMembership(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__updateOrganizationMembership(request, requestOptions)); + } + async __updateOrganizationMembership(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/organizations/memberships"), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PUT /api/public/organizations/memberships."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a membership from the organization associated with the API key (requires organization-scoped API key) + * + * @param {LangfuseAPI.DeleteMembershipRequest} request + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.deleteOrganizationMembership({ + * userId: "userId" + * }) + */ + deleteOrganizationMembership(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteOrganizationMembership(request, requestOptions)); + } + async __deleteOrganizationMembership(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/organizations/memberships"), + method: "DELETE", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/organizations/memberships."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get all memberships for a specific project (requires organization-scoped API key) + * + * @param {string} projectId + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.getProjectMemberships("projectId") + */ + getProjectMemberships(projectId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getProjectMemberships(projectId, requestOptions)); + } + async __getProjectMemberships(projectId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}/memberships`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/projects/{projectId}/memberships."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. + * + * @param {string} projectId + * @param {LangfuseAPI.MembershipRequest} request + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.updateProjectMembership("projectId", { + * userId: "userId", + * role: "OWNER" + * }) + */ + updateProjectMembership(projectId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__updateProjectMembership(projectId, request, requestOptions)); + } + async __updateProjectMembership(projectId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}/memberships`), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PUT /api/public/projects/{projectId}/memberships."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a membership from a specific project (requires organization-scoped API key). The user must be a member of the organization. + * + * @param {string} projectId + * @param {LangfuseAPI.DeleteMembershipRequest} request + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.deleteProjectMembership("projectId", { + * userId: "userId" + * }) + */ + deleteProjectMembership(projectId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteProjectMembership(projectId, request, requestOptions)); + } + async __deleteProjectMembership(projectId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}/memberships`), + method: "DELETE", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/projects/{projectId}/memberships."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get all projects for the organization associated with the API key (requires organization-scoped API key) + * + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.getOrganizationProjects() + */ + getOrganizationProjects(requestOptions) { + return HttpResponsePromise.fromPromise(this.__getOrganizationProjects(requestOptions)); + } + async __getOrganizationProjects(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/organizations/projects"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/organizations/projects."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get all API keys for the organization associated with the API key (requires organization-scoped API key) + * + * @param {Organizations.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.organizations.getOrganizationApiKeys() + */ + getOrganizationApiKeys(requestOptions) { + return HttpResponsePromise.fromPromise(this.__getOrganizationApiKeys(requestOptions)); + } + async __getOrganizationApiKeys(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/organizations/apiKeys"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/organizations/apiKeys."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Projects = class { + constructor(_options) { + this._options = _options; + } + /** + * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. + * + * @param {Projects.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.projects.get() + */ + get(requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(requestOptions)); + } + async __get(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/projects"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/projects."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create a new project (requires organization-scoped API key) + * + * @param {LangfuseAPI.CreateProjectRequest} request + * @param {Projects.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.projects.create({ + * name: "name", + * metadata: undefined, + * retention: 1 + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/projects"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/projects."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Update a project by ID (requires organization-scoped API key). + * + * @param {string} projectId + * @param {LangfuseAPI.UpdateProjectRequest} request + * @param {Projects.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.projects.update("projectId", { + * name: "name", + * metadata: undefined, + * retention: undefined + * }) + */ + update(projectId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__update(projectId, request, requestOptions)); + } + async __update(projectId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}`), + method: "PUT", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PUT /api/public/projects/{projectId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. + * + * @param {string} projectId + * @param {Projects.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.projects.delete("projectId") + */ + delete(projectId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(projectId, requestOptions)); + } + async __delete(projectId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/projects/{projectId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get all API keys for a project (requires organization-scoped API key) + * + * @param {string} projectId + * @param {Projects.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.projects.getApiKeys("projectId") + */ + getApiKeys(projectId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getApiKeys(projectId, requestOptions)); + } + async __getApiKeys(projectId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}/apiKeys`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/projects/{projectId}/apiKeys."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create a new API key for a project (requires organization-scoped API key) + * + * @param {string} projectId + * @param {LangfuseAPI.CreateApiKeyRequest} request + * @param {Projects.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.projects.createApiKey("projectId", { + * note: undefined, + * publicKey: undefined, + * secretKey: undefined + * }) + */ + createApiKey(projectId, request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__createApiKey(projectId, request, requestOptions)); + } + async __createApiKey(projectId, request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}/apiKeys`), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/projects/{projectId}/apiKeys."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete an API key for a project (requires organization-scoped API key) + * + * @param {string} projectId + * @param {string} apiKeyId + * @param {Projects.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.projects.deleteApiKey("projectId", "apiKeyId") + */ + deleteApiKey(projectId, apiKeyId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteApiKey(projectId, apiKeyId, requestOptions)); + } + async __deleteApiKey(projectId, apiKeyId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/projects/${encodeURIComponent(projectId)}/apiKeys/${encodeURIComponent(apiKeyId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/projects/{projectId}/apiKeys/{apiKeyId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var PromptVersion = class { + constructor(_options) { + this._options = _options; + } + /** + * Update labels for a specific prompt version + * + * @param {string} name - The name of the prompt. If the prompt is in a folder (e.g., "folder/subfolder/prompt-name"), + * the folder path must be URL encoded. + * @param {number} version - Version of the prompt to update + * @param {LangfuseAPI.UpdatePromptRequest} request + * @param {PromptVersion.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.promptVersion.update("name", 1, { + * newLabels: ["newLabels", "newLabels"] + * }) + */ + update(name, version, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__update(name, version, request, requestOptions)); + } + async __update(name, version, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/prompts/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/v2/prompts/{name}/versions/{version}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Prompts = class { + constructor(_options) { + this._options = _options; + } + /** + * Get a prompt + * + * @param {string} promptName - The name of the prompt. If the prompt is in a folder (e.g., "folder/subfolder/prompt-name"), + * the folder path must be URL encoded. + * @param {LangfuseAPI.GetPromptRequest} request + * @param {Prompts.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.prompts.get("promptName") + */ + get(promptName, request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(promptName, request, requestOptions)); + } + async __get(promptName, request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { version, label, resolve } = request; + const _queryParams = {}; + if (version != null) _queryParams["version"] = version.toString(); + if (label != null) _queryParams["label"] = label; + if (resolve != null) _queryParams["resolve"] = resolve.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/prompts/${encodeURIComponent(promptName)}`), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/prompts/{promptName}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a list of prompt names with versions and labels + * + * @param {LangfuseAPI.ListPromptsMetaRequest} request + * @param {Prompts.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.prompts.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { name, label, tag, page, limit, fromUpdatedAt, toUpdatedAt } = request; + const _queryParams = {}; + if (name != null) _queryParams["name"] = name; + if (label != null) _queryParams["label"] = label; + if (tag != null) _queryParams["tag"] = tag; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + if (fromUpdatedAt != null) _queryParams["fromUpdatedAt"] = fromUpdatedAt; + if (toUpdatedAt != null) _queryParams["toUpdatedAt"] = toUpdatedAt; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/prompts"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v2/prompts."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create a new version for the prompt with the given `name` + * + * @param {LangfuseAPI.CreatePromptRequest} request + * @param {Prompts.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.prompts.create({ + * name: "name", + * prompt: [{ + * role: "role", + * content: "content", + * type: undefined + * }, { + * role: "role", + * content: "content", + * type: undefined + * }], + * config: undefined, + * type: "chat", + * labels: undefined, + * tags: undefined, + * commitMessage: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v2/prompts"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/v2/prompts."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + * + * @param {string} promptName - The name of the prompt + * @param {LangfuseAPI.DeletePromptRequest} request + * @param {Prompts.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.prompts.delete("promptName") + */ + delete(promptName, request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(promptName, request, requestOptions)); + } + async __delete(promptName, request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { label, version } = request; + const _queryParams = {}; + if (label != null) _queryParams["label"] = label; + if (version != null) _queryParams["version"] = version.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/v2/prompts/${encodeURIComponent(promptName)}`), + method: "DELETE", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: void 0, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/v2/prompts/{promptName}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Scim = class { + constructor(_options) { + this._options = _options; + } + /** + * Get SCIM Service Provider Configuration (requires organization-scoped API key) + * + * @param {Scim.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scim.getServiceProviderConfig() + */ + getServiceProviderConfig(requestOptions) { + return HttpResponsePromise.fromPromise(this.__getServiceProviderConfig(requestOptions)); + } + async __getServiceProviderConfig(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/scim/ServiceProviderConfig"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/scim/ServiceProviderConfig."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get SCIM Resource Types (requires organization-scoped API key) + * + * @param {Scim.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scim.getResourceTypes() + */ + getResourceTypes(requestOptions) { + return HttpResponsePromise.fromPromise(this.__getResourceTypes(requestOptions)); + } + async __getResourceTypes(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/scim/ResourceTypes"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/scim/ResourceTypes."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get SCIM Schemas (requires organization-scoped API key) + * + * @param {Scim.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scim.getSchemas() + */ + getSchemas(requestOptions) { + return HttpResponsePromise.fromPromise(this.__getSchemas(requestOptions)); + } + async __getSchemas(requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/scim/Schemas"), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/scim/Schemas."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * List users in the organization (requires organization-scoped API key) + * + * @param {LangfuseAPI.ListUsersRequest} request + * @param {Scim.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scim.listUsers() + */ + listUsers(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__listUsers(request, requestOptions)); + } + async __listUsers(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { filter, startIndex, count } = request; + const _queryParams = {}; + if (filter != null) _queryParams["filter"] = filter; + if (startIndex != null) _queryParams["startIndex"] = startIndex.toString(); + if (count != null) _queryParams["count"] = count.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/scim/Users"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/scim/Users."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create a new user in the organization (requires organization-scoped API key) + * + * @param {LangfuseAPI.CreateUserRequest} request + * @param {Scim.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scim.createUser({ + * userName: "userName", + * name: { + * formatted: undefined + * }, + * emails: undefined, + * active: undefined, + * password: undefined + * }) + */ + createUser(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__createUser(request, requestOptions)); + } + async __createUser(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/scim/Users"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/scim/Users."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a specific user by ID (requires organization-scoped API key) + * + * @param {string} userId + * @param {Scim.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scim.getUser("userId") + */ + getUser(userId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getUser(userId, requestOptions)); + } + async __getUser(userId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/scim/Users/${encodeURIComponent(userId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/scim/Users/{userId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + * + * @param {string} userId + * @param {Scim.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scim.deleteUser("userId") + */ + deleteUser(userId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteUser(userId, requestOptions)); + } + async __deleteUser(userId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/scim/Users/${encodeURIComponent(userId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/scim/Users/{userId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var ScoreConfigs = class { + constructor(_options) { + this._options = _options; + } + /** + * Create a score configuration (config). Score configs are used to define the structure of scores + * + * @param {LangfuseAPI.CreateScoreConfigRequest} request + * @param {ScoreConfigs.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scoreConfigs.create({ + * name: "name", + * dataType: "NUMERIC", + * categories: undefined, + * minValue: undefined, + * maxValue: undefined, + * description: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/score-configs"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/score-configs."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get all score configs + * + * @param {LangfuseAPI.GetScoreConfigsRequest} request + * @param {ScoreConfigs.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scoreConfigs.get() + */ + get(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + async __get(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/score-configs"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/score-configs."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a score config + * + * @param {string} configId - The unique langfuse identifier of a score config + * @param {ScoreConfigs.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scoreConfigs.getById("configId") + */ + getById(configId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getById(configId, requestOptions)); + } + async __getById(configId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/score-configs/${encodeURIComponent(configId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/score-configs/{configId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Update a score config + * + * @param {string} configId - The unique langfuse identifier of a score config + * @param {LangfuseAPI.UpdateScoreConfigRequest} request + * @param {ScoreConfigs.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scoreConfigs.update("configId", { + * isArchived: undefined, + * name: undefined, + * categories: undefined, + * minValue: undefined, + * maxValue: undefined, + * description: undefined + * }) + */ + update(configId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__update(configId, request, requestOptions)); + } + async __update(configId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/score-configs/${encodeURIComponent(configId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/score-configs/{configId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var ScoresV3 = class { + constructor(_options) { + this._options = _options; + } + /** + * Get a list of scores with a polymorphic `value` field (v3). + * + * The `value` field type depends on `dataType`: + * - `NUMERIC` → number + * - `BOOLEAN` → boolean + * - `CATEGORICAL`, `TEXT`, `CORRECTION` → string + * + * The response always includes the core fields: id, projectId, name, + * value, dataType, source, timestamp, environment, createdAt, updatedAt. + * + * Additional field groups can be requested via the `fields` parameter: + * - `details` — adds comment, configId, metadata + * - `subject` — adds the subject object describing the entity the score + * is attached to: kind (trace, observation, session, or experiment), + * id, and traceId for observation-level scores + * - `annotation` — adds authorUserId, queueId + * + * Unknown group names return HTTP 400. + * + * @param {LangfuseAPI.GetScoresV3Request} request + * @param {ScoresV3.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.scoresV3.getManyV3() + */ + getManyV3(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__getManyV3(request, requestOptions)); + } + async __getManyV3(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { limit, cursor, fields, id, name, source, dataType, environment, configId, queueId, authorUserId, value, valueMin, valueMax, traceId, sessionId, observationId, experimentId, fromTimestamp, toTimestamp } = request; + const _queryParams = {}; + if (limit != null) _queryParams["limit"] = limit.toString(); + if (cursor != null) _queryParams["cursor"] = cursor; + if (fields != null) _queryParams["fields"] = fields; + if (id != null) _queryParams["id"] = id; + if (name != null) _queryParams["name"] = name; + if (source != null) _queryParams["source"] = source; + if (dataType != null) _queryParams["dataType"] = dataType; + if (environment != null) _queryParams["environment"] = environment; + if (configId != null) _queryParams["configId"] = configId; + if (queueId != null) _queryParams["queueId"] = queueId; + if (authorUserId != null) _queryParams["authorUserId"] = authorUserId; + if (value != null) _queryParams["value"] = value; + if (valueMin != null) _queryParams["valueMin"] = valueMin.toString(); + if (valueMax != null) _queryParams["valueMax"] = valueMax.toString(); + if (traceId != null) _queryParams["traceId"] = traceId; + if (sessionId != null) _queryParams["sessionId"] = sessionId; + if (observationId != null) _queryParams["observationId"] = observationId; + if (experimentId != null) _queryParams["experimentId"] = experimentId; + if (fromTimestamp != null) _queryParams["fromTimestamp"] = fromTimestamp; + if (toTimestamp != null) _queryParams["toTimestamp"] = toTimestamp; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/v3/scores"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/v3/scores."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Sessions = class { + constructor(_options) { + this._options = _options; + } + /** + * Get sessions. + * + * This legacy endpoint is not recommended for new data extraction workflows. + * Use the v2 observations endpoint with a bounded time range and group rows by + * `sessionId` instead: + * `GET /api/public/v2/observations?fromStartTime=&toStartTime=`. + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, read session data via `GET /api/public/v2/observations?filter=&fromStartTime=&toStartTime=`. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.GetSessionsRequest} request + * @param {Sessions.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.sessions.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit, fromTimestamp, toTimestamp, environment } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + if (fromTimestamp != null) _queryParams["fromTimestamp"] = fromTimestamp; + if (toTimestamp != null) _queryParams["toTimestamp"] = toTimestamp; + if (environment != null) { + if (Array.isArray(environment)) _queryParams["environment"] = environment.map((item) => item); + else _queryParams["environment"] = environment; + } + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/sessions"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/sessions."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a session. + * + * Please note that `traces` on this endpoint are not paginated. For large + * sessions or new data extraction workflows, use the v2 observations endpoint + * with a URL-encoded `sessionId` filter and a bounded time range: + * `GET /api/public/v2/observations?filter=&fromStartTime=&toStartTime=`. + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, read session data via `GET /api/public/v2/observations?filter=&fromStartTime=&toStartTime=`. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {string} sessionId - The unique id of a session + * @param {Sessions.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.sessions.get("sessionId") + */ + get(sessionId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(sessionId, requestOptions)); + } + async __get(sessionId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/sessions/${encodeURIComponent(sessionId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/sessions/{sessionId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Trace = class { + constructor(_options) { + this._options = _options; + } + /** + * Get a specific trace + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, read span and trace data via `GET /api/public/v2/observations?fromStartTime=&toStartTime=`. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {string} traceId - The unique langfuse identifier of a trace + * @param {LangfuseAPI.GetTraceRequest} request + * @param {Trace.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.trace.get("traceId") + */ + get(traceId, request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(traceId, request, requestOptions)); + } + async __get(traceId, request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { fields } = request; + const _queryParams = {}; + if (fields != null) _queryParams["fields"] = fields; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/traces/${encodeURIComponent(traceId)}`), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/traces/{traceId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a specific trace + * + * @param {string} traceId - The unique langfuse identifier of the trace to delete + * @param {Trace.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.trace.delete("traceId") + */ + delete(traceId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(traceId, requestOptions)); + } + async __delete(traceId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/traces/${encodeURIComponent(traceId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/traces/{traceId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get list of traces + * + * @deprecated On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. In Langfuse v4, read span and trace data via `GET /api/public/v2/observations?fromStartTime=&toStartTime=`. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. + * + * @param {LangfuseAPI.GetTracesRequest} request + * @param {Trace.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.trace.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit, userId, name, sessionId, fromTimestamp, toTimestamp, orderBy, tags, version, release, environment, fields, filter } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + if (userId != null) _queryParams["userId"] = userId; + if (name != null) _queryParams["name"] = name; + if (sessionId != null) _queryParams["sessionId"] = sessionId; + if (fromTimestamp != null) _queryParams["fromTimestamp"] = fromTimestamp; + if (toTimestamp != null) _queryParams["toTimestamp"] = toTimestamp; + if (orderBy != null) _queryParams["orderBy"] = orderBy; + if (tags != null) { + if (Array.isArray(tags)) _queryParams["tags"] = tags.map((item) => item); + else _queryParams["tags"] = tags; + } + if (version != null) _queryParams["version"] = version; + if (release != null) _queryParams["release"] = release; + if (environment != null) { + if (Array.isArray(environment)) _queryParams["environment"] = environment.map((item) => item); + else _queryParams["environment"] = environment; + } + if (fields != null) _queryParams["fields"] = fields; + if (filter != null) _queryParams["filter"] = filter; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/traces"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/traces."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete multiple traces + * + * @param {LangfuseAPI.DeleteTracesRequest} request + * @param {Trace.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.trace.deleteMultiple({ + * traceIds: ["traceIds", "traceIds"] + * }) + */ + deleteMultiple(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deleteMultiple(request, requestOptions)); + } + async __deleteMultiple(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/traces"), + method: "DELETE", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/traces."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var DashboardWidgets = class { + constructor(_options) { + this._options = _options; + } + /** + * List dashboard widgets in the project, ordered by most recently + * updated first. + * + * Responses may include legacy `traces` widgets created before this + * API existed. New widgets cannot be created with `view: traces`. + * + * @param {LangfuseAPI.unstable.ListDashboardWidgetsRequest} request + * @param {DashboardWidgets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboardWidgets.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/unstable/dashboard-widgets"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/unstable/dashboard-widgets."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create a dashboard widget (a standalone chart definition you place on + * any dashboard). + * + * This endpoint creates the widget only; place it on a dashboard via + * `POST /dashboards/{dashboardId}/placements`. + * + * Supported views are `observations`, `scores-numeric`, `scores-boolean`, and `scores-categorical`. + * The legacy `traces` view is not supported by this unstable API. + * Widgets are created as v2 internally. + * + * `chartConfig` is optional and defaults to the plain config for + * `chartType`; when `chartConfig.type` is given it must match + * `chartType`. + * + * Unstable API note: + * - This surface may evolve while dashboard/widget APIs are being finalized. + * + * @param {LangfuseAPI.unstable.CreateDashboardWidgetRequest} request + * @param {DashboardWidgets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboardWidgets.create({ + * name: "Total cost by model", + * description: "Total model cost grouped by provided model name.", + * view: "observations", + * dimensions: [{ + * field: "providedModelName" + * }], + * metrics: [{ + * measure: "totalCost", + * agg: "sum" + * }], + * filters: [], + * chartType: "HORIZONTAL_BAR", + * chartConfig: { + * row_limit: 10 + * } + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/unstable/dashboard-widgets"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/unstable/dashboard-widgets."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a dashboard widget by id. + * + * The response may use `view: traces` for legacy widgets. + * + * @param {string} widgetId + * @param {DashboardWidgets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboardWidgets.get("widgetId") + */ + get(widgetId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(widgetId, requestOptions)); + } + async __get(widgetId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboard-widgets/${encodeURIComponent(widgetId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/unstable/dashboard-widgets/{widgetId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Update a dashboard widget. + * + * All fields are optional; at least one field is required. + * Changing `chartType` without sending `chartConfig` resets the config + * to the new chart type's defaults. When `chartConfig.type` is given + * it must match the widget's (possibly updated) `chartType`. + * + * `view` cannot be changed to the legacy `traces` value. Existing + * `traces` widgets may be updated on other fields. + * + * @param {string} widgetId + * @param {LangfuseAPI.unstable.UpdateDashboardWidgetRequest} request + * @param {DashboardWidgets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboardWidgets.update("widgetId", { + * name: undefined, + * description: undefined, + * view: undefined, + * dimensions: undefined, + * metrics: undefined, + * filters: undefined, + * chartType: undefined, + * chartConfig: undefined + * }) + */ + update(widgetId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__update(widgetId, request, requestOptions)); + } + async __update(widgetId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboard-widgets/${encodeURIComponent(widgetId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/unstable/dashboard-widgets/{widgetId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a dashboard widget. + * + * The API returns `409` while the widget is still placed on a dashboard. + * Remove those placements first. + * + * @param {string} widgetId + * @param {DashboardWidgets.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.ConflictError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboardWidgets.delete("widgetId") + */ + delete(widgetId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(widgetId, requestOptions)); + } + async __delete(widgetId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboard-widgets/${encodeURIComponent(widgetId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 409: throw new unstable_exports.ConflictError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/unstable/dashboard-widgets/{widgetId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Dashboards = class { + constructor(_options) { + this._options = _options; + } + /** + * List dashboards in the project, ordered by most recently updated + * first. + * + * @param {LangfuseAPI.unstable.ListDashboardsRequest} request + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.list() + */ + list(request = {}, requestOptions) { + return HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + async __list(request = {}, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + const { page, limit } = request; + const _queryParams = {}; + if (page != null) _queryParams["page"] = page.toString(); + if (limit != null) _queryParams["limit"] = limit.toString(); + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/unstable/dashboards"), + method: "GET", + headers: _headers, + queryParameters: { + ..._queryParams, + ...requestOptions == null ? void 0 : requestOptions.queryParams + }, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/unstable/dashboards."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Create a dashboard. + * + * @param {LangfuseAPI.unstable.CreateDashboardRequest} request + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.create({ + * name: "name", + * description: undefined, + * definition: undefined, + * filters: undefined + * }) + */ + create(request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + async __create(request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), "/api/public/unstable/dashboards"), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/unstable/dashboards."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Get a dashboard by id. + * + * @param {string} dashboardId + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.get("dashboardId") + */ + get(dashboardId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__get(dashboardId, requestOptions)); + } + async __get(dashboardId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboards/${encodeURIComponent(dashboardId)}`), + method: "GET", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling GET /api/public/unstable/dashboards/{dashboardId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Update a dashboard's name, description, definition, or filters. + * + * @param {string} dashboardId + * @param {LangfuseAPI.unstable.UpdateDashboardRequest} request + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.update("dashboardId", { + * name: undefined, + * description: undefined, + * definition: undefined, + * filters: undefined + * }) + */ + update(dashboardId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__update(dashboardId, request, requestOptions)); + } + async __update(dashboardId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboards/${encodeURIComponent(dashboardId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/unstable/dashboards/{dashboardId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Delete a dashboard. + * + * @param {string} dashboardId + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.delete("dashboardId") + */ + delete(dashboardId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__delete(dashboardId, requestOptions)); + } + async __delete(dashboardId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboards/${encodeURIComponent(dashboardId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/unstable/dashboards/{dashboardId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Add a placement to a dashboard grid (see `DashboardPlacement` for + * grid semantics). + * + * `id` and the position fields are optional: when omitted, the + * placement gets a server-generated id and is appended below all + * existing tiles as a 6x6 tile. Returns the created placement. + * + * The referenced widget must exist in the same project or be a + * Langfuse-managed widget. The API returns `409` if a placement with + * the same `id` already exists on the dashboard. + * + * @param {string} dashboardId + * @param {LangfuseAPI.unstable.CreateDashboardPlacementRequest} request + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.ConflictError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.addPlacement("dashboardId", { + * type: "widget", + * id: undefined, + * widgetId: "widgetId", + * x: undefined, + * y: undefined, + * width: undefined, + * height: undefined + * }) + */ + addPlacement(dashboardId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__addPlacement(dashboardId, request, requestOptions)); + } + async __addPlacement(dashboardId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboards/${encodeURIComponent(dashboardId)}/placements`), + method: "POST", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 409: throw new unstable_exports.ConflictError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling POST /api/public/unstable/dashboards/{dashboardId}/placements."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Move or resize a placement. All fields are optional; at least one is + * required. Omitted fields keep their current value. The placement's + * content (widget/preset reference) and id cannot change — delete and + * re-add the placement to swap content. Returns the updated placement. + * + * @param {string} dashboardId + * @param {string} placementId + * @param {LangfuseAPI.unstable.UpdateDashboardPlacementRequest} request + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.updatePlacement("dashboardId", "placementId", { + * x: undefined, + * y: undefined, + * width: undefined, + * height: undefined + * }) + */ + updatePlacement(dashboardId, placementId, request, requestOptions) { + return HttpResponsePromise.fromPromise(this.__updatePlacement(dashboardId, placementId, request, requestOptions)); + } + async __updatePlacement(dashboardId, placementId, request, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboards/${encodeURIComponent(dashboardId)}/placements/${encodeURIComponent(placementId)}`), + method: "PATCH", + headers: _headers, + contentType: "application/json", + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + requestType: "json", + body: request, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling PATCH /api/public/unstable/dashboards/{dashboardId}/placements/{placementId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + /** + * Remove a placement from a dashboard grid without deleting the referenced widget. + * + * @param {string} dashboardId + * @param {string} placementId + * @param {Dashboards.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link LangfuseAPI.unstable.BadRequestError} + * @throws {@link LangfuseAPI.unstable.UnauthorizedError} + * @throws {@link LangfuseAPI.unstable.AccessDeniedError} + * @throws {@link LangfuseAPI.unstable.NotFoundError} + * @throws {@link LangfuseAPI.unstable.MethodNotAllowedError} + * @throws {@link LangfuseAPI.unstable.TooManyRequestsError} + * @throws {@link LangfuseAPI.unstable.InternalServerError} + * @throws {@link LangfuseAPI.Error} + * @throws {@link LangfuseAPI.UnauthorizedError} + * @throws {@link LangfuseAPI.AccessDeniedError} + * @throws {@link LangfuseAPI.MethodNotAllowedError} + * @throws {@link LangfuseAPI.NotFoundError} + * + * @example + * await client.unstable.dashboards.deletePlacement("dashboardId", "placementId") + */ + deletePlacement(dashboardId, placementId, requestOptions) { + return HttpResponsePromise.fromPromise(this.__deletePlacement(dashboardId, placementId, requestOptions)); + } + async __deletePlacement(dashboardId, placementId, requestOptions) { + var _a2, _b, _c, _d, _e, _f, _g, _h; + let _headers = mergeHeaders$1((_a2 = this._options) == null ? void 0 : _a2.headers, mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "X-Langfuse-Sdk-Name": (_c = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkName) != null ? _c : (_b = this._options) == null ? void 0 : _b.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": (_e = requestOptions == null ? void 0 : requestOptions.xLangfuseSdkVersion) != null ? _e : (_d = this._options) == null ? void 0 : _d.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": (_g = requestOptions == null ? void 0 : requestOptions.xLangfusePublicKey) != null ? _g : (_f = this._options) == null ? void 0 : _f.xLangfusePublicKey + }), requestOptions == null ? void 0 : requestOptions.headers); + const _response = await fetcher({ + url: url_exports.join((_h = await Supplier.get(this._options.baseUrl)) != null ? _h : await Supplier.get(this._options.environment), `/api/public/unstable/dashboards/${encodeURIComponent(dashboardId)}/placements/${encodeURIComponent(placementId)}`), + method: "DELETE", + headers: _headers, + queryParameters: requestOptions == null ? void 0 : requestOptions.queryParams, + timeoutMs: (requestOptions == null ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4, + maxRetries: requestOptions == null ? void 0 : requestOptions.maxRetries, + abortSignal: requestOptions == null ? void 0 : requestOptions.abortSignal + }); + if (_response.ok) return { + data: _response.body, + rawResponse: _response.rawResponse + }; + if (_response.error.reason === "status-code") switch (_response.error.statusCode) { + case 400: throw new unstable_exports.BadRequestError(_response.error.body, _response.rawResponse); + case 401: throw new unstable_exports.UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new unstable_exports.AccessDeniedError(_response.error.body, _response.rawResponse); + case 404: throw new unstable_exports.NotFoundError(_response.error.body, _response.rawResponse); + case 405: throw new unstable_exports.MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 429: throw new unstable_exports.TooManyRequestsError(_response.error.body, _response.rawResponse); + case 500: throw new unstable_exports.InternalServerError(_response.error.body, _response.rawResponse); + case 400: throw new Error2(_response.error.body, _response.rawResponse); + case 401: throw new UnauthorizedError(_response.error.body, _response.rawResponse); + case 403: throw new AccessDeniedError(_response.error.body, _response.rawResponse); + case 405: throw new MethodNotAllowedError(_response.error.body, _response.rawResponse); + case 404: throw new NotFoundError(_response.error.body, _response.rawResponse); + default: throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse + }); + } + switch (_response.error.reason) { + case "non-json": throw new LangfuseAPIError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse + }); + case "timeout": throw new LangfuseAPITimeoutError("Timeout exceeded when calling DELETE /api/public/unstable/dashboards/{dashboardId}/placements/{placementId}."); + case "unknown": throw new LangfuseAPIError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse + }); + } + } + async _getAuthorizationHeader() { + const username = await Supplier.get(this._options.username); + const password = await Supplier.get(this._options.password); + if (username != null && password != null) return BasicAuth.toAuthorizationHeader({ + username, + password + }); + } +}; +var Unstable = class { + constructor(_options) { + this._options = _options; + } + get dashboardWidgets() { + var _a2; + return (_a2 = this._dashboardWidgets) != null ? _a2 : this._dashboardWidgets = new DashboardWidgets(this._options); + } + get dashboards() { + var _a2; + return (_a2 = this._dashboards) != null ? _a2 : this._dashboards = new Dashboards(this._options); + } +}; +var LangfuseAPIClient = class { + constructor(_options) { + this._options = { + ..._options, + headers: mergeHeaders$1({ + "X-Langfuse-Sdk-Name": _options == null ? void 0 : _options.xLangfuseSdkName, + "X-Langfuse-Sdk-Version": _options == null ? void 0 : _options.xLangfuseSdkVersion, + "X-Langfuse-Public-Key": _options == null ? void 0 : _options.xLangfusePublicKey + }, _options == null ? void 0 : _options.headers) + }; + } + get annotationQueues() { + var _a2; + return (_a2 = this._annotationQueues) != null ? _a2 : this._annotationQueues = new AnnotationQueues(this._options); + } + get blobStorageIntegrations() { + var _a2; + return (_a2 = this._blobStorageIntegrations) != null ? _a2 : this._blobStorageIntegrations = new BlobStorageIntegrations(this._options); + } + get comments() { + var _a2; + return (_a2 = this._comments) != null ? _a2 : this._comments = new Comments(this._options); + } + get datasetItems() { + var _a2; + return (_a2 = this._datasetItems) != null ? _a2 : this._datasetItems = new DatasetItems(this._options); + } + get datasetRunItems() { + var _a2; + return (_a2 = this._datasetRunItems) != null ? _a2 : this._datasetRunItems = new DatasetRunItems(this._options); + } + get datasets() { + var _a2; + return (_a2 = this._datasets) != null ? _a2 : this._datasets = new Datasets(this._options); + } + get evaluationRules() { + var _a2; + return (_a2 = this._evaluationRules) != null ? _a2 : this._evaluationRules = new EvaluationRules(this._options); + } + get evaluators() { + var _a2; + return (_a2 = this._evaluators) != null ? _a2 : this._evaluators = new Evaluators(this._options); + } + get experiments() { + var _a2; + return (_a2 = this._experiments) != null ? _a2 : this._experiments = new Experiments(this._options); + } + get feedback() { + var _a2; + return (_a2 = this._feedback) != null ? _a2 : this._feedback = new Feedback(this._options); + } + get health() { + var _a2; + return (_a2 = this._health) != null ? _a2 : this._health = new Health(this._options); + } + get ingestion() { + var _a2; + return (_a2 = this._ingestion) != null ? _a2 : this._ingestion = new Ingestion(this._options); + } + get legacy() { + var _a2; + return (_a2 = this._legacy) != null ? _a2 : this._legacy = new Legacy(this._options); + } + get llmConnections() { + var _a2; + return (_a2 = this._llmConnections) != null ? _a2 : this._llmConnections = new LlmConnections(this._options); + } + get media() { + var _a2; + return (_a2 = this._media) != null ? _a2 : this._media = new Media(this._options); + } + get metrics() { + var _a2; + return (_a2 = this._metrics) != null ? _a2 : this._metrics = new Metrics(this._options); + } + get models() { + var _a2; + return (_a2 = this._models) != null ? _a2 : this._models = new Models(this._options); + } + get observations() { + var _a2; + return (_a2 = this._observations) != null ? _a2 : this._observations = new Observations(this._options); + } + get opentelemetry() { + var _a2; + return (_a2 = this._opentelemetry) != null ? _a2 : this._opentelemetry = new Opentelemetry(this._options); + } + get organizations() { + var _a2; + return (_a2 = this._organizations) != null ? _a2 : this._organizations = new Organizations(this._options); + } + get projects() { + var _a2; + return (_a2 = this._projects) != null ? _a2 : this._projects = new Projects(this._options); + } + get promptVersion() { + var _a2; + return (_a2 = this._promptVersion) != null ? _a2 : this._promptVersion = new PromptVersion(this._options); + } + get prompts() { + var _a2; + return (_a2 = this._prompts) != null ? _a2 : this._prompts = new Prompts(this._options); + } + get scim() { + var _a2; + return (_a2 = this._scim) != null ? _a2 : this._scim = new Scim(this._options); + } + get scoreConfigs() { + var _a2; + return (_a2 = this._scoreConfigs) != null ? _a2 : this._scoreConfigs = new ScoreConfigs(this._options); + } + get scoresV3() { + var _a2; + return (_a2 = this._scoresV3) != null ? _a2 : this._scoresV3 = new ScoresV3(this._options); + } + get scores() { + var _a2; + return (_a2 = this._scores) != null ? _a2 : this._scores = new Scores(this._options); + } + get sessions() { + var _a2; + return (_a2 = this._sessions) != null ? _a2 : this._sessions = new Sessions(this._options); + } + get trace() { + var _a2; + return (_a2 = this._trace) != null ? _a2 : this._trace = new Trace(this._options); + } + get unstable() { + var _a2; + return (_a2 = this._unstable) != null ? _a2 : this._unstable = new Unstable(this._options); + } +}; +var LangfuseMedia = class { + /** + * Creates a new LangfuseMedia instance. + * + * @param params - Media parameters specifying the source and content + * + * @example + * ```typescript + * // Create from base64 data URI + * const media = new LangfuseMedia({ + * source: "base64_data_uri", + * base64DataUri: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ..." + * }); + * ``` + */ + constructor(params) { + const { source } = params; + this._source = source; + if (source === "base64_data_uri") { + const [contentBytesParsed, contentTypeParsed] = this.parseBase64DataUri(params.base64DataUri); + this._contentBytes = contentBytesParsed; + this._contentType = contentTypeParsed; + } else { + this._contentBytes = params.contentBytes; + this._contentType = params.contentType; + } + } + /** + * Parses a base64 data URI to extract content bytes and type. + * + * @param data - The base64 data URI string + * @returns Tuple of [contentBytes, contentType] or [undefined, undefined] on error + * @private + */ + parseBase64DataUri(data) { + try { + if (!data || typeof data !== "string") throw new Error("Data URI is not a string"); + if (!data.startsWith("data:")) throw new Error("Data URI does not start with 'data:'"); + const [header, actualData] = data.slice(5).split(",", 2); + if (!header || !actualData) throw new Error("Invalid URI"); + const headerParts = header.split(";"); + if (!headerParts.includes("base64")) throw new Error("Data is not base64 encoded"); + const contentType = headerParts[0]; + if (!contentType) throw new Error("Content type is empty"); + return [base64ToBytes(actualData), contentType]; + } catch (error) { + getGlobalLogger().error("Error parsing base64 data URI", error); + return [void 0, void 0]; + } + } + /** + * Gets a unique identifier for this media based on its content hash. + * + * The ID is derived from the first 22 characters of the URL-safe base64-encoded + * SHA-256 hash of the content. + * + * @returns The unique media ID, or null if hash generation failed + * + * @example + * ```typescript + * const media = new LangfuseMedia({...}); + * console.log(media.id); // "A1B2C3D4E5F6G7H8I9J0K1" + * ``` + */ + async getId() { + const contentSha256Hash = await this.getSha256Hash(); + if (!contentSha256Hash) return null; + return contentSha256Hash.replaceAll("+", "-").replaceAll("/", "_").slice(0, 22); + } + /** + * Gets the length of the media content in bytes. + * + * @returns The content length in bytes, or undefined if no content is available + */ + get contentLength() { + var _a2; + return (_a2 = this._contentBytes) == null ? void 0 : _a2.length; + } + /** + * Gets the SHA-256 hash of the media content. + * + * The hash is used for content integrity verification and generating unique media IDs. + * Returns undefined if crypto is not available or hash generation fails. + * + * @returns The base64-encoded SHA-256 hash, or undefined if unavailable + */ + async getSha256Hash() { + if (!this._contentBytes) return; + try { + const hash = await crypto.subtle.digest("SHA-256", this._contentBytes); + return bytesToBase64(new Uint8Array(hash)); + } catch (error) { + getGlobalLogger().warn("[Langfuse] Failed to generate SHA-256 hash for media content:", error); + return; + } + } + /** + * Gets the media reference tag for embedding in trace data. + * + * The tag format is: `@@@langfuseMedia:type=|id=|source=@@@` + * This tag can be embedded in trace attributes and will be replaced with actual + * media content when the trace is viewed in Langfuse. + * + * @returns The media reference tag, or null if required data is missing + * + * @example + * ```typescript + * const media = new LangfuseMedia({...}); + * console.log(media.tag); + * // "@@@langfuseMedia:type=image/png|id=A1B2C3D4E5F6G7H8I9J0K1|source=base64_data_uri@@@" + * ``` + */ + async getTag() { + const id = await this.getId(); + if (!this._contentType || !this._source || !id) return null; + return `@@@langfuseMedia:type=${this._contentType}|id=${id}|source=${this._source}@@@`; + } + /** + * Gets the media content as a base64 data URI. + * + * @returns The complete data URI string, or null if no content is available + * + * @example + * ```typescript + * const media = new LangfuseMedia({...}); + * console.log(media.base64DataUri); + * // "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB..." + * ``` + */ + get base64DataUri() { + if (!this._contentBytes) return null; + return `data:${this._contentType};base64,${bytesToBase64(this._contentBytes)}`; + } + /** + * Serializes the media to JSON (returns the base64 data URI). + * + * @returns The base64 data URI, or null if no content is available + */ + toJSON() { + return this.base64DataUri; + } +}; +async function uploadMedia(params) { + var _a2; + const { apiClient, media, traceId, observationId, datasetId, datasetItemId, field, maxRetries = 3, baseDelay = 1e3 } = params; + const logger = (_a2 = params.logger) != null ? _a2 : getGlobalLogger(); + const contentSha256Hash = await media.getSha256Hash(); + if (!media.contentLength || !media._contentType || !contentSha256Hash || !media._contentBytes) throw new Error("Cannot upload media: media content is incomplete."); + const { uploadUrl, mediaId } = await apiClient.media.getUploadUrl({ + contentLength: media.contentLength, + traceId, + observationId, + datasetId, + datasetItemId, + field, + contentType: media._contentType, + sha256Hash: contentSha256Hash + }); + if (!uploadUrl) { + logger.debug(`Media status: Media with ID ${mediaId} already uploaded. Skipping duplicate upload.`); + return; + } + const clientSideMediaId = await media.getId(); + if (clientSideMediaId !== mediaId) throw new Error(`Media integrity error: Media ID mismatch between SDK (${clientSideMediaId}) and Server (${mediaId}). Upload cancelled.`); + logger.debug(`Uploading media ${mediaId}...`); + const startTime = Date.now(); + const uploadResponse = await uploadWithBackoff({ + uploadUrl, + contentBytes: media._contentBytes, + contentType: media._contentType, + contentSha256Hash, + maxRetries, + baseDelay + }); + if (!uploadResponse) throw new Error("Media upload process failed"); + const uploadSucceeded = uploadResponse.status === 200 || uploadResponse.status === 201; + await apiClient.media.patch(mediaId, { + uploadedAt: (/* @__PURE__ */ new Date()).toISOString(), + uploadHttpStatus: uploadResponse.status, + uploadHttpError: await uploadResponse.text(), + uploadTimeMs: Date.now() - startTime + }); + logger.debug(`Media upload status reported for ${mediaId}`); + if (!uploadSucceeded) throw new Error(`Media upload failed with HTTP ${uploadResponse.status} after ${maxRetries} retries.`); +} +async function uploadWithBackoff(params) { + const { uploadUrl, contentType, contentSha256Hash, contentBytes, maxRetries, baseDelay } = params; + for (let attempt = 0; attempt <= maxRetries; attempt++) try { + let parsedHostname; + try { + parsedHostname = new URL(uploadUrl).hostname; + } catch { + parsedHostname = ""; + } + const headers = parsedHostname === "storage.googleapis.com" || parsedHostname.endsWith(".storage.googleapis.com") ? { "Content-Type": contentType } : { + "Content-Type": contentType, + "x-amz-checksum-sha256": contentSha256Hash, + "x-ms-blob-type": "BlockBlob" + }; + const uploadResponse = await fetch(uploadUrl, { + method: "PUT", + body: contentBytes, + headers + }); + if (attempt < maxRetries && uploadResponse.status !== 200 && uploadResponse.status !== 201) throw new Error(`Upload failed with status ${uploadResponse.status}`); + return uploadResponse; + } catch (e) { + if (attempt === maxRetries) throw e; + const delay = baseDelay * Math.pow(2, attempt); + const jitter = Math.random() * 1e3; + await new Promise((resolve) => setTimeout(resolve, delay + jitter)); + } +} +var experimentKeys = [ + "experimentId", + "experimentName", + "experimentMetadata", + "experimentDatasetId", + "experimentItemId", + "experimentItemMetadata", + "experimentItemRootObservationId" +]; +var LangfuseOtelContextKeys = { + userId: createContextKey("langfuse_user_id"), + sessionId: createContextKey("langfuse_session_id"), + metadata: createContextKey("langfuse_metadata"), + version: createContextKey("langfuse_version"), + tags: createContextKey("langfuse_tags"), + traceName: createContextKey("langfuse_trace_name"), + environment: createContextKey("langfuse_environment"), + promptName: createContextKey("langfuse_prompt_name"), + promptVersion: createContextKey("langfuse_prompt_version"), + experimentId: createContextKey("langfuse_experiment_id"), + experimentName: createContextKey("langfuse_experiment_name"), + experimentMetadata: createContextKey("langfuse_experiment_metadata"), + experimentDatasetId: createContextKey("langfuse_experiment_dataset_id"), + experimentItemId: createContextKey("langfuse_experiment_item_id"), + experimentItemMetadata: createContextKey("langfuse_experiment_item_metadata"), + experimentItemRootObservationId: createContextKey("langfuse_experiment_item_root_observation_id") +}; +var LANGFUSE_BAGGAGE_PREFIX = "langfuse_"; +var LANGFUSE_BAGGAGE_TAGS_SEPARATOR = ","; +var LANGFUSE_TRACE_ID_BAGGAGE_KEY = "langfuse_trace_id"; +function getLangfuseTraceIdFromBaggage(context) { + const baggage = propagation.getBaggage(context); + const entry = baggage == null ? void 0 : baggage.getEntry(LANGFUSE_TRACE_ID_BAGGAGE_KEY); + if (!(entry == null ? void 0 : entry.value)) return void 0; + return entry.value.toLowerCase(); +} +function propagateAttributes(params, fn) { + var _a2; + let context$1 = context.active(); + const span = trace.getActiveSpan(); + const asBaggage = (_a2 = params.asBaggage) != null ? _a2 : false; + const { userId, sessionId, metadata, version, tags, traceName, environment, prompt, _internalExperiment } = params; + if (userId) { + if (isValidPropagatedString({ + value: userId, + attributeName: "userId" + })) context$1 = setPropagatedAttribute({ + key: "userId", + value: userId, + context: context$1, + span, + asBaggage + }); + } + if (sessionId) { + if (isValidPropagatedString({ + value: sessionId, + attributeName: "sessionId" + })) context$1 = setPropagatedAttribute({ + key: "sessionId", + value: sessionId, + context: context$1, + span, + asBaggage + }); + } + if (version) { + if (isValidPropagatedString({ + value: version, + attributeName: "version" + })) context$1 = setPropagatedAttribute({ + key: "version", + value: version, + context: context$1, + span, + asBaggage + }); + } + if (traceName) { + if (isValidPropagatedString({ + value: traceName, + attributeName: "traceName" + })) context$1 = setPropagatedAttribute({ + key: "traceName", + value: traceName, + context: context$1, + span, + asBaggage + }); + } + if (environment !== void 0 && isValidEnvironment(environment)) context$1 = setPropagatedAttribute({ + key: "environment", + value: environment, + context: context$1, + span, + asBaggage + }); + if (tags && tags.length > 0) { + const validTags = tags.filter((tag) => isValidPropagatedString({ + value: tag, + attributeName: "tag" + })); + if (validTags.length > 0) context$1 = setPropagatedAttribute({ + key: "tags", + value: validTags, + context: context$1, + span, + asBaggage + }); + } + if (metadata) { + const validatedMetadata = {}; + for (const [key, value] of Object.entries(metadata)) if (isValidPropagatedString({ + value, + attributeName: `metadata.${key}` + })) validatedMetadata[key] = value; + if (Object.keys(validatedMetadata).length > 0) context$1 = setPropagatedAttribute({ + key: "metadata", + value: validatedMetadata, + context: context$1, + span, + asBaggage + }); + } + if (prompt) { + const propagatedPrompt = extractPropagatedPrompt(prompt); + if (propagatedPrompt) { + context$1 = setPropagatedAttribute({ + key: "promptName", + value: propagatedPrompt.name, + context: context$1, + span, + asBaggage + }); + context$1 = setPropagatedAttribute({ + key: "promptVersion", + value: propagatedPrompt.version, + context: context$1, + span, + asBaggage + }); + } + } + if (_internalExperiment) { + for (const [key, value] of Object.entries(_internalExperiment)) if (value !== void 0) context$1 = setPropagatedAttribute({ + key, + value, + context: context$1, + span, + asBaggage + }); + } + return context.with(context$1, fn); +} +function extractPropagatedPrompt(prompt) { + const logger = getGlobalLogger(); + const { name, version: rawVersion, isFallback } = prompt; + if (isFallback) { + logger.debug("Propagated prompt is a fallback prompt. Skipping prompt linking."); + return null; + } + if (typeof name !== "string" || name.length === 0) { + logger.warn("Propagated 'prompt' has no valid 'name' (non-empty string required). Dropping prompt link."); + return null; + } + const version = typeof rawVersion === "string" && /^\d+$/.test(rawVersion) ? Number(rawVersion) : rawVersion; + if (typeof version !== "number" || !Number.isInteger(version)) { + logger.warn("Propagated 'prompt' has no valid 'version' (integer required). Dropping prompt link."); + return null; + } + return { + name, + version + }; +} +function getPropagatedAttributesFromContext(context) { + const propagatedAttributes = {}; + const baggage = propagation.getBaggage(context); + if (baggage) baggage.getAllEntries().forEach(([baggageKey, baggageEntry]) => { + if (baggageKey === "langfuse_trace_id") return; + if (baggageKey.startsWith(LANGFUSE_BAGGAGE_PREFIX)) { + const spanKey = getSpanKeyFromBaggageKey(baggageKey); + if (spanKey) { + if (spanKey === "langfuse.environment") { + if (isValidEnvironment(baggageEntry.value)) propagatedAttributes[spanKey] = baggageEntry.value; + return; + } + if (spanKey === "langfuse.observation.prompt.version" && /^\d+$/.test(baggageEntry.value)) { + propagatedAttributes[spanKey] = Number(baggageEntry.value); + return; + } + const isMergedTags = baggageKey == getBaggageKeyForPropagatedKey("tags"); + propagatedAttributes[spanKey] = isMergedTags ? baggageEntry.value.split(LANGFUSE_BAGGAGE_TAGS_SEPARATOR) : baggageEntry.value; + } + } + }); + const userId = context.getValue(LangfuseOtelContextKeys["userId"]); + if (userId && typeof userId === "string") { + const spanKey = getSpanKeyForPropagatedKey("userId"); + propagatedAttributes[spanKey] = userId; + } + const sessionId = context.getValue(LangfuseOtelContextKeys["sessionId"]); + if (sessionId && typeof sessionId === "string") { + const spanKey = getSpanKeyForPropagatedKey("sessionId"); + propagatedAttributes[spanKey] = sessionId; + } + const version = context.getValue(LangfuseOtelContextKeys["version"]); + if (version && typeof version === "string") { + const spanKey = getSpanKeyForPropagatedKey("version"); + propagatedAttributes[spanKey] = version; + } + const traceName = context.getValue(LangfuseOtelContextKeys["traceName"]); + if (traceName && typeof traceName === "string") { + const spanKey = getSpanKeyForPropagatedKey("traceName"); + propagatedAttributes[spanKey] = traceName; + } + const environment = context.getValue(LangfuseOtelContextKeys["environment"]); + if (isValidEnvironment(environment)) propagatedAttributes["langfuse.environment"] = environment; + const tags = context.getValue(LangfuseOtelContextKeys["tags"]); + if (tags && Array.isArray(tags)) { + const spanKey = getSpanKeyForPropagatedKey("tags"); + propagatedAttributes[spanKey] = tags; + } + const promptName = context.getValue(LangfuseOtelContextKeys["promptName"]); + if (promptName && typeof promptName === "string") { + const spanKey = getSpanKeyForPropagatedKey("promptName"); + propagatedAttributes[spanKey] = promptName; + } + const promptVersion = context.getValue(LangfuseOtelContextKeys["promptVersion"]); + if (typeof promptVersion === "number") { + const spanKey = getSpanKeyForPropagatedKey("promptVersion"); + propagatedAttributes[spanKey] = promptVersion; + } + const metadata = context.getValue(LangfuseOtelContextKeys["metadata"]); + if (metadata && typeof metadata === "object" && metadata !== null) for (const [k, v] of Object.entries(metadata)) { + const spanKey = `langfuse.trace.metadata.${k}`; + propagatedAttributes[spanKey] = String(v); + } + for (const key of experimentKeys) { + const contextKey = LangfuseOtelContextKeys[key]; + const value = context.getValue(contextKey); + if (value && typeof value === "string") { + const spanKey = getSpanKeyForPropagatedKey(key); + propagatedAttributes[spanKey] = value; + } + } + if (propagatedAttributes[getSpanKeyForPropagatedKey("experimentItemRootObservationId")]) propagatedAttributes["langfuse.environment"] = LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT; + return propagatedAttributes; +} +function setPropagatedAttribute(params) { + const { key, value, span, asBaggage } = params; + let context = params.context; + let mergedMetadata = key === "metadata" ? getContextMergedMetadata(context, value) : {}; + let mergedTags = key === "tags" ? getContextMergedTags(context, value) : []; + const contextKey = getContextKeyForPropagatedKey(key); + if (key === "metadata") context = context.setValue(contextKey, mergedMetadata); + else if (key === "tags") context = context.setValue(contextKey, mergedTags); + else context = context.setValue(contextKey, value); + if (span && span.isRecording()) { + if (key === "metadata") for (const [k, v] of Object.entries(mergedMetadata)) span.setAttribute(`langfuse.trace.metadata.${k}`, v); + else if (key === "tags") { + const spanKey = getSpanKeyForPropagatedKey(key); + span.setAttribute(spanKey, mergedTags); + } else { + const spanKey = getSpanKeyForPropagatedKey(key); + span.setAttribute(spanKey, value); + } + } + if (asBaggage) { + const baggageKey = getBaggageKeyForPropagatedKey(key); + let baggage = propagation.getBaggage(context) || propagation.createBaggage(); + if (key === "metadata") for (const [k, v] of Object.entries(mergedMetadata)) baggage = baggage.setEntry(`${baggageKey}_${k}`, { value: v }); + else if (key === "tags") baggage = baggage.setEntry(baggageKey, { value: mergedTags.join(LANGFUSE_BAGGAGE_TAGS_SEPARATOR) }); + else baggage = baggage.setEntry(baggageKey, { value: String(value) }); + context = propagation.setBaggage(context, baggage); + } + return context; +} +function getContextMergedTags(context, newTags) { + const existingTags = context.getValue(LangfuseOtelContextKeys["tags"]); + if (existingTags && Array.isArray(existingTags)) return [.../* @__PURE__ */ new Set([...existingTags, ...newTags])]; + else return newTags; +} +function getContextMergedMetadata(context, newMetadata) { + const existingMetadata = context.getValue(LangfuseOtelContextKeys["metadata"]); + if (existingMetadata && typeof existingMetadata === "object" && existingMetadata !== null && !Array.isArray(existingMetadata)) return { + ...existingMetadata, + ...newMetadata + }; + else return newMetadata; +} +function isValidPropagatedString(params) { + const logger = getGlobalLogger(); + const { value, attributeName } = params; + if (typeof value !== "string") { + logger.warn(`Propagated attribute '${attributeName}' must be a string. Dropping value.`); + return false; + } + if (value.length > 200) { + logger.warn(`Propagated attribute '${attributeName}' value is over 200 characters (${value.length} chars). Dropping value.`); + return false; + } + return true; +} +var ENVIRONMENT_VALUE_PATTERN = /^(?!langfuse)[a-z0-9_-]+$/; +function isValidEnvironment(value) { + const logger = getGlobalLogger(); + if (typeof value !== "string") { + if (value !== void 0) logger.warn("Propagated attribute 'environment' must be a string. Dropping value."); + return false; + } + if (value.length > 40) { + logger.warn(`Propagated attribute 'environment' value is over 40 characters (${value.length} chars). Dropping value.`); + return false; + } + if (!ENVIRONMENT_VALUE_PATTERN.test(value)) { + logger.warn("Propagated attribute 'environment' must be a lowercase alphanumeric string with optional hyphens or underscores and must not start with 'langfuse'. Dropping value."); + return false; + } + return true; +} +function getContextKeyForPropagatedKey(key) { + return LangfuseOtelContextKeys[key]; +} +function getSpanKeyForPropagatedKey(key) { + switch (key) { + case "userId": return "user.id"; + case "sessionId": return "session.id"; + case "version": return "langfuse.version"; + case "traceName": return "langfuse.trace.name"; + case "environment": return "langfuse.environment"; + case "metadata": return "langfuse.trace.metadata"; + case "tags": return "langfuse.trace.tags"; + case "promptName": return "langfuse.observation.prompt.name"; + case "promptVersion": return "langfuse.observation.prompt.version"; + case "experimentId": return "langfuse.experiment.id"; + case "experimentName": return "langfuse.experiment.name"; + case "experimentMetadata": return "langfuse.experiment.metadata"; + case "experimentDatasetId": return "langfuse.experiment.dataset.id"; + case "experimentItemId": return "langfuse.experiment.item.id"; + case "experimentItemMetadata": return "langfuse.experiment.item.metadata"; + case "experimentItemRootObservationId": return "langfuse.experiment.item.root_observation_id"; + default: throw Error("Unhandled propagated key", key); + } +} +function getBaggageKeyForPropagatedKey(key) { + switch (key) { + case "userId": return `${LANGFUSE_BAGGAGE_PREFIX}user_id`; + case "sessionId": return `${LANGFUSE_BAGGAGE_PREFIX}session_id`; + case "version": return `${LANGFUSE_BAGGAGE_PREFIX}version`; + case "traceName": return `${LANGFUSE_BAGGAGE_PREFIX}trace_name`; + case "environment": return `${LANGFUSE_BAGGAGE_PREFIX}environment`; + case "metadata": return `${LANGFUSE_BAGGAGE_PREFIX}metadata`; + case "tags": return `${LANGFUSE_BAGGAGE_PREFIX}tags`; + case "promptName": return `${LANGFUSE_BAGGAGE_PREFIX}prompt_name`; + case "promptVersion": return `${LANGFUSE_BAGGAGE_PREFIX}prompt_version`; + case "experimentId": return `${LANGFUSE_BAGGAGE_PREFIX}experiment_id`; + case "experimentName": return `${LANGFUSE_BAGGAGE_PREFIX}experiment_name`; + case "experimentMetadata": return `${LANGFUSE_BAGGAGE_PREFIX}experiment_metadata`; + case "experimentDatasetId": return `${LANGFUSE_BAGGAGE_PREFIX}experiment_dataset_id`; + case "experimentItemId": return `${LANGFUSE_BAGGAGE_PREFIX}experiment_item_id`; + case "experimentItemMetadata": return `${LANGFUSE_BAGGAGE_PREFIX}experiment_item_metadata`; + case "experimentItemRootObservationId": return `${LANGFUSE_BAGGAGE_PREFIX}experiment_item_root_observation_id`; + default: throw Error("Unhandled propagated key", key); + } +} +function getSpanKeyFromBaggageKey(baggageKey) { + if (!baggageKey.startsWith(LANGFUSE_BAGGAGE_PREFIX)) return; + const suffix = baggageKey.slice(LANGFUSE_BAGGAGE_PREFIX.length); + if (suffix.startsWith("metadata_")) return `langfuse.trace.metadata.${suffix.slice(9)}`; + switch (suffix) { + case "user_id": return getSpanKeyForPropagatedKey("userId"); + case "session_id": return getSpanKeyForPropagatedKey("sessionId"); + case "version": return getSpanKeyForPropagatedKey("version"); + case "trace_name": return getSpanKeyForPropagatedKey("traceName"); + case "environment": return getSpanKeyForPropagatedKey("environment"); + case "tags": return getSpanKeyForPropagatedKey("tags"); + case "prompt_name": return getSpanKeyForPropagatedKey("promptName"); + case "prompt_version": return getSpanKeyForPropagatedKey("promptVersion"); + case "experiment_id": return getSpanKeyForPropagatedKey("experimentId"); + case "experiment_name": return getSpanKeyForPropagatedKey("experimentName"); + case "experiment_metadata": return getSpanKeyForPropagatedKey("experimentMetadata"); + case "experiment_dataset_id": return getSpanKeyForPropagatedKey("experimentDatasetId"); + case "experiment_item_id": return getSpanKeyForPropagatedKey("experimentItemId"); + case "experiment_item_metadata": return getSpanKeyForPropagatedKey("experimentItemMetadata"); + case "experiment_item_root_observation_id": return getSpanKeyForPropagatedKey("experimentItemRootObservationId"); + } +} + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js +var require_suppress_tracing = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = void 0; + const SUPPRESS_TRACING_KEY = (0, (init_esm$2(), __toCommonJS(esm_exports$2)).createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING"); + function suppressTracing(context) { + return context.setValue(SUPPRESS_TRACING_KEY, true); + } + exports.suppressTracing = suppressTracing; + function unsuppressTracing(context) { + return context.deleteValue(SUPPRESS_TRACING_KEY); + } + exports.unsuppressTracing = unsuppressTracing; + function isTracingSuppressed(context) { + return context.getValue(SUPPRESS_TRACING_KEY) === true; + } + exports.isTracingSuppressed = isTracingSuppressed; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/baggage/constants.js +var require_constants = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BAGGAGE_MAX_TOTAL_LENGTH = exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = exports.BAGGAGE_HEADER = exports.BAGGAGE_ITEMS_SEPARATOR = exports.BAGGAGE_PROPERTIES_SEPARATOR = exports.BAGGAGE_KEY_PAIR_SEPARATOR = void 0; + exports.BAGGAGE_KEY_PAIR_SEPARATOR = "="; + exports.BAGGAGE_PROPERTIES_SEPARATOR = ";"; + exports.BAGGAGE_ITEMS_SEPARATOR = ","; + exports.BAGGAGE_HEADER = "baggage"; + exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = 180; + exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096; + exports.BAGGAGE_MAX_TOTAL_LENGTH = 8192; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/baggage/utils.js +var require_utils$5 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseKeyPairsIntoRecord = exports.parseBaggageHeaderString = exports.parsePairKeyValue = exports.getKeyPairs = exports.serializeKeyPairs = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const constants_1 = require_constants(); + function serializeKeyPairs(keyPairs) { + return keyPairs.reduce((hValue, current) => { + const value = `${hValue}${hValue !== "" ? constants_1.BAGGAGE_ITEMS_SEPARATOR : ""}${current}`; + return value.length > constants_1.BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value; + }, ""); + } + exports.serializeKeyPairs = serializeKeyPairs; + function getKeyPairs(baggage) { + return baggage.getAllEntries().map(([key, value]) => { + let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`; + if (value.metadata !== void 0) entry += constants_1.BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString(); + return entry; + }); + } + exports.getKeyPairs = getKeyPairs; + function parsePairKeyValue(entry) { + if (!entry) return; + const metadataSeparatorIndex = entry.indexOf(constants_1.BAGGAGE_PROPERTIES_SEPARATOR); + const keyPairPart = metadataSeparatorIndex === -1 ? entry : entry.substring(0, metadataSeparatorIndex); + const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR); + if (separatorIndex <= 0) return; + const rawKey = keyPairPart.substring(0, separatorIndex).trim(); + const rawValue = keyPairPart.substring(separatorIndex + 1).trim(); + if (!rawKey || !rawValue) return; + let key; + let value; + try { + key = decodeURIComponent(rawKey); + value = decodeURIComponent(rawValue); + } catch { + return; + } + let metadata; + if (metadataSeparatorIndex !== -1 && metadataSeparatorIndex < entry.length - 1) { + const metadataString = entry.substring(metadataSeparatorIndex + 1); + metadata = (0, api_1.baggageEntryMetadataFromString)(metadataString); + } + return { + key, + value, + metadata + }; + } + exports.parsePairKeyValue = parsePairKeyValue; + /** + * Parses a single baggage header string into the provided record, applying limits defined in this package. + * Uses indexOf/substring in a while loop to avoid allocating a full array of split entries. + * Returns the updated pair count so callers can track totals across multiple header values. + */ + function parseBaggageHeaderString(value, baggage, count, totalSize) { + let start = 0; + while (start < value.length && count < constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS) { + const end = value.indexOf(constants_1.BAGGAGE_ITEMS_SEPARATOR, start); + const entryEnd = end === -1 ? value.length : end; + const entryLength = entryEnd - start; + if (entryLength <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS) { + const keyPair = parsePairKeyValue(value.substring(start, entryEnd)); + if (keyPair) { + const entrySize = (count === 0 ? 0 : 1) + entryLength; + if (totalSize + entrySize > constants_1.BAGGAGE_MAX_TOTAL_LENGTH) break; + baggage[keyPair.key] = keyPair.metadata ? { + value: keyPair.value, + metadata: keyPair.metadata + } : { value: keyPair.value }; + count++; + totalSize += entrySize; + } + } + if (end === -1) break; + start = end + 1; + } + return [count, totalSize]; + } + exports.parseBaggageHeaderString = parseBaggageHeaderString; + /** + * Parse a string serialized in the baggage HTTP Format (without metadata): + * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md + */ + function parseKeyPairsIntoRecord(value) { + const result = {}; + if (typeof value === "string" && value.length > 0) value.split(constants_1.BAGGAGE_ITEMS_SEPARATOR).forEach((entry) => { + const keyPair = parsePairKeyValue(entry); + if (keyPair !== void 0 && keyPair.value.length > 0) result[keyPair.key] = keyPair.value; + }); + return result; + } + exports.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js +var require_W3CBaggagePropagator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.W3CBaggagePropagator = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const suppress_tracing_1 = require_suppress_tracing(); + const constants_1 = require_constants(); + const utils_1 = require_utils$5(); + /** + * Propagates {@link Baggage} through Context format propagation. + * + * Based on the Baggage specification: + * https://w3c.github.io/baggage/ + */ + var W3CBaggagePropagator = class { + inject(context, carrier, setter) { + const baggage = api_1.propagation.getBaggage(context); + if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context)) return; + const keyPairs = (0, utils_1.getKeyPairs)(baggage).filter((pair) => { + return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS; + }).slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS); + const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs); + if (headerValue.length > 0) setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue); + } + extract(context, carrier, getter) { + const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER); + if (!headerValue) return context; + const baggage = {}; + let count = 0; + let totalSize = 0; + if (Array.isArray(headerValue)) for (let i = 0; i < headerValue.length; i++) [count, totalSize] = (0, utils_1.parseBaggageHeaderString)(headerValue[i], baggage, count, totalSize); + else [count] = (0, utils_1.parseBaggageHeaderString)(headerValue, baggage, count, totalSize); + if (count === 0) return context; + return api_1.propagation.setBaggage(context, api_1.propagation.createBaggage(baggage)); + } + fields() { + return [constants_1.BAGGAGE_HEADER]; + } + }; + exports.W3CBaggagePropagator = W3CBaggagePropagator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js +var require_anchored_clock = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AnchoredClock = void 0; + /** + * A utility for returning wall times anchored to a given point in time. Wall time measurements will + * not be taken from the system, but instead are computed by adding a monotonic clock time + * to the anchor point. + * + * This is needed because the system time can change and result in unexpected situations like + * spans ending before they are started. Creating an anchored clock for each local root span + * ensures that span timings and durations are accurate while preventing span times from drifting + * too far from the system clock. + * + * Only creating an anchored clock once per local trace ensures span times are correct relative + * to each other. For example, a child span will never have a start time before its parent even + * if the system clock is corrected during the local trace. + * + * Heavily inspired by the OTel Java anchored clock + * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java + */ + var AnchoredClock = class { + _monotonicClock; + _epochMillis; + _performanceMillis; + /** + * Create a new AnchoredClock anchored to the current time returned by systemClock. + * + * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date + * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance + */ + constructor(systemClock, monotonicClock) { + this._monotonicClock = monotonicClock; + this._epochMillis = systemClock.now(); + this._performanceMillis = monotonicClock.now(); + } + /** + * Returns the current time by adding the number of milliseconds since the + * AnchoredClock was created to the creation epoch time + */ + now() { + const delta = this._monotonicClock.now() - this._performanceMillis; + return this._epochMillis + delta; + } + }; + exports.AnchoredClock = AnchoredClock; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/common/attributes.js +var require_attributes = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isAttributeValue = exports.isAttributeKey = exports.sanitizeAttributes = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + function sanitizeAttributes(attributes) { + const out = {}; + if (typeof attributes !== "object" || attributes == null) return out; + for (const key in attributes) { + if (!Object.prototype.hasOwnProperty.call(attributes, key)) continue; + if (!isAttributeKey(key)) { + api_1.diag.warn(`Invalid attribute key: ${key}`); + continue; + } + const val = attributes[key]; + if (!isAttributeValue(val)) { + api_1.diag.warn(`Invalid attribute value set for key: ${key}`); + continue; + } + if (Array.isArray(val)) out[key] = val.slice(); + else out[key] = val; + } + return out; + } + exports.sanitizeAttributes = sanitizeAttributes; + function isAttributeKey(key) { + return typeof key === "string" && key !== ""; + } + exports.isAttributeKey = isAttributeKey; + function isAttributeValue(val) { + if (val == null) return true; + if (Array.isArray(val)) return isHomogeneousAttributeValueArray(val); + return isValidPrimitiveAttributeValueType(typeof val); + } + exports.isAttributeValue = isAttributeValue; + function isHomogeneousAttributeValueArray(arr) { + let type; + for (const element of arr) { + if (element == null) continue; + const elementType = typeof element; + if (elementType === type) continue; + if (!type) { + if (isValidPrimitiveAttributeValueType(elementType)) { + type = elementType; + continue; + } + return false; + } + return false; + } + return true; + } + function isValidPrimitiveAttributeValueType(valType) { + switch (valType) { + case "number": + case "boolean": + case "string": return true; + } + return false; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js +var require_logging_error_handler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.loggingErrorHandler = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + /** + * Returns a function that logs an error using the provided logger, or a + * console logger if one was not provided. + */ + function loggingErrorHandler() { + return (ex) => { + api_1.diag.error(stringifyException(ex)); + }; + } + exports.loggingErrorHandler = loggingErrorHandler; + /** + * Converts an exception into a string representation + * @param {Exception} ex + */ + function stringifyException(ex) { + if (typeof ex === "string") return ex; + else return JSON.stringify(flattenException(ex)); + } + /** + * Flattens an exception into key-value pairs by traversing the prototype chain + * and coercing values to strings. Duplicate properties will not be overwritten; + * the first insert wins. + */ + function flattenException(ex) { + const result = {}; + let current = ex; + while (current !== null) { + Object.getOwnPropertyNames(current).forEach((propertyName) => { + if (result[propertyName]) return; + const value = current[propertyName]; + if (value) result[propertyName] = String(value); + }); + current = Object.getPrototypeOf(current); + } + return result; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js +var require_global_error_handler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.globalErrorHandler = exports.setGlobalErrorHandler = void 0; + /** The global error handler delegate */ + let delegateHandler = (0, require_logging_error_handler().loggingErrorHandler)(); + /** + * Set the global error handler + * @param {ErrorHandler} handler + */ + function setGlobalErrorHandler(handler) { + delegateHandler = handler; + } + exports.setGlobalErrorHandler = setGlobalErrorHandler; + /** + * Return the global error handler + * @param {Exception} ex + */ + function globalErrorHandler(ex) { + try { + delegateHandler(ex); + } catch {} + } + exports.globalErrorHandler = globalErrorHandler; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/platform/node/environment.js +var require_environment = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getStringListFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports.getNumberFromEnv = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const util_1 = __require("util"); + /** + * Retrieves a number from an environment variable. + * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number. + * - Returns a number in all other cases. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {number | undefined} - The number value or `undefined`. + */ + function getNumberFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === "") return; + const value = Number(raw); + if (isNaN(value)) { + api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected a number, using defaults`); + return; + } + return value; + } + exports.getNumberFromEnv = getNumberFromEnv; + /** + * Retrieves a string from an environment variable. + * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {string | undefined} - The string value or `undefined`. + */ + function getStringFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === "") return; + return raw; + } + exports.getStringFromEnv = getStringFromEnv; + /** + * Retrieves a boolean value from an environment variable. + * - Trims leading and trailing whitespace and ignores casing. + * - Returns `false` if the environment variable is empty, unset, or contains only whitespace. + * - Returns `false` for strings that cannot be mapped to a boolean. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace. + */ + function getBooleanFromEnv(key) { + const raw = process.env[key]?.trim().toLowerCase(); + if (raw == null || raw === "") return false; + if (raw === "true") return true; + else if (raw === "false") return false; + else { + api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`); + return false; + } + } + exports.getBooleanFromEnv = getBooleanFromEnv; + /** + * Retrieves a list of strings from an environment variable. + * - Uses ',' as the delimiter. + * - Trims leading and trailing whitespace from each entry. + * - Excludes empty entries. + * - Returns `undefined` if the environment variable is empty or contains only whitespace. + * - Returns an empty array if all entries are empty or whitespace. + * + * @param {string} key - The name of the environment variable to retrieve. + * @returns {string[] | undefined} - The list of strings or `undefined`. + */ + function getStringListFromEnv(key) { + return getStringFromEnv(key)?.split(",").map((v) => v.trim()).filter((s) => s !== ""); + } + exports.getStringListFromEnv = getStringListFromEnv; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/common/globalThis.js +var require_globalThis = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports._globalThis = void 0; + /** + * @deprecated Use globalThis directly instead. + */ + exports._globalThis = globalThis; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/version.js +var require_version$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = void 0; + exports.VERSION = "2.11.0"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.js +/** +* Creates a const map from the given values +* @param values - An array of values to be used as keys and values in the map. +* @returns A populated version of the map with the values and keys derived from the values. +*/ +/*#__NO_SIDE_EFFECTS__*/ +function createConstMap(values) { + let res = {}; + const len = values.length; + for (let lp = 0; lp < len; lp++) { + const val = values[lp]; + if (val) res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val; + } + return res; +} +var init_utils = __esmMin((() => {})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js +var TMP_AWS_LAMBDA_INVOKED_ARN, TMP_DB_SYSTEM, TMP_DB_CONNECTION_STRING, TMP_DB_USER, TMP_DB_JDBC_DRIVER_CLASSNAME, TMP_DB_NAME, TMP_DB_STATEMENT, TMP_DB_OPERATION, TMP_DB_MSSQL_INSTANCE_NAME, TMP_DB_CASSANDRA_KEYSPACE, TMP_DB_CASSANDRA_PAGE_SIZE, TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, TMP_DB_CASSANDRA_TABLE, TMP_DB_CASSANDRA_IDEMPOTENCE, TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, TMP_DB_CASSANDRA_COORDINATOR_ID, TMP_DB_CASSANDRA_COORDINATOR_DC, TMP_DB_HBASE_NAMESPACE, TMP_DB_REDIS_DATABASE_INDEX, TMP_DB_MONGODB_COLLECTION, TMP_DB_SQL_TABLE, TMP_EXCEPTION_TYPE, TMP_EXCEPTION_MESSAGE, TMP_EXCEPTION_STACKTRACE, TMP_EXCEPTION_ESCAPED, TMP_FAAS_TRIGGER, TMP_FAAS_EXECUTION, TMP_FAAS_DOCUMENT_COLLECTION, TMP_FAAS_DOCUMENT_OPERATION, TMP_FAAS_DOCUMENT_TIME, TMP_FAAS_DOCUMENT_NAME, TMP_FAAS_TIME, TMP_FAAS_CRON, TMP_FAAS_COLDSTART, TMP_FAAS_INVOKED_NAME, TMP_FAAS_INVOKED_PROVIDER, TMP_FAAS_INVOKED_REGION, TMP_NET_TRANSPORT, TMP_NET_PEER_IP, TMP_NET_PEER_PORT, TMP_NET_PEER_NAME, TMP_NET_HOST_IP, TMP_NET_HOST_PORT, TMP_NET_HOST_NAME, TMP_NET_HOST_CONNECTION_TYPE, TMP_NET_HOST_CONNECTION_SUBTYPE, TMP_NET_HOST_CARRIER_NAME, TMP_NET_HOST_CARRIER_MCC, TMP_NET_HOST_CARRIER_MNC, TMP_NET_HOST_CARRIER_ICC, TMP_PEER_SERVICE, TMP_ENDUSER_ID, TMP_ENDUSER_ROLE, TMP_ENDUSER_SCOPE, TMP_THREAD_ID, TMP_THREAD_NAME, TMP_CODE_FUNCTION, TMP_CODE_NAMESPACE, TMP_CODE_FILEPATH, TMP_CODE_LINENO, TMP_HTTP_METHOD, TMP_HTTP_URL, TMP_HTTP_TARGET, TMP_HTTP_HOST, TMP_HTTP_SCHEME, TMP_HTTP_STATUS_CODE, TMP_HTTP_FLAVOR, TMP_HTTP_USER_AGENT, TMP_HTTP_REQUEST_CONTENT_LENGTH, TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, TMP_HTTP_RESPONSE_CONTENT_LENGTH, TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, TMP_HTTP_SERVER_NAME, TMP_HTTP_ROUTE, TMP_HTTP_CLIENT_IP, TMP_AWS_DYNAMODB_TABLE_NAMES, TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, TMP_AWS_DYNAMODB_CONSISTENT_READ, TMP_AWS_DYNAMODB_PROJECTION, TMP_AWS_DYNAMODB_LIMIT, TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, TMP_AWS_DYNAMODB_INDEX_NAME, TMP_AWS_DYNAMODB_SELECT, TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, TMP_AWS_DYNAMODB_TABLE_COUNT, TMP_AWS_DYNAMODB_SCAN_FORWARD, TMP_AWS_DYNAMODB_SEGMENT, TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, TMP_AWS_DYNAMODB_COUNT, TMP_AWS_DYNAMODB_SCANNED_COUNT, TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, TMP_MESSAGING_SYSTEM, TMP_MESSAGING_DESTINATION, TMP_MESSAGING_DESTINATION_KIND, TMP_MESSAGING_TEMP_DESTINATION, TMP_MESSAGING_PROTOCOL, TMP_MESSAGING_PROTOCOL_VERSION, TMP_MESSAGING_URL, TMP_MESSAGING_MESSAGE_ID, TMP_MESSAGING_CONVERSATION_ID, TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, TMP_MESSAGING_OPERATION, TMP_MESSAGING_CONSUMER_ID, TMP_MESSAGING_RABBITMQ_ROUTING_KEY, TMP_MESSAGING_KAFKA_MESSAGE_KEY, TMP_MESSAGING_KAFKA_CONSUMER_GROUP, TMP_MESSAGING_KAFKA_CLIENT_ID, TMP_MESSAGING_KAFKA_PARTITION, TMP_MESSAGING_KAFKA_TOMBSTONE, TMP_RPC_SYSTEM, TMP_RPC_SERVICE, TMP_RPC_METHOD, TMP_RPC_GRPC_STATUS_CODE, TMP_RPC_JSONRPC_VERSION, TMP_RPC_JSONRPC_REQUEST_ID, TMP_RPC_JSONRPC_ERROR_CODE, TMP_RPC_JSONRPC_ERROR_MESSAGE, TMP_MESSAGE_TYPE, TMP_MESSAGE_ID, TMP_MESSAGE_COMPRESSED_SIZE, TMP_MESSAGE_UNCOMPRESSED_SIZE, SEMATTRS_AWS_LAMBDA_INVOKED_ARN, SEMATTRS_DB_SYSTEM, SEMATTRS_DB_CONNECTION_STRING, SEMATTRS_DB_USER, SEMATTRS_DB_JDBC_DRIVER_CLASSNAME, SEMATTRS_DB_NAME, SEMATTRS_DB_STATEMENT, SEMATTRS_DB_OPERATION, SEMATTRS_DB_MSSQL_INSTANCE_NAME, SEMATTRS_DB_CASSANDRA_KEYSPACE, SEMATTRS_DB_CASSANDRA_PAGE_SIZE, SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL, SEMATTRS_DB_CASSANDRA_TABLE, SEMATTRS_DB_CASSANDRA_IDEMPOTENCE, SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, SEMATTRS_DB_CASSANDRA_COORDINATOR_ID, SEMATTRS_DB_CASSANDRA_COORDINATOR_DC, SEMATTRS_DB_HBASE_NAMESPACE, SEMATTRS_DB_REDIS_DATABASE_INDEX, SEMATTRS_DB_MONGODB_COLLECTION, SEMATTRS_DB_SQL_TABLE, SEMATTRS_EXCEPTION_TYPE, SEMATTRS_EXCEPTION_MESSAGE, SEMATTRS_EXCEPTION_STACKTRACE, SEMATTRS_EXCEPTION_ESCAPED, SEMATTRS_FAAS_TRIGGER, SEMATTRS_FAAS_EXECUTION, SEMATTRS_FAAS_DOCUMENT_COLLECTION, SEMATTRS_FAAS_DOCUMENT_OPERATION, SEMATTRS_FAAS_DOCUMENT_TIME, SEMATTRS_FAAS_DOCUMENT_NAME, SEMATTRS_FAAS_TIME, SEMATTRS_FAAS_CRON, SEMATTRS_FAAS_COLDSTART, SEMATTRS_FAAS_INVOKED_NAME, SEMATTRS_FAAS_INVOKED_PROVIDER, SEMATTRS_FAAS_INVOKED_REGION, SEMATTRS_NET_TRANSPORT, SEMATTRS_NET_PEER_IP, SEMATTRS_NET_PEER_PORT, SEMATTRS_NET_PEER_NAME, SEMATTRS_NET_HOST_IP, SEMATTRS_NET_HOST_PORT, SEMATTRS_NET_HOST_NAME, SEMATTRS_NET_HOST_CONNECTION_TYPE, SEMATTRS_NET_HOST_CONNECTION_SUBTYPE, SEMATTRS_NET_HOST_CARRIER_NAME, SEMATTRS_NET_HOST_CARRIER_MCC, SEMATTRS_NET_HOST_CARRIER_MNC, SEMATTRS_NET_HOST_CARRIER_ICC, SEMATTRS_PEER_SERVICE, SEMATTRS_ENDUSER_ID, SEMATTRS_ENDUSER_ROLE, SEMATTRS_ENDUSER_SCOPE, SEMATTRS_THREAD_ID, SEMATTRS_THREAD_NAME, SEMATTRS_CODE_FUNCTION, SEMATTRS_CODE_NAMESPACE, SEMATTRS_CODE_FILEPATH, SEMATTRS_CODE_LINENO, SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_URL, SEMATTRS_HTTP_TARGET, SEMATTRS_HTTP_HOST, SEMATTRS_HTTP_SCHEME, SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_HTTP_FLAVOR, SEMATTRS_HTTP_USER_AGENT, SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH, SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, SEMATTRS_HTTP_SERVER_NAME, SEMATTRS_HTTP_ROUTE, SEMATTRS_HTTP_CLIENT_IP, SEMATTRS_AWS_DYNAMODB_TABLE_NAMES, SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY, SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ, SEMATTRS_AWS_DYNAMODB_PROJECTION, SEMATTRS_AWS_DYNAMODB_LIMIT, SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET, SEMATTRS_AWS_DYNAMODB_INDEX_NAME, SEMATTRS_AWS_DYNAMODB_SELECT, SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, SEMATTRS_AWS_DYNAMODB_TABLE_COUNT, SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD, SEMATTRS_AWS_DYNAMODB_SEGMENT, SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS, SEMATTRS_AWS_DYNAMODB_COUNT, SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT, SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, SEMATTRS_MESSAGING_SYSTEM, SEMATTRS_MESSAGING_DESTINATION, SEMATTRS_MESSAGING_DESTINATION_KIND, SEMATTRS_MESSAGING_TEMP_DESTINATION, SEMATTRS_MESSAGING_PROTOCOL, SEMATTRS_MESSAGING_PROTOCOL_VERSION, SEMATTRS_MESSAGING_URL, SEMATTRS_MESSAGING_MESSAGE_ID, SEMATTRS_MESSAGING_CONVERSATION_ID, SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, SEMATTRS_MESSAGING_OPERATION, SEMATTRS_MESSAGING_CONSUMER_ID, SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY, SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY, SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP, SEMATTRS_MESSAGING_KAFKA_CLIENT_ID, SEMATTRS_MESSAGING_KAFKA_PARTITION, SEMATTRS_MESSAGING_KAFKA_TOMBSTONE, SEMATTRS_RPC_SYSTEM, SEMATTRS_RPC_SERVICE, SEMATTRS_RPC_METHOD, SEMATTRS_RPC_GRPC_STATUS_CODE, SEMATTRS_RPC_JSONRPC_VERSION, SEMATTRS_RPC_JSONRPC_REQUEST_ID, SEMATTRS_RPC_JSONRPC_ERROR_CODE, SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE, SEMATTRS_MESSAGE_TYPE, SEMATTRS_MESSAGE_ID, SEMATTRS_MESSAGE_COMPRESSED_SIZE, SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE, SemanticAttributes, TMP_DBSYSTEMVALUES_OTHER_SQL, TMP_DBSYSTEMVALUES_MSSQL, TMP_DBSYSTEMVALUES_MYSQL, TMP_DBSYSTEMVALUES_ORACLE, TMP_DBSYSTEMVALUES_DB2, TMP_DBSYSTEMVALUES_POSTGRESQL, TMP_DBSYSTEMVALUES_REDSHIFT, TMP_DBSYSTEMVALUES_HIVE, TMP_DBSYSTEMVALUES_CLOUDSCAPE, TMP_DBSYSTEMVALUES_HSQLDB, TMP_DBSYSTEMVALUES_PROGRESS, TMP_DBSYSTEMVALUES_MAXDB, TMP_DBSYSTEMVALUES_HANADB, TMP_DBSYSTEMVALUES_INGRES, TMP_DBSYSTEMVALUES_FIRSTSQL, TMP_DBSYSTEMVALUES_EDB, TMP_DBSYSTEMVALUES_CACHE, TMP_DBSYSTEMVALUES_ADABAS, TMP_DBSYSTEMVALUES_FIREBIRD, TMP_DBSYSTEMVALUES_DERBY, TMP_DBSYSTEMVALUES_FILEMAKER, TMP_DBSYSTEMVALUES_INFORMIX, TMP_DBSYSTEMVALUES_INSTANTDB, TMP_DBSYSTEMVALUES_INTERBASE, TMP_DBSYSTEMVALUES_MARIADB, TMP_DBSYSTEMVALUES_NETEZZA, TMP_DBSYSTEMVALUES_PERVASIVE, TMP_DBSYSTEMVALUES_POINTBASE, TMP_DBSYSTEMVALUES_SQLITE, TMP_DBSYSTEMVALUES_SYBASE, TMP_DBSYSTEMVALUES_TERADATA, TMP_DBSYSTEMVALUES_VERTICA, TMP_DBSYSTEMVALUES_H2, TMP_DBSYSTEMVALUES_COLDFUSION, TMP_DBSYSTEMVALUES_CASSANDRA, TMP_DBSYSTEMVALUES_HBASE, TMP_DBSYSTEMVALUES_MONGODB, TMP_DBSYSTEMVALUES_REDIS, TMP_DBSYSTEMVALUES_COUCHBASE, TMP_DBSYSTEMVALUES_COUCHDB, TMP_DBSYSTEMVALUES_COSMOSDB, TMP_DBSYSTEMVALUES_DYNAMODB, TMP_DBSYSTEMVALUES_NEO4J, TMP_DBSYSTEMVALUES_GEODE, TMP_DBSYSTEMVALUES_ELASTICSEARCH, TMP_DBSYSTEMVALUES_MEMCACHED, TMP_DBSYSTEMVALUES_COCKROACHDB, DBSYSTEMVALUES_OTHER_SQL, DBSYSTEMVALUES_MSSQL, DBSYSTEMVALUES_MYSQL, DBSYSTEMVALUES_ORACLE, DBSYSTEMVALUES_DB2, DBSYSTEMVALUES_POSTGRESQL, DBSYSTEMVALUES_REDSHIFT, DBSYSTEMVALUES_HIVE, DBSYSTEMVALUES_CLOUDSCAPE, DBSYSTEMVALUES_HSQLDB, DBSYSTEMVALUES_PROGRESS, DBSYSTEMVALUES_MAXDB, DBSYSTEMVALUES_HANADB, DBSYSTEMVALUES_INGRES, DBSYSTEMVALUES_FIRSTSQL, DBSYSTEMVALUES_EDB, DBSYSTEMVALUES_CACHE, DBSYSTEMVALUES_ADABAS, DBSYSTEMVALUES_FIREBIRD, DBSYSTEMVALUES_DERBY, DBSYSTEMVALUES_FILEMAKER, DBSYSTEMVALUES_INFORMIX, DBSYSTEMVALUES_INSTANTDB, DBSYSTEMVALUES_INTERBASE, DBSYSTEMVALUES_MARIADB, DBSYSTEMVALUES_NETEZZA, DBSYSTEMVALUES_PERVASIVE, DBSYSTEMVALUES_POINTBASE, DBSYSTEMVALUES_SQLITE, DBSYSTEMVALUES_SYBASE, DBSYSTEMVALUES_TERADATA, DBSYSTEMVALUES_VERTICA, DBSYSTEMVALUES_H2, DBSYSTEMVALUES_COLDFUSION, DBSYSTEMVALUES_CASSANDRA, DBSYSTEMVALUES_HBASE, DBSYSTEMVALUES_MONGODB, DBSYSTEMVALUES_REDIS, DBSYSTEMVALUES_COUCHBASE, DBSYSTEMVALUES_COUCHDB, DBSYSTEMVALUES_COSMOSDB, DBSYSTEMVALUES_DYNAMODB, DBSYSTEMVALUES_NEO4J, DBSYSTEMVALUES_GEODE, DBSYSTEMVALUES_ELASTICSEARCH, DBSYSTEMVALUES_MEMCACHED, DBSYSTEMVALUES_COCKROACHDB, DbSystemValues, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, DBCASSANDRACONSISTENCYLEVELVALUES_ALL, DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, DBCASSANDRACONSISTENCYLEVELVALUES_ONE, DBCASSANDRACONSISTENCYLEVELVALUES_TWO, DBCASSANDRACONSISTENCYLEVELVALUES_THREE, DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, DBCASSANDRACONSISTENCYLEVELVALUES_ANY, DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, DbCassandraConsistencyLevelValues, TMP_FAASTRIGGERVALUES_DATASOURCE, TMP_FAASTRIGGERVALUES_HTTP, TMP_FAASTRIGGERVALUES_PUBSUB, TMP_FAASTRIGGERVALUES_TIMER, TMP_FAASTRIGGERVALUES_OTHER, FAASTRIGGERVALUES_DATASOURCE, FAASTRIGGERVALUES_HTTP, FAASTRIGGERVALUES_PUBSUB, FAASTRIGGERVALUES_TIMER, FAASTRIGGERVALUES_OTHER, FaasTriggerValues, TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, TMP_FAASDOCUMENTOPERATIONVALUES_DELETE, FAASDOCUMENTOPERATIONVALUES_INSERT, FAASDOCUMENTOPERATIONVALUES_EDIT, FAASDOCUMENTOPERATIONVALUES_DELETE, FaasDocumentOperationValues, TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, TMP_FAASINVOKEDPROVIDERVALUES_AWS, TMP_FAASINVOKEDPROVIDERVALUES_AZURE, TMP_FAASINVOKEDPROVIDERVALUES_GCP, FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, FAASINVOKEDPROVIDERVALUES_AWS, FAASINVOKEDPROVIDERVALUES_AZURE, FAASINVOKEDPROVIDERVALUES_GCP, FaasInvokedProviderValues, TMP_NETTRANSPORTVALUES_IP_TCP, TMP_NETTRANSPORTVALUES_IP_UDP, TMP_NETTRANSPORTVALUES_IP, TMP_NETTRANSPORTVALUES_UNIX, TMP_NETTRANSPORTVALUES_PIPE, TMP_NETTRANSPORTVALUES_INPROC, TMP_NETTRANSPORTVALUES_OTHER, NETTRANSPORTVALUES_IP_TCP, NETTRANSPORTVALUES_IP_UDP, NETTRANSPORTVALUES_IP, NETTRANSPORTVALUES_UNIX, NETTRANSPORTVALUES_PIPE, NETTRANSPORTVALUES_INPROC, NETTRANSPORTVALUES_OTHER, NetTransportValues, TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, NETHOSTCONNECTIONTYPEVALUES_WIFI, NETHOSTCONNECTIONTYPEVALUES_WIRED, NETHOSTCONNECTIONTYPEVALUES_CELL, NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, NetHostConnectionTypeValues, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, NETHOSTCONNECTIONSUBTYPEVALUES_LTE, NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, NETHOSTCONNECTIONSUBTYPEVALUES_GSM, NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, NETHOSTCONNECTIONSUBTYPEVALUES_NR, NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, NetHostConnectionSubtypeValues, TMP_HTTPFLAVORVALUES_HTTP_1_0, TMP_HTTPFLAVORVALUES_HTTP_1_1, TMP_HTTPFLAVORVALUES_HTTP_2_0, TMP_HTTPFLAVORVALUES_SPDY, TMP_HTTPFLAVORVALUES_QUIC, HTTPFLAVORVALUES_HTTP_1_0, HTTPFLAVORVALUES_HTTP_1_1, HTTPFLAVORVALUES_HTTP_2_0, HTTPFLAVORVALUES_SPDY, HTTPFLAVORVALUES_QUIC, HttpFlavorValues, TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC, MESSAGINGDESTINATIONKINDVALUES_QUEUE, MESSAGINGDESTINATIONKINDVALUES_TOPIC, MessagingDestinationKindValues, TMP_MESSAGINGOPERATIONVALUES_RECEIVE, TMP_MESSAGINGOPERATIONVALUES_PROCESS, MESSAGINGOPERATIONVALUES_RECEIVE, MESSAGINGOPERATIONVALUES_PROCESS, MessagingOperationValues, TMP_RPCGRPCSTATUSCODEVALUES_OK, TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED, RPCGRPCSTATUSCODEVALUES_OK, RPCGRPCSTATUSCODEVALUES_CANCELLED, RPCGRPCSTATUSCODEVALUES_UNKNOWN, RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, RPCGRPCSTATUSCODEVALUES_NOT_FOUND, RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, RPCGRPCSTATUSCODEVALUES_ABORTED, RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, RPCGRPCSTATUSCODEVALUES_INTERNAL, RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, RPCGRPCSTATUSCODEVALUES_DATA_LOSS, RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED, RpcGrpcStatusCodeValues, TMP_MESSAGETYPEVALUES_SENT, TMP_MESSAGETYPEVALUES_RECEIVED, MESSAGETYPEVALUES_SENT, MESSAGETYPEVALUES_RECEIVED, MessageTypeValues; +var init_SemanticAttributes = __esmMin((() => { + init_utils(); + TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn"; + TMP_DB_SYSTEM = "db.system"; + TMP_DB_CONNECTION_STRING = "db.connection_string"; + TMP_DB_USER = "db.user"; + TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname"; + TMP_DB_NAME = "db.name"; + TMP_DB_STATEMENT = "db.statement"; + TMP_DB_OPERATION = "db.operation"; + TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name"; + TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace"; + TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size"; + TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level"; + TMP_DB_CASSANDRA_TABLE = "db.cassandra.table"; + TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence"; + TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count"; + TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id"; + TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc"; + TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace"; + TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index"; + TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection"; + TMP_DB_SQL_TABLE = "db.sql.table"; + TMP_EXCEPTION_TYPE = "exception.type"; + TMP_EXCEPTION_MESSAGE = "exception.message"; + TMP_EXCEPTION_STACKTRACE = "exception.stacktrace"; + TMP_EXCEPTION_ESCAPED = "exception.escaped"; + TMP_FAAS_TRIGGER = "faas.trigger"; + TMP_FAAS_EXECUTION = "faas.execution"; + TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection"; + TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation"; + TMP_FAAS_DOCUMENT_TIME = "faas.document.time"; + TMP_FAAS_DOCUMENT_NAME = "faas.document.name"; + TMP_FAAS_TIME = "faas.time"; + TMP_FAAS_CRON = "faas.cron"; + TMP_FAAS_COLDSTART = "faas.coldstart"; + TMP_FAAS_INVOKED_NAME = "faas.invoked_name"; + TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider"; + TMP_FAAS_INVOKED_REGION = "faas.invoked_region"; + TMP_NET_TRANSPORT = "net.transport"; + TMP_NET_PEER_IP = "net.peer.ip"; + TMP_NET_PEER_PORT = "net.peer.port"; + TMP_NET_PEER_NAME = "net.peer.name"; + TMP_NET_HOST_IP = "net.host.ip"; + TMP_NET_HOST_PORT = "net.host.port"; + TMP_NET_HOST_NAME = "net.host.name"; + TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type"; + TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype"; + TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name"; + TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc"; + TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc"; + TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc"; + TMP_PEER_SERVICE = "peer.service"; + TMP_ENDUSER_ID = "enduser.id"; + TMP_ENDUSER_ROLE = "enduser.role"; + TMP_ENDUSER_SCOPE = "enduser.scope"; + TMP_THREAD_ID = "thread.id"; + TMP_THREAD_NAME = "thread.name"; + TMP_CODE_FUNCTION = "code.function"; + TMP_CODE_NAMESPACE = "code.namespace"; + TMP_CODE_FILEPATH = "code.filepath"; + TMP_CODE_LINENO = "code.lineno"; + TMP_HTTP_METHOD = "http.method"; + TMP_HTTP_URL = "http.url"; + TMP_HTTP_TARGET = "http.target"; + TMP_HTTP_HOST = "http.host"; + TMP_HTTP_SCHEME = "http.scheme"; + TMP_HTTP_STATUS_CODE = "http.status_code"; + TMP_HTTP_FLAVOR = "http.flavor"; + TMP_HTTP_USER_AGENT = "http.user_agent"; + TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; + TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; + TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; + TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; + TMP_HTTP_SERVER_NAME = "http.server_name"; + TMP_HTTP_ROUTE = "http.route"; + TMP_HTTP_CLIENT_IP = "http.client_ip"; + TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names"; + TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity"; + TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics"; + TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity"; + TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity"; + TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read"; + TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection"; + TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit"; + TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get"; + TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name"; + TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select"; + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes"; + TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes"; + TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table"; + TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count"; + TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward"; + TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment"; + TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments"; + TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count"; + TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count"; + TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions"; + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates"; + TMP_MESSAGING_SYSTEM = "messaging.system"; + TMP_MESSAGING_DESTINATION = "messaging.destination"; + TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind"; + TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination"; + TMP_MESSAGING_PROTOCOL = "messaging.protocol"; + TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version"; + TMP_MESSAGING_URL = "messaging.url"; + TMP_MESSAGING_MESSAGE_ID = "messaging.message_id"; + TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id"; + TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes"; + TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes"; + TMP_MESSAGING_OPERATION = "messaging.operation"; + TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id"; + TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key"; + TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key"; + TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group"; + TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id"; + TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition"; + TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone"; + TMP_RPC_SYSTEM = "rpc.system"; + TMP_RPC_SERVICE = "rpc.service"; + TMP_RPC_METHOD = "rpc.method"; + TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code"; + TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version"; + TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id"; + TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code"; + TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message"; + TMP_MESSAGE_TYPE = "message.type"; + TMP_MESSAGE_ID = "message.id"; + TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size"; + TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size"; + SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; + SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; + SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; + SEMATTRS_DB_USER = TMP_DB_USER; + SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; + SEMATTRS_DB_NAME = TMP_DB_NAME; + SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; + SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; + SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; + SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; + SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; + SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; + SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; + SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; + SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; + SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; + SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; + SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; + SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; + SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; + SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; + SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; + SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; + SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; + SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; + SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; + SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; + SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; + SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; + SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; + SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; + SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; + SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; + SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; + SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; + SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; + SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; + SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; + SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; + SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; + SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; + SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; + SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; + SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; + SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; + SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; + SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; + SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; + SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; + SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; + SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; + SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; + SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; + SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; + SEMATTRS_THREAD_ID = TMP_THREAD_ID; + SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; + SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; + SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; + SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; + SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; + SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; + SEMATTRS_HTTP_URL = TMP_HTTP_URL; + SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; + SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; + SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; + SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; + SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; + SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; + SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; + SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; + SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; + SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; + SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; + SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; + SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; + SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; + SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; + SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; + SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; + SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; + SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; + SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; + SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; + SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; + SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; + SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; + SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; + SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; + SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; + SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; + SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; + SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; + SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; + SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; + SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; + SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; + SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; + SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; + SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; + SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; + SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; + SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; + SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; + SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; + SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; + SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; + SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; + SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; + SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; + SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; + SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; + SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; + SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; + SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; + SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; + SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; + SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; + SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; + SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; + SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; + SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; + SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; + SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; + SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; + SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; + SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; + SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; + SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; + SemanticAttributes = /*#__PURE__*/ createConstMap([ + TMP_AWS_LAMBDA_INVOKED_ARN, + TMP_DB_SYSTEM, + TMP_DB_CONNECTION_STRING, + TMP_DB_USER, + TMP_DB_JDBC_DRIVER_CLASSNAME, + TMP_DB_NAME, + TMP_DB_STATEMENT, + TMP_DB_OPERATION, + TMP_DB_MSSQL_INSTANCE_NAME, + TMP_DB_CASSANDRA_KEYSPACE, + TMP_DB_CASSANDRA_PAGE_SIZE, + TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, + TMP_DB_CASSANDRA_TABLE, + TMP_DB_CASSANDRA_IDEMPOTENCE, + TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, + TMP_DB_CASSANDRA_COORDINATOR_ID, + TMP_DB_CASSANDRA_COORDINATOR_DC, + TMP_DB_HBASE_NAMESPACE, + TMP_DB_REDIS_DATABASE_INDEX, + TMP_DB_MONGODB_COLLECTION, + TMP_DB_SQL_TABLE, + TMP_EXCEPTION_TYPE, + TMP_EXCEPTION_MESSAGE, + TMP_EXCEPTION_STACKTRACE, + TMP_EXCEPTION_ESCAPED, + TMP_FAAS_TRIGGER, + TMP_FAAS_EXECUTION, + TMP_FAAS_DOCUMENT_COLLECTION, + TMP_FAAS_DOCUMENT_OPERATION, + TMP_FAAS_DOCUMENT_TIME, + TMP_FAAS_DOCUMENT_NAME, + TMP_FAAS_TIME, + TMP_FAAS_CRON, + TMP_FAAS_COLDSTART, + TMP_FAAS_INVOKED_NAME, + TMP_FAAS_INVOKED_PROVIDER, + TMP_FAAS_INVOKED_REGION, + TMP_NET_TRANSPORT, + TMP_NET_PEER_IP, + TMP_NET_PEER_PORT, + TMP_NET_PEER_NAME, + TMP_NET_HOST_IP, + TMP_NET_HOST_PORT, + TMP_NET_HOST_NAME, + TMP_NET_HOST_CONNECTION_TYPE, + TMP_NET_HOST_CONNECTION_SUBTYPE, + TMP_NET_HOST_CARRIER_NAME, + TMP_NET_HOST_CARRIER_MCC, + TMP_NET_HOST_CARRIER_MNC, + TMP_NET_HOST_CARRIER_ICC, + TMP_PEER_SERVICE, + TMP_ENDUSER_ID, + TMP_ENDUSER_ROLE, + TMP_ENDUSER_SCOPE, + TMP_THREAD_ID, + TMP_THREAD_NAME, + TMP_CODE_FUNCTION, + TMP_CODE_NAMESPACE, + TMP_CODE_FILEPATH, + TMP_CODE_LINENO, + TMP_HTTP_METHOD, + TMP_HTTP_URL, + TMP_HTTP_TARGET, + TMP_HTTP_HOST, + TMP_HTTP_SCHEME, + TMP_HTTP_STATUS_CODE, + TMP_HTTP_FLAVOR, + TMP_HTTP_USER_AGENT, + TMP_HTTP_REQUEST_CONTENT_LENGTH, + TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_RESPONSE_CONTENT_LENGTH, + TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_SERVER_NAME, + TMP_HTTP_ROUTE, + TMP_HTTP_CLIENT_IP, + TMP_AWS_DYNAMODB_TABLE_NAMES, + TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, + TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, + TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, + TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, + TMP_AWS_DYNAMODB_CONSISTENT_READ, + TMP_AWS_DYNAMODB_PROJECTION, + TMP_AWS_DYNAMODB_LIMIT, + TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, + TMP_AWS_DYNAMODB_INDEX_NAME, + TMP_AWS_DYNAMODB_SELECT, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, + TMP_AWS_DYNAMODB_TABLE_COUNT, + TMP_AWS_DYNAMODB_SCAN_FORWARD, + TMP_AWS_DYNAMODB_SEGMENT, + TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, + TMP_AWS_DYNAMODB_COUNT, + TMP_AWS_DYNAMODB_SCANNED_COUNT, + TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, + TMP_MESSAGING_SYSTEM, + TMP_MESSAGING_DESTINATION, + TMP_MESSAGING_DESTINATION_KIND, + TMP_MESSAGING_TEMP_DESTINATION, + TMP_MESSAGING_PROTOCOL, + TMP_MESSAGING_PROTOCOL_VERSION, + TMP_MESSAGING_URL, + TMP_MESSAGING_MESSAGE_ID, + TMP_MESSAGING_CONVERSATION_ID, + TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, + TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, + TMP_MESSAGING_OPERATION, + TMP_MESSAGING_CONSUMER_ID, + TMP_MESSAGING_RABBITMQ_ROUTING_KEY, + TMP_MESSAGING_KAFKA_MESSAGE_KEY, + TMP_MESSAGING_KAFKA_CONSUMER_GROUP, + TMP_MESSAGING_KAFKA_CLIENT_ID, + TMP_MESSAGING_KAFKA_PARTITION, + TMP_MESSAGING_KAFKA_TOMBSTONE, + TMP_RPC_SYSTEM, + TMP_RPC_SERVICE, + TMP_RPC_METHOD, + TMP_RPC_GRPC_STATUS_CODE, + TMP_RPC_JSONRPC_VERSION, + TMP_RPC_JSONRPC_REQUEST_ID, + TMP_RPC_JSONRPC_ERROR_CODE, + TMP_RPC_JSONRPC_ERROR_MESSAGE, + TMP_MESSAGE_TYPE, + TMP_MESSAGE_ID, + TMP_MESSAGE_COMPRESSED_SIZE, + TMP_MESSAGE_UNCOMPRESSED_SIZE + ]); + TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql"; + TMP_DBSYSTEMVALUES_MSSQL = "mssql"; + TMP_DBSYSTEMVALUES_MYSQL = "mysql"; + TMP_DBSYSTEMVALUES_ORACLE = "oracle"; + TMP_DBSYSTEMVALUES_DB2 = "db2"; + TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql"; + TMP_DBSYSTEMVALUES_REDSHIFT = "redshift"; + TMP_DBSYSTEMVALUES_HIVE = "hive"; + TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape"; + TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb"; + TMP_DBSYSTEMVALUES_PROGRESS = "progress"; + TMP_DBSYSTEMVALUES_MAXDB = "maxdb"; + TMP_DBSYSTEMVALUES_HANADB = "hanadb"; + TMP_DBSYSTEMVALUES_INGRES = "ingres"; + TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql"; + TMP_DBSYSTEMVALUES_EDB = "edb"; + TMP_DBSYSTEMVALUES_CACHE = "cache"; + TMP_DBSYSTEMVALUES_ADABAS = "adabas"; + TMP_DBSYSTEMVALUES_FIREBIRD = "firebird"; + TMP_DBSYSTEMVALUES_DERBY = "derby"; + TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker"; + TMP_DBSYSTEMVALUES_INFORMIX = "informix"; + TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb"; + TMP_DBSYSTEMVALUES_INTERBASE = "interbase"; + TMP_DBSYSTEMVALUES_MARIADB = "mariadb"; + TMP_DBSYSTEMVALUES_NETEZZA = "netezza"; + TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive"; + TMP_DBSYSTEMVALUES_POINTBASE = "pointbase"; + TMP_DBSYSTEMVALUES_SQLITE = "sqlite"; + TMP_DBSYSTEMVALUES_SYBASE = "sybase"; + TMP_DBSYSTEMVALUES_TERADATA = "teradata"; + TMP_DBSYSTEMVALUES_VERTICA = "vertica"; + TMP_DBSYSTEMVALUES_H2 = "h2"; + TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion"; + TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra"; + TMP_DBSYSTEMVALUES_HBASE = "hbase"; + TMP_DBSYSTEMVALUES_MONGODB = "mongodb"; + TMP_DBSYSTEMVALUES_REDIS = "redis"; + TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase"; + TMP_DBSYSTEMVALUES_COUCHDB = "couchdb"; + TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb"; + TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb"; + TMP_DBSYSTEMVALUES_NEO4J = "neo4j"; + TMP_DBSYSTEMVALUES_GEODE = "geode"; + TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch"; + TMP_DBSYSTEMVALUES_MEMCACHED = "memcached"; + TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb"; + DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; + DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; + DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; + DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; + DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; + DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; + DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; + DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; + DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; + DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; + DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; + DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; + DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; + DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; + DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; + DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; + DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; + DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; + DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; + DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; + DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; + DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; + DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; + DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; + DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; + DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; + DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; + DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; + DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; + DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; + DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; + DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; + DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; + DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; + DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; + DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; + DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; + DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; + DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; + DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; + DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; + DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; + DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; + DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; + DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; + DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; + DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; + DbSystemValues = /*#__PURE__*/ createConstMap([ + TMP_DBSYSTEMVALUES_OTHER_SQL, + TMP_DBSYSTEMVALUES_MSSQL, + TMP_DBSYSTEMVALUES_MYSQL, + TMP_DBSYSTEMVALUES_ORACLE, + TMP_DBSYSTEMVALUES_DB2, + TMP_DBSYSTEMVALUES_POSTGRESQL, + TMP_DBSYSTEMVALUES_REDSHIFT, + TMP_DBSYSTEMVALUES_HIVE, + TMP_DBSYSTEMVALUES_CLOUDSCAPE, + TMP_DBSYSTEMVALUES_HSQLDB, + TMP_DBSYSTEMVALUES_PROGRESS, + TMP_DBSYSTEMVALUES_MAXDB, + TMP_DBSYSTEMVALUES_HANADB, + TMP_DBSYSTEMVALUES_INGRES, + TMP_DBSYSTEMVALUES_FIRSTSQL, + TMP_DBSYSTEMVALUES_EDB, + TMP_DBSYSTEMVALUES_CACHE, + TMP_DBSYSTEMVALUES_ADABAS, + TMP_DBSYSTEMVALUES_FIREBIRD, + TMP_DBSYSTEMVALUES_DERBY, + TMP_DBSYSTEMVALUES_FILEMAKER, + TMP_DBSYSTEMVALUES_INFORMIX, + TMP_DBSYSTEMVALUES_INSTANTDB, + TMP_DBSYSTEMVALUES_INTERBASE, + TMP_DBSYSTEMVALUES_MARIADB, + TMP_DBSYSTEMVALUES_NETEZZA, + TMP_DBSYSTEMVALUES_PERVASIVE, + TMP_DBSYSTEMVALUES_POINTBASE, + TMP_DBSYSTEMVALUES_SQLITE, + TMP_DBSYSTEMVALUES_SYBASE, + TMP_DBSYSTEMVALUES_TERADATA, + TMP_DBSYSTEMVALUES_VERTICA, + TMP_DBSYSTEMVALUES_H2, + TMP_DBSYSTEMVALUES_COLDFUSION, + TMP_DBSYSTEMVALUES_CASSANDRA, + TMP_DBSYSTEMVALUES_HBASE, + TMP_DBSYSTEMVALUES_MONGODB, + TMP_DBSYSTEMVALUES_REDIS, + TMP_DBSYSTEMVALUES_COUCHBASE, + TMP_DBSYSTEMVALUES_COUCHDB, + TMP_DBSYSTEMVALUES_COSMOSDB, + TMP_DBSYSTEMVALUES_DYNAMODB, + TMP_DBSYSTEMVALUES_NEO4J, + TMP_DBSYSTEMVALUES_GEODE, + TMP_DBSYSTEMVALUES_ELASTICSEARCH, + TMP_DBSYSTEMVALUES_MEMCACHED, + TMP_DBSYSTEMVALUES_COCKROACHDB + ]); + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial"; + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial"; + DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; + DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; + DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; + DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; + DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; + DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; + DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; + DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; + DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; + DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; + DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; + DbCassandraConsistencyLevelValues = /*#__PURE__*/ createConstMap([ + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL + ]); + TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource"; + TMP_FAASTRIGGERVALUES_HTTP = "http"; + TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub"; + TMP_FAASTRIGGERVALUES_TIMER = "timer"; + TMP_FAASTRIGGERVALUES_OTHER = "other"; + FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; + FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; + FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; + FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; + FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; + FaasTriggerValues = /*#__PURE__*/ createConstMap([ + TMP_FAASTRIGGERVALUES_DATASOURCE, + TMP_FAASTRIGGERVALUES_HTTP, + TMP_FAASTRIGGERVALUES_PUBSUB, + TMP_FAASTRIGGERVALUES_TIMER, + TMP_FAASTRIGGERVALUES_OTHER + ]); + TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert"; + TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit"; + TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete"; + FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; + FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; + FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; + FaasDocumentOperationValues = /*#__PURE__*/ createConstMap([ + TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, + TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, + TMP_FAASDOCUMENTOPERATIONVALUES_DELETE + ]); + TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws"; + TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure"; + TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp"; + FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; + FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; + FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; + FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; + FaasInvokedProviderValues = /*#__PURE__*/ createConstMap([ + TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_FAASINVOKEDPROVIDERVALUES_AWS, + TMP_FAASINVOKEDPROVIDERVALUES_AZURE, + TMP_FAASINVOKEDPROVIDERVALUES_GCP + ]); + TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp"; + TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp"; + TMP_NETTRANSPORTVALUES_IP = "ip"; + TMP_NETTRANSPORTVALUES_UNIX = "unix"; + TMP_NETTRANSPORTVALUES_PIPE = "pipe"; + TMP_NETTRANSPORTVALUES_INPROC = "inproc"; + TMP_NETTRANSPORTVALUES_OTHER = "other"; + NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; + NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; + NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; + NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; + NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; + NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; + NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; + NetTransportValues = /*#__PURE__*/ createConstMap([ + TMP_NETTRANSPORTVALUES_IP_TCP, + TMP_NETTRANSPORTVALUES_IP_UDP, + TMP_NETTRANSPORTVALUES_IP, + TMP_NETTRANSPORTVALUES_UNIX, + TMP_NETTRANSPORTVALUES_PIPE, + TMP_NETTRANSPORTVALUES_INPROC, + TMP_NETTRANSPORTVALUES_OTHER + ]); + TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi"; + TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired"; + TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell"; + TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable"; + TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown"; + NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; + NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; + NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; + NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; + NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; + NetHostConnectionTypeValues = /*#__PURE__*/ createConstMap([ + TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, + TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, + TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN + ]); + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa"; + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca"; + NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; + NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; + NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; + NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; + NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; + NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; + NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; + NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; + NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; + NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; + NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; + NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; + NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; + NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; + NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; + NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; + NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; + NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; + NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; + NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; + NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; + NetHostConnectionSubtypeValues = /*#__PURE__*/ createConstMap([ + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA + ]); + TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0"; + TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1"; + TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0"; + TMP_HTTPFLAVORVALUES_SPDY = "SPDY"; + TMP_HTTPFLAVORVALUES_QUIC = "QUIC"; + HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; + HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; + HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; + HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; + HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; + HttpFlavorValues = { + HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, + HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, + HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, + SPDY: TMP_HTTPFLAVORVALUES_SPDY, + QUIC: TMP_HTTPFLAVORVALUES_QUIC + }; + TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue"; + TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic"; + MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; + MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; + MessagingDestinationKindValues = /*#__PURE__*/ createConstMap([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]); + TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive"; + TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process"; + MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; + MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; + MessagingOperationValues = /*#__PURE__*/ createConstMap([TMP_MESSAGINGOPERATIONVALUES_RECEIVE, TMP_MESSAGINGOPERATIONVALUES_PROCESS]); + TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; + TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; + TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; + TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; + TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; + TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; + TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; + TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; + TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; + TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; + TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; + TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; + TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; + TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; + TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; + TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; + TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; + RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; + RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; + RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; + RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; + RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; + RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; + RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; + RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; + RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; + RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; + RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; + RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; + RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; + RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; + RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; + RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; + RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; + RpcGrpcStatusCodeValues = { + OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, + CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, + UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, + INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, + DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, + NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, + ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, + PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, + RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, + FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, + ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, + OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, + UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, + INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, + UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, + DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, + UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED + }; + TMP_MESSAGETYPEVALUES_SENT = "SENT"; + TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED"; + MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; + MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; + MessageTypeValues = /*#__PURE__*/ createConstMap([TMP_MESSAGETYPEVALUES_SENT, TMP_MESSAGETYPEVALUES_RECEIVED]); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js +var init_trace = __esmMin((() => { + init_SemanticAttributes(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js +var TMP_CLOUD_PROVIDER, TMP_CLOUD_ACCOUNT_ID, TMP_CLOUD_REGION, TMP_CLOUD_AVAILABILITY_ZONE, TMP_CLOUD_PLATFORM, TMP_AWS_ECS_CONTAINER_ARN, TMP_AWS_ECS_CLUSTER_ARN, TMP_AWS_ECS_LAUNCHTYPE, TMP_AWS_ECS_TASK_ARN, TMP_AWS_ECS_TASK_FAMILY, TMP_AWS_ECS_TASK_REVISION, TMP_AWS_EKS_CLUSTER_ARN, TMP_AWS_LOG_GROUP_NAMES, TMP_AWS_LOG_GROUP_ARNS, TMP_AWS_LOG_STREAM_NAMES, TMP_AWS_LOG_STREAM_ARNS, TMP_CONTAINER_NAME, TMP_CONTAINER_ID, TMP_CONTAINER_RUNTIME, TMP_CONTAINER_IMAGE_NAME, TMP_CONTAINER_IMAGE_TAG, TMP_DEPLOYMENT_ENVIRONMENT, TMP_DEVICE_ID, TMP_DEVICE_MODEL_IDENTIFIER, TMP_DEVICE_MODEL_NAME, TMP_FAAS_NAME, TMP_FAAS_ID, TMP_FAAS_VERSION, TMP_FAAS_INSTANCE, TMP_FAAS_MAX_MEMORY, TMP_HOST_ID, TMP_HOST_NAME, TMP_HOST_TYPE, TMP_HOST_ARCH, TMP_HOST_IMAGE_NAME, TMP_HOST_IMAGE_ID, TMP_HOST_IMAGE_VERSION, TMP_K8S_CLUSTER_NAME, TMP_K8S_NODE_NAME, TMP_K8S_NODE_UID, TMP_K8S_NAMESPACE_NAME, TMP_K8S_POD_UID, TMP_K8S_POD_NAME, TMP_K8S_CONTAINER_NAME, TMP_K8S_REPLICASET_UID, TMP_K8S_REPLICASET_NAME, TMP_K8S_DEPLOYMENT_UID, TMP_K8S_DEPLOYMENT_NAME, TMP_K8S_STATEFULSET_UID, TMP_K8S_STATEFULSET_NAME, TMP_K8S_DAEMONSET_UID, TMP_K8S_DAEMONSET_NAME, TMP_K8S_JOB_UID, TMP_K8S_JOB_NAME, TMP_K8S_CRONJOB_UID, TMP_K8S_CRONJOB_NAME, TMP_OS_TYPE, TMP_OS_DESCRIPTION, TMP_OS_NAME, TMP_OS_VERSION, TMP_PROCESS_PID, TMP_PROCESS_EXECUTABLE_NAME, TMP_PROCESS_EXECUTABLE_PATH, TMP_PROCESS_COMMAND, TMP_PROCESS_COMMAND_LINE, TMP_PROCESS_COMMAND_ARGS, TMP_PROCESS_OWNER, TMP_PROCESS_RUNTIME_NAME, TMP_PROCESS_RUNTIME_VERSION, TMP_PROCESS_RUNTIME_DESCRIPTION, TMP_SERVICE_NAME, TMP_SERVICE_NAMESPACE, TMP_SERVICE_INSTANCE_ID, TMP_SERVICE_VERSION, TMP_TELEMETRY_SDK_NAME, TMP_TELEMETRY_SDK_LANGUAGE, TMP_TELEMETRY_SDK_VERSION, TMP_TELEMETRY_AUTO_VERSION, TMP_WEBENGINE_NAME, TMP_WEBENGINE_VERSION, TMP_WEBENGINE_DESCRIPTION, SEMRESATTRS_CLOUD_PROVIDER, SEMRESATTRS_CLOUD_ACCOUNT_ID, SEMRESATTRS_CLOUD_REGION, SEMRESATTRS_CLOUD_AVAILABILITY_ZONE, SEMRESATTRS_CLOUD_PLATFORM, SEMRESATTRS_AWS_ECS_CONTAINER_ARN, SEMRESATTRS_AWS_ECS_CLUSTER_ARN, SEMRESATTRS_AWS_ECS_LAUNCHTYPE, SEMRESATTRS_AWS_ECS_TASK_ARN, SEMRESATTRS_AWS_ECS_TASK_FAMILY, SEMRESATTRS_AWS_ECS_TASK_REVISION, SEMRESATTRS_AWS_EKS_CLUSTER_ARN, SEMRESATTRS_AWS_LOG_GROUP_NAMES, SEMRESATTRS_AWS_LOG_GROUP_ARNS, SEMRESATTRS_AWS_LOG_STREAM_NAMES, SEMRESATTRS_AWS_LOG_STREAM_ARNS, SEMRESATTRS_CONTAINER_NAME, SEMRESATTRS_CONTAINER_ID, SEMRESATTRS_CONTAINER_RUNTIME, SEMRESATTRS_CONTAINER_IMAGE_NAME, SEMRESATTRS_CONTAINER_IMAGE_TAG, SEMRESATTRS_DEPLOYMENT_ENVIRONMENT, SEMRESATTRS_DEVICE_ID, SEMRESATTRS_DEVICE_MODEL_IDENTIFIER, SEMRESATTRS_DEVICE_MODEL_NAME, SEMRESATTRS_FAAS_NAME, SEMRESATTRS_FAAS_ID, SEMRESATTRS_FAAS_VERSION, SEMRESATTRS_FAAS_INSTANCE, SEMRESATTRS_FAAS_MAX_MEMORY, SEMRESATTRS_HOST_ID, SEMRESATTRS_HOST_NAME, SEMRESATTRS_HOST_TYPE, SEMRESATTRS_HOST_ARCH, SEMRESATTRS_HOST_IMAGE_NAME, SEMRESATTRS_HOST_IMAGE_ID, SEMRESATTRS_HOST_IMAGE_VERSION, SEMRESATTRS_K8S_CLUSTER_NAME, SEMRESATTRS_K8S_NODE_NAME, SEMRESATTRS_K8S_NODE_UID, SEMRESATTRS_K8S_NAMESPACE_NAME, SEMRESATTRS_K8S_POD_UID, SEMRESATTRS_K8S_POD_NAME, SEMRESATTRS_K8S_CONTAINER_NAME, SEMRESATTRS_K8S_REPLICASET_UID, SEMRESATTRS_K8S_REPLICASET_NAME, SEMRESATTRS_K8S_DEPLOYMENT_UID, SEMRESATTRS_K8S_DEPLOYMENT_NAME, SEMRESATTRS_K8S_STATEFULSET_UID, SEMRESATTRS_K8S_STATEFULSET_NAME, SEMRESATTRS_K8S_DAEMONSET_UID, SEMRESATTRS_K8S_DAEMONSET_NAME, SEMRESATTRS_K8S_JOB_UID, SEMRESATTRS_K8S_JOB_NAME, SEMRESATTRS_K8S_CRONJOB_UID, SEMRESATTRS_K8S_CRONJOB_NAME, SEMRESATTRS_OS_TYPE, SEMRESATTRS_OS_DESCRIPTION, SEMRESATTRS_OS_NAME, SEMRESATTRS_OS_VERSION, SEMRESATTRS_PROCESS_PID, SEMRESATTRS_PROCESS_EXECUTABLE_NAME, SEMRESATTRS_PROCESS_EXECUTABLE_PATH, SEMRESATTRS_PROCESS_COMMAND, SEMRESATTRS_PROCESS_COMMAND_LINE, SEMRESATTRS_PROCESS_COMMAND_ARGS, SEMRESATTRS_PROCESS_OWNER, SEMRESATTRS_PROCESS_RUNTIME_NAME, SEMRESATTRS_PROCESS_RUNTIME_VERSION, SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION, SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_NAMESPACE, SEMRESATTRS_SERVICE_INSTANCE_ID, SEMRESATTRS_SERVICE_VERSION, SEMRESATTRS_TELEMETRY_SDK_NAME, SEMRESATTRS_TELEMETRY_SDK_LANGUAGE, SEMRESATTRS_TELEMETRY_SDK_VERSION, SEMRESATTRS_TELEMETRY_AUTO_VERSION, SEMRESATTRS_WEBENGINE_NAME, SEMRESATTRS_WEBENGINE_VERSION, SEMRESATTRS_WEBENGINE_DESCRIPTION, SemanticResourceAttributes, TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, TMP_CLOUDPROVIDERVALUES_AWS, TMP_CLOUDPROVIDERVALUES_AZURE, TMP_CLOUDPROVIDERVALUES_GCP, CLOUDPROVIDERVALUES_ALIBABA_CLOUD, CLOUDPROVIDERVALUES_AWS, CLOUDPROVIDERVALUES_AZURE, CLOUDPROVIDERVALUES_GCP, CloudProviderValues, TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, TMP_CLOUDPLATFORMVALUES_AWS_EC2, TMP_CLOUDPLATFORMVALUES_AWS_ECS, TMP_CLOUDPLATFORMVALUES_AWS_EKS, TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, TMP_CLOUDPLATFORMVALUES_AZURE_VM, TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, TMP_CLOUDPLATFORMVALUES_AZURE_AKS, TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE, CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, CLOUDPLATFORMVALUES_AWS_EC2, CLOUDPLATFORMVALUES_AWS_ECS, CLOUDPLATFORMVALUES_AWS_EKS, CLOUDPLATFORMVALUES_AWS_LAMBDA, CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, CLOUDPLATFORMVALUES_AZURE_VM, CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, CLOUDPLATFORMVALUES_AZURE_AKS, CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, CLOUDPLATFORMVALUES_GCP_APP_ENGINE, CloudPlatformValues, TMP_AWSECSLAUNCHTYPEVALUES_EC2, TMP_AWSECSLAUNCHTYPEVALUES_FARGATE, AWSECSLAUNCHTYPEVALUES_EC2, AWSECSLAUNCHTYPEVALUES_FARGATE, AwsEcsLaunchtypeValues, TMP_HOSTARCHVALUES_AMD64, TMP_HOSTARCHVALUES_ARM32, TMP_HOSTARCHVALUES_ARM64, TMP_HOSTARCHVALUES_IA64, TMP_HOSTARCHVALUES_PPC32, TMP_HOSTARCHVALUES_PPC64, TMP_HOSTARCHVALUES_X86, HOSTARCHVALUES_AMD64, HOSTARCHVALUES_ARM32, HOSTARCHVALUES_ARM64, HOSTARCHVALUES_IA64, HOSTARCHVALUES_PPC32, HOSTARCHVALUES_PPC64, HOSTARCHVALUES_X86, HostArchValues, TMP_OSTYPEVALUES_WINDOWS, TMP_OSTYPEVALUES_LINUX, TMP_OSTYPEVALUES_DARWIN, TMP_OSTYPEVALUES_FREEBSD, TMP_OSTYPEVALUES_NETBSD, TMP_OSTYPEVALUES_OPENBSD, TMP_OSTYPEVALUES_DRAGONFLYBSD, TMP_OSTYPEVALUES_HPUX, TMP_OSTYPEVALUES_AIX, TMP_OSTYPEVALUES_SOLARIS, TMP_OSTYPEVALUES_Z_OS, OSTYPEVALUES_WINDOWS, OSTYPEVALUES_LINUX, OSTYPEVALUES_DARWIN, OSTYPEVALUES_FREEBSD, OSTYPEVALUES_NETBSD, OSTYPEVALUES_OPENBSD, OSTYPEVALUES_DRAGONFLYBSD, OSTYPEVALUES_HPUX, OSTYPEVALUES_AIX, OSTYPEVALUES_SOLARIS, OSTYPEVALUES_Z_OS, OsTypeValues, TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, TMP_TELEMETRYSDKLANGUAGEVALUES_GO, TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS, TELEMETRYSDKLANGUAGEVALUES_CPP, TELEMETRYSDKLANGUAGEVALUES_DOTNET, TELEMETRYSDKLANGUAGEVALUES_ERLANG, TELEMETRYSDKLANGUAGEVALUES_GO, TELEMETRYSDKLANGUAGEVALUES_JAVA, TELEMETRYSDKLANGUAGEVALUES_NODEJS, TELEMETRYSDKLANGUAGEVALUES_PHP, TELEMETRYSDKLANGUAGEVALUES_PYTHON, TELEMETRYSDKLANGUAGEVALUES_RUBY, TELEMETRYSDKLANGUAGEVALUES_WEBJS, TelemetrySdkLanguageValues; +var init_SemanticResourceAttributes = __esmMin((() => { + init_utils(); + TMP_CLOUD_PROVIDER = "cloud.provider"; + TMP_CLOUD_ACCOUNT_ID = "cloud.account.id"; + TMP_CLOUD_REGION = "cloud.region"; + TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; + TMP_CLOUD_PLATFORM = "cloud.platform"; + TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn"; + TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn"; + TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype"; + TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn"; + TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family"; + TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision"; + TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn"; + TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names"; + TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns"; + TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names"; + TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns"; + TMP_CONTAINER_NAME = "container.name"; + TMP_CONTAINER_ID = "container.id"; + TMP_CONTAINER_RUNTIME = "container.runtime"; + TMP_CONTAINER_IMAGE_NAME = "container.image.name"; + TMP_CONTAINER_IMAGE_TAG = "container.image.tag"; + TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment"; + TMP_DEVICE_ID = "device.id"; + TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier"; + TMP_DEVICE_MODEL_NAME = "device.model.name"; + TMP_FAAS_NAME = "faas.name"; + TMP_FAAS_ID = "faas.id"; + TMP_FAAS_VERSION = "faas.version"; + TMP_FAAS_INSTANCE = "faas.instance"; + TMP_FAAS_MAX_MEMORY = "faas.max_memory"; + TMP_HOST_ID = "host.id"; + TMP_HOST_NAME = "host.name"; + TMP_HOST_TYPE = "host.type"; + TMP_HOST_ARCH = "host.arch"; + TMP_HOST_IMAGE_NAME = "host.image.name"; + TMP_HOST_IMAGE_ID = "host.image.id"; + TMP_HOST_IMAGE_VERSION = "host.image.version"; + TMP_K8S_CLUSTER_NAME = "k8s.cluster.name"; + TMP_K8S_NODE_NAME = "k8s.node.name"; + TMP_K8S_NODE_UID = "k8s.node.uid"; + TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + TMP_K8S_POD_UID = "k8s.pod.uid"; + TMP_K8S_POD_NAME = "k8s.pod.name"; + TMP_K8S_CONTAINER_NAME = "k8s.container.name"; + TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid"; + TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name"; + TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; + TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; + TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; + TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; + TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; + TMP_K8S_JOB_UID = "k8s.job.uid"; + TMP_K8S_JOB_NAME = "k8s.job.name"; + TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid"; + TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name"; + TMP_OS_TYPE = "os.type"; + TMP_OS_DESCRIPTION = "os.description"; + TMP_OS_NAME = "os.name"; + TMP_OS_VERSION = "os.version"; + TMP_PROCESS_PID = "process.pid"; + TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name"; + TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path"; + TMP_PROCESS_COMMAND = "process.command"; + TMP_PROCESS_COMMAND_LINE = "process.command_line"; + TMP_PROCESS_COMMAND_ARGS = "process.command_args"; + TMP_PROCESS_OWNER = "process.owner"; + TMP_PROCESS_RUNTIME_NAME = "process.runtime.name"; + TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version"; + TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; + TMP_SERVICE_NAME = "service.name"; + TMP_SERVICE_NAMESPACE = "service.namespace"; + TMP_SERVICE_INSTANCE_ID = "service.instance.id"; + TMP_SERVICE_VERSION = "service.version"; + TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version"; + TMP_WEBENGINE_NAME = "webengine.name"; + TMP_WEBENGINE_VERSION = "webengine.version"; + TMP_WEBENGINE_DESCRIPTION = "webengine.description"; + SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; + SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; + SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; + SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; + SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; + SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; + SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; + SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; + SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; + SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; + SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; + SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; + SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; + SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; + SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; + SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; + SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; + SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; + SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; + SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; + SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; + SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; + SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; + SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; + SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; + SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; + SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; + SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; + SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; + SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; + SEMRESATTRS_HOST_ID = TMP_HOST_ID; + SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; + SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; + SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; + SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; + SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; + SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; + SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; + SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; + SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; + SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; + SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; + SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; + SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; + SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; + SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; + SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; + SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; + SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; + SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; + SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; + SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; + SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; + SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; + SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; + SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; + SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; + SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; + SEMRESATTRS_OS_NAME = TMP_OS_NAME; + SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; + SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; + SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; + SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; + SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; + SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; + SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; + SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; + SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; + SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; + SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; + SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; + SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; + SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; + SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; + SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; + SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; + SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; + SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; + SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; + SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; + SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; + SemanticResourceAttributes = /*#__PURE__*/ createConstMap([ + TMP_CLOUD_PROVIDER, + TMP_CLOUD_ACCOUNT_ID, + TMP_CLOUD_REGION, + TMP_CLOUD_AVAILABILITY_ZONE, + TMP_CLOUD_PLATFORM, + TMP_AWS_ECS_CONTAINER_ARN, + TMP_AWS_ECS_CLUSTER_ARN, + TMP_AWS_ECS_LAUNCHTYPE, + TMP_AWS_ECS_TASK_ARN, + TMP_AWS_ECS_TASK_FAMILY, + TMP_AWS_ECS_TASK_REVISION, + TMP_AWS_EKS_CLUSTER_ARN, + TMP_AWS_LOG_GROUP_NAMES, + TMP_AWS_LOG_GROUP_ARNS, + TMP_AWS_LOG_STREAM_NAMES, + TMP_AWS_LOG_STREAM_ARNS, + TMP_CONTAINER_NAME, + TMP_CONTAINER_ID, + TMP_CONTAINER_RUNTIME, + TMP_CONTAINER_IMAGE_NAME, + TMP_CONTAINER_IMAGE_TAG, + TMP_DEPLOYMENT_ENVIRONMENT, + TMP_DEVICE_ID, + TMP_DEVICE_MODEL_IDENTIFIER, + TMP_DEVICE_MODEL_NAME, + TMP_FAAS_NAME, + TMP_FAAS_ID, + TMP_FAAS_VERSION, + TMP_FAAS_INSTANCE, + TMP_FAAS_MAX_MEMORY, + TMP_HOST_ID, + TMP_HOST_NAME, + TMP_HOST_TYPE, + TMP_HOST_ARCH, + TMP_HOST_IMAGE_NAME, + TMP_HOST_IMAGE_ID, + TMP_HOST_IMAGE_VERSION, + TMP_K8S_CLUSTER_NAME, + TMP_K8S_NODE_NAME, + TMP_K8S_NODE_UID, + TMP_K8S_NAMESPACE_NAME, + TMP_K8S_POD_UID, + TMP_K8S_POD_NAME, + TMP_K8S_CONTAINER_NAME, + TMP_K8S_REPLICASET_UID, + TMP_K8S_REPLICASET_NAME, + TMP_K8S_DEPLOYMENT_UID, + TMP_K8S_DEPLOYMENT_NAME, + TMP_K8S_STATEFULSET_UID, + TMP_K8S_STATEFULSET_NAME, + TMP_K8S_DAEMONSET_UID, + TMP_K8S_DAEMONSET_NAME, + TMP_K8S_JOB_UID, + TMP_K8S_JOB_NAME, + TMP_K8S_CRONJOB_UID, + TMP_K8S_CRONJOB_NAME, + TMP_OS_TYPE, + TMP_OS_DESCRIPTION, + TMP_OS_NAME, + TMP_OS_VERSION, + TMP_PROCESS_PID, + TMP_PROCESS_EXECUTABLE_NAME, + TMP_PROCESS_EXECUTABLE_PATH, + TMP_PROCESS_COMMAND, + TMP_PROCESS_COMMAND_LINE, + TMP_PROCESS_COMMAND_ARGS, + TMP_PROCESS_OWNER, + TMP_PROCESS_RUNTIME_NAME, + TMP_PROCESS_RUNTIME_VERSION, + TMP_PROCESS_RUNTIME_DESCRIPTION, + TMP_SERVICE_NAME, + TMP_SERVICE_NAMESPACE, + TMP_SERVICE_INSTANCE_ID, + TMP_SERVICE_VERSION, + TMP_TELEMETRY_SDK_NAME, + TMP_TELEMETRY_SDK_LANGUAGE, + TMP_TELEMETRY_SDK_VERSION, + TMP_TELEMETRY_AUTO_VERSION, + TMP_WEBENGINE_NAME, + TMP_WEBENGINE_VERSION, + TMP_WEBENGINE_DESCRIPTION + ]); + TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + TMP_CLOUDPROVIDERVALUES_AWS = "aws"; + TMP_CLOUDPROVIDERVALUES_AZURE = "azure"; + TMP_CLOUDPROVIDERVALUES_GCP = "gcp"; + CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; + CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; + CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; + CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; + CloudProviderValues = /*#__PURE__*/ createConstMap([ + TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_CLOUDPROVIDERVALUES_AWS, + TMP_CLOUDPROVIDERVALUES_AZURE, + TMP_CLOUDPROVIDERVALUES_GCP + ]); + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; + TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2"; + TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs"; + TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks"; + TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda"; + TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; + TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm"; + TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances"; + TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks"; + TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions"; + TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service"; + TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine"; + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run"; + TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; + TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine"; + CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; + CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; + CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; + CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; + CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; + CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; + CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; + CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; + CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; + CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; + CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; + CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; + CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; + CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; + CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; + CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; + CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; + CloudPlatformValues = /*#__PURE__*/ createConstMap([ + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, + TMP_CLOUDPLATFORMVALUES_AWS_EC2, + TMP_CLOUDPLATFORMVALUES_AWS_ECS, + TMP_CLOUDPLATFORMVALUES_AWS_EKS, + TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, + TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, + TMP_CLOUDPLATFORMVALUES_AZURE_VM, + TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, + TMP_CLOUDPLATFORMVALUES_AZURE_AKS, + TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, + TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, + TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE + ]); + TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2"; + TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate"; + AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; + AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; + AwsEcsLaunchtypeValues = /*#__PURE__*/ createConstMap([TMP_AWSECSLAUNCHTYPEVALUES_EC2, TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]); + TMP_HOSTARCHVALUES_AMD64 = "amd64"; + TMP_HOSTARCHVALUES_ARM32 = "arm32"; + TMP_HOSTARCHVALUES_ARM64 = "arm64"; + TMP_HOSTARCHVALUES_IA64 = "ia64"; + TMP_HOSTARCHVALUES_PPC32 = "ppc32"; + TMP_HOSTARCHVALUES_PPC64 = "ppc64"; + TMP_HOSTARCHVALUES_X86 = "x86"; + HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; + HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; + HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; + HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; + HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; + HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; + HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; + HostArchValues = /*#__PURE__*/ createConstMap([ + TMP_HOSTARCHVALUES_AMD64, + TMP_HOSTARCHVALUES_ARM32, + TMP_HOSTARCHVALUES_ARM64, + TMP_HOSTARCHVALUES_IA64, + TMP_HOSTARCHVALUES_PPC32, + TMP_HOSTARCHVALUES_PPC64, + TMP_HOSTARCHVALUES_X86 + ]); + TMP_OSTYPEVALUES_WINDOWS = "windows"; + TMP_OSTYPEVALUES_LINUX = "linux"; + TMP_OSTYPEVALUES_DARWIN = "darwin"; + TMP_OSTYPEVALUES_FREEBSD = "freebsd"; + TMP_OSTYPEVALUES_NETBSD = "netbsd"; + TMP_OSTYPEVALUES_OPENBSD = "openbsd"; + TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd"; + TMP_OSTYPEVALUES_HPUX = "hpux"; + TMP_OSTYPEVALUES_AIX = "aix"; + TMP_OSTYPEVALUES_SOLARIS = "solaris"; + TMP_OSTYPEVALUES_Z_OS = "z_os"; + OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; + OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; + OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; + OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; + OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; + OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; + OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; + OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; + OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; + OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; + OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; + OsTypeValues = /*#__PURE__*/ createConstMap([ + TMP_OSTYPEVALUES_WINDOWS, + TMP_OSTYPEVALUES_LINUX, + TMP_OSTYPEVALUES_DARWIN, + TMP_OSTYPEVALUES_FREEBSD, + TMP_OSTYPEVALUES_NETBSD, + TMP_OSTYPEVALUES_OPENBSD, + TMP_OSTYPEVALUES_DRAGONFLYBSD, + TMP_OSTYPEVALUES_HPUX, + TMP_OSTYPEVALUES_AIX, + TMP_OSTYPEVALUES_SOLARIS, + TMP_OSTYPEVALUES_Z_OS + ]); + TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp"; + TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet"; + TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang"; + TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go"; + TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java"; + TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs"; + TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php"; + TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python"; + TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby"; + TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs"; + TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; + TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; + TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; + TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; + TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; + TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; + TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; + TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; + TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; + TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; + TelemetrySdkLanguageValues = /*#__PURE__*/ createConstMap([ + TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, + TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, + TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, + TMP_TELEMETRYSDKLANGUAGEVALUES_GO, + TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, + TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, + TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, + TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, + TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, + TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS + ]); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js +var init_resource = __esmMin((() => { + init_SemanticResourceAttributes(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js +var ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED, ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED, ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE, ATTR_ASPNETCORE_RATE_LIMITING_POLICY, ATTR_ASPNETCORE_RATE_LIMITING_RESULT, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER, ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED, ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED, ATTR_ASPNETCORE_ROUTING_IS_FALLBACK, ATTR_ASPNETCORE_ROUTING_MATCH_STATUS, ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE, ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS, ATTR_ASPNETCORE_USER_IS_AUTHENTICATED, ATTR_CLIENT_ADDRESS, ATTR_CLIENT_PORT, ATTR_CODE_COLUMN_NUMBER, ATTR_CODE_FILE_PATH, ATTR_CODE_FUNCTION_NAME, ATTR_CODE_LINE_NUMBER, ATTR_CODE_STACKTRACE, ATTR_CONTAINER_ID, ATTR_CONTAINER_IMAGE_NAME, ATTR_CONTAINER_IMAGE_REPO_DIGESTS, ATTR_CONTAINER_IMAGE_TAGS, ATTR_DB_COLLECTION_NAME, ATTR_DB_NAMESPACE, ATTR_DB_OPERATION_BATCH_SIZE, ATTR_DB_OPERATION_NAME, ATTR_DB_QUERY_SUMMARY, ATTR_DB_QUERY_TEXT, ATTR_DB_RESPONSE_STATUS_CODE, ATTR_DB_STORED_PROCEDURE_NAME, ATTR_DB_SYSTEM_NAME, DB_SYSTEM_NAME_VALUE_MARIADB, DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER, DB_SYSTEM_NAME_VALUE_MYSQL, DB_SYSTEM_NAME_VALUE_POSTGRESQL, ATTR_DEPLOYMENT_ENVIRONMENT_NAME, DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT, DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION, DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING, DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST, ATTR_DOTNET_GC_HEAP_GENERATION, DOTNET_GC_HEAP_GENERATION_VALUE_GEN0, DOTNET_GC_HEAP_GENERATION_VALUE_GEN1, DOTNET_GC_HEAP_GENERATION_VALUE_GEN2, DOTNET_GC_HEAP_GENERATION_VALUE_LOH, DOTNET_GC_HEAP_GENERATION_VALUE_POH, ATTR_ERROR_TYPE$1, ERROR_TYPE_VALUE_OTHER, ATTR_EXCEPTION_ESCAPED, ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, HTTP_REQUEST_METHOD_VALUE_OTHER, HTTP_REQUEST_METHOD_VALUE_CONNECT, HTTP_REQUEST_METHOD_VALUE_DELETE, HTTP_REQUEST_METHOD_VALUE_GET, HTTP_REQUEST_METHOD_VALUE_HEAD, HTTP_REQUEST_METHOD_VALUE_OPTIONS, HTTP_REQUEST_METHOD_VALUE_PATCH, HTTP_REQUEST_METHOD_VALUE_POST, HTTP_REQUEST_METHOD_VALUE_PUT, HTTP_REQUEST_METHOD_VALUE_TRACE, ATTR_HTTP_REQUEST_METHOD_ORIGINAL, ATTR_HTTP_REQUEST_RESEND_COUNT, ATTR_HTTP_RESPONSE_HEADER, ATTR_HTTP_RESPONSE_STATUS_CODE$1, ATTR_HTTP_ROUTE, ATTR_JVM_GC_ACTION, ATTR_JVM_GC_NAME, ATTR_JVM_MEMORY_POOL_NAME, ATTR_JVM_MEMORY_TYPE, JVM_MEMORY_TYPE_VALUE_HEAP, JVM_MEMORY_TYPE_VALUE_NON_HEAP, ATTR_JVM_THREAD_DAEMON, ATTR_JVM_THREAD_STATE, JVM_THREAD_STATE_VALUE_BLOCKED, JVM_THREAD_STATE_VALUE_NEW, JVM_THREAD_STATE_VALUE_RUNNABLE, JVM_THREAD_STATE_VALUE_TERMINATED, JVM_THREAD_STATE_VALUE_TIMED_WAITING, JVM_THREAD_STATE_VALUE_WAITING, ATTR_K8S_CLUSTER_NAME, ATTR_K8S_CLUSTER_UID, ATTR_K8S_CONTAINER_NAME, ATTR_K8S_CONTAINER_RESTART_COUNT, ATTR_K8S_CRONJOB_ANNOTATION, ATTR_K8S_CRONJOB_LABEL, ATTR_K8S_CRONJOB_NAME, ATTR_K8S_CRONJOB_UID, ATTR_K8S_DAEMONSET_ANNOTATION, ATTR_K8S_DAEMONSET_LABEL, ATTR_K8S_DAEMONSET_NAME, ATTR_K8S_DAEMONSET_UID, ATTR_K8S_DEPLOYMENT_ANNOTATION, ATTR_K8S_DEPLOYMENT_LABEL, ATTR_K8S_DEPLOYMENT_NAME, ATTR_K8S_DEPLOYMENT_UID, ATTR_K8S_JOB_ANNOTATION, ATTR_K8S_JOB_LABEL, ATTR_K8S_JOB_NAME, ATTR_K8S_JOB_UID, ATTR_K8S_NAMESPACE_ANNOTATION, ATTR_K8S_NAMESPACE_LABEL, ATTR_K8S_NAMESPACE_NAME, ATTR_K8S_NODE_ANNOTATION, ATTR_K8S_NODE_LABEL, ATTR_K8S_NODE_NAME, ATTR_K8S_NODE_UID, ATTR_K8S_POD_ANNOTATION, ATTR_K8S_POD_HOSTNAME, ATTR_K8S_POD_IP, ATTR_K8S_POD_LABEL, ATTR_K8S_POD_NAME, ATTR_K8S_POD_START_TIME, ATTR_K8S_POD_UID, ATTR_K8S_REPLICASET_ANNOTATION, ATTR_K8S_REPLICASET_LABEL, ATTR_K8S_REPLICASET_NAME, ATTR_K8S_REPLICASET_UID, ATTR_K8S_STATEFULSET_ANNOTATION, ATTR_K8S_STATEFULSET_LABEL, ATTR_K8S_STATEFULSET_NAME, ATTR_K8S_STATEFULSET_UID, ATTR_NETWORK_LOCAL_ADDRESS, ATTR_NETWORK_LOCAL_PORT, ATTR_NETWORK_PEER_ADDRESS, ATTR_NETWORK_PEER_PORT, ATTR_NETWORK_PROTOCOL_NAME, ATTR_NETWORK_PROTOCOL_VERSION, ATTR_NETWORK_TRANSPORT, NETWORK_TRANSPORT_VALUE_PIPE, NETWORK_TRANSPORT_VALUE_QUIC, NETWORK_TRANSPORT_VALUE_TCP, NETWORK_TRANSPORT_VALUE_UDP, NETWORK_TRANSPORT_VALUE_UNIX, ATTR_NETWORK_TYPE, NETWORK_TYPE_VALUE_IPV4, NETWORK_TYPE_VALUE_IPV6, ATTR_OTEL_EVENT_NAME, ATTR_OTEL_SCOPE_NAME, ATTR_OTEL_SCOPE_VERSION, ATTR_OTEL_STATUS_CODE, OTEL_STATUS_CODE_VALUE_ERROR, OTEL_STATUS_CODE_VALUE_OK, ATTR_OTEL_STATUS_DESCRIPTION, ATTR_SERVER_ADDRESS$1, ATTR_SERVER_PORT$1, ATTR_SERVICE_INSTANCE_ID, ATTR_SERVICE_NAME, ATTR_SERVICE_NAMESPACE, ATTR_SERVICE_VERSION, ATTR_SIGNALR_CONNECTION_STATUS, SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN, SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE, SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT, ATTR_SIGNALR_TRANSPORT, SIGNALR_TRANSPORT_VALUE_LONG_POLLING, SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS, SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS, ATTR_TELEMETRY_DISTRO_NAME, ATTR_TELEMETRY_DISTRO_VERSION, ATTR_TELEMETRY_SDK_LANGUAGE, TELEMETRY_SDK_LANGUAGE_VALUE_CPP, TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET, TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG, TELEMETRY_SDK_LANGUAGE_VALUE_GO, TELEMETRY_SDK_LANGUAGE_VALUE_JAVA, TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN, TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, TELEMETRY_SDK_LANGUAGE_VALUE_PHP, TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON, TELEMETRY_SDK_LANGUAGE_VALUE_RUBY, TELEMETRY_SDK_LANGUAGE_VALUE_RUST, TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT, TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_VERSION, ATTR_URL_FRAGMENT, ATTR_URL_FULL, ATTR_URL_PATH, ATTR_URL_QUERY, ATTR_URL_SCHEME, ATTR_USER_AGENT_ORIGINAL; +var init_stable_attributes = __esmMin((() => { + ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result"; + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; + ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type"; + ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy"; + ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result"; + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; + ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled"; + ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback"; + ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status"; + ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; + ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; + ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = "aspnetcore.user.is_authenticated"; + ATTR_CLIENT_ADDRESS = "client.address"; + ATTR_CLIENT_PORT = "client.port"; + ATTR_CODE_COLUMN_NUMBER = "code.column.number"; + ATTR_CODE_FILE_PATH = "code.file.path"; + ATTR_CODE_FUNCTION_NAME = "code.function.name"; + ATTR_CODE_LINE_NUMBER = "code.line.number"; + ATTR_CODE_STACKTRACE = "code.stacktrace"; + ATTR_CONTAINER_ID = "container.id"; + ATTR_CONTAINER_IMAGE_NAME = "container.image.name"; + ATTR_CONTAINER_IMAGE_REPO_DIGESTS = "container.image.repo_digests"; + ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags"; + ATTR_DB_COLLECTION_NAME = "db.collection.name"; + ATTR_DB_NAMESPACE = "db.namespace"; + ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size"; + ATTR_DB_OPERATION_NAME = "db.operation.name"; + ATTR_DB_QUERY_SUMMARY = "db.query.summary"; + ATTR_DB_QUERY_TEXT = "db.query.text"; + ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code"; + ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name"; + ATTR_DB_SYSTEM_NAME = "db.system.name"; + DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; + DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; + DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; + DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; + ATTR_DEPLOYMENT_ENVIRONMENT_NAME = "deployment.environment.name"; + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = "development"; + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = "production"; + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = "staging"; + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = "test"; + ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation"; + DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; + DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; + DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; + DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; + DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; + ATTR_ERROR_TYPE$1 = "error.type"; + ERROR_TYPE_VALUE_OTHER = "_OTHER"; + ATTR_EXCEPTION_ESCAPED = "exception.escaped"; + ATTR_EXCEPTION_MESSAGE = "exception.message"; + ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace"; + ATTR_EXCEPTION_TYPE = "exception.type"; + ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; + ATTR_HTTP_REQUEST_METHOD = "http.request.method"; + HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; + HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; + HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; + HTTP_REQUEST_METHOD_VALUE_GET = "GET"; + HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; + HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; + HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; + HTTP_REQUEST_METHOD_VALUE_POST = "POST"; + HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; + HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; + ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original"; + ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count"; + ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; + ATTR_HTTP_RESPONSE_STATUS_CODE$1 = "http.response.status_code"; + ATTR_HTTP_ROUTE = "http.route"; + ATTR_JVM_GC_ACTION = "jvm.gc.action"; + ATTR_JVM_GC_NAME = "jvm.gc.name"; + ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name"; + ATTR_JVM_MEMORY_TYPE = "jvm.memory.type"; + JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; + JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; + ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon"; + ATTR_JVM_THREAD_STATE = "jvm.thread.state"; + JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; + JVM_THREAD_STATE_VALUE_NEW = "new"; + JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; + JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; + JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; + JVM_THREAD_STATE_VALUE_WAITING = "waiting"; + ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name"; + ATTR_K8S_CLUSTER_UID = "k8s.cluster.uid"; + ATTR_K8S_CONTAINER_NAME = "k8s.container.name"; + ATTR_K8S_CONTAINER_RESTART_COUNT = "k8s.container.restart_count"; + ATTR_K8S_CRONJOB_ANNOTATION = (key) => `k8s.cronjob.annotation.${key}`; + ATTR_K8S_CRONJOB_LABEL = (key) => `k8s.cronjob.label.${key}`; + ATTR_K8S_CRONJOB_NAME = "k8s.cronjob.name"; + ATTR_K8S_CRONJOB_UID = "k8s.cronjob.uid"; + ATTR_K8S_DAEMONSET_ANNOTATION = (key) => `k8s.daemonset.annotation.${key}`; + ATTR_K8S_DAEMONSET_LABEL = (key) => `k8s.daemonset.label.${key}`; + ATTR_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; + ATTR_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; + ATTR_K8S_DEPLOYMENT_ANNOTATION = (key) => `k8s.deployment.annotation.${key}`; + ATTR_K8S_DEPLOYMENT_LABEL = (key) => `k8s.deployment.label.${key}`; + ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + ATTR_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; + ATTR_K8S_JOB_ANNOTATION = (key) => `k8s.job.annotation.${key}`; + ATTR_K8S_JOB_LABEL = (key) => `k8s.job.label.${key}`; + ATTR_K8S_JOB_NAME = "k8s.job.name"; + ATTR_K8S_JOB_UID = "k8s.job.uid"; + ATTR_K8S_NAMESPACE_ANNOTATION = (key) => `k8s.namespace.annotation.${key}`; + ATTR_K8S_NAMESPACE_LABEL = (key) => `k8s.namespace.label.${key}`; + ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + ATTR_K8S_NODE_ANNOTATION = (key) => `k8s.node.annotation.${key}`; + ATTR_K8S_NODE_LABEL = (key) => `k8s.node.label.${key}`; + ATTR_K8S_NODE_NAME = "k8s.node.name"; + ATTR_K8S_NODE_UID = "k8s.node.uid"; + ATTR_K8S_POD_ANNOTATION = (key) => `k8s.pod.annotation.${key}`; + ATTR_K8S_POD_HOSTNAME = "k8s.pod.hostname"; + ATTR_K8S_POD_IP = "k8s.pod.ip"; + ATTR_K8S_POD_LABEL = (key) => `k8s.pod.label.${key}`; + ATTR_K8S_POD_NAME = "k8s.pod.name"; + ATTR_K8S_POD_START_TIME = "k8s.pod.start_time"; + ATTR_K8S_POD_UID = "k8s.pod.uid"; + ATTR_K8S_REPLICASET_ANNOTATION = (key) => `k8s.replicaset.annotation.${key}`; + ATTR_K8S_REPLICASET_LABEL = (key) => `k8s.replicaset.label.${key}`; + ATTR_K8S_REPLICASET_NAME = "k8s.replicaset.name"; + ATTR_K8S_REPLICASET_UID = "k8s.replicaset.uid"; + ATTR_K8S_STATEFULSET_ANNOTATION = (key) => `k8s.statefulset.annotation.${key}`; + ATTR_K8S_STATEFULSET_LABEL = (key) => `k8s.statefulset.label.${key}`; + ATTR_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; + ATTR_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; + ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address"; + ATTR_NETWORK_LOCAL_PORT = "network.local.port"; + ATTR_NETWORK_PEER_ADDRESS = "network.peer.address"; + ATTR_NETWORK_PEER_PORT = "network.peer.port"; + ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name"; + ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version"; + ATTR_NETWORK_TRANSPORT = "network.transport"; + NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; + NETWORK_TRANSPORT_VALUE_QUIC = "quic"; + NETWORK_TRANSPORT_VALUE_TCP = "tcp"; + NETWORK_TRANSPORT_VALUE_UDP = "udp"; + NETWORK_TRANSPORT_VALUE_UNIX = "unix"; + ATTR_NETWORK_TYPE = "network.type"; + NETWORK_TYPE_VALUE_IPV4 = "ipv4"; + NETWORK_TYPE_VALUE_IPV6 = "ipv6"; + ATTR_OTEL_EVENT_NAME = "otel.event.name"; + ATTR_OTEL_SCOPE_NAME = "otel.scope.name"; + ATTR_OTEL_SCOPE_VERSION = "otel.scope.version"; + ATTR_OTEL_STATUS_CODE = "otel.status_code"; + OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; + OTEL_STATUS_CODE_VALUE_OK = "OK"; + ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description"; + ATTR_SERVER_ADDRESS$1 = "server.address"; + ATTR_SERVER_PORT$1 = "server.port"; + ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; + ATTR_SERVICE_NAME = "service.name"; + ATTR_SERVICE_NAMESPACE = "service.namespace"; + ATTR_SERVICE_VERSION = "service.version"; + ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status"; + SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; + SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; + SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; + ATTR_SIGNALR_TRANSPORT = "signalr.transport"; + SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; + SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; + SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; + ATTR_TELEMETRY_DISTRO_NAME = "telemetry.distro.name"; + ATTR_TELEMETRY_DISTRO_VERSION = "telemetry.distro.version"; + ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; + TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; + TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; + TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; + TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; + TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = "kotlin"; + TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; + TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; + TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; + TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; + TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; + TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; + TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; + ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + ATTR_URL_FRAGMENT = "url.fragment"; + ATTR_URL_FULL = "url.full"; + ATTR_URL_PATH = "url.path"; + ATTR_URL_QUERY = "url.query"; + ATTR_URL_SCHEME = "url.scheme"; + ATTR_USER_AGENT_ORIGINAL = "user_agent.original"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js +var METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS, METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES, METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS, METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE, METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION, METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS, METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS, METRIC_DB_CLIENT_OPERATION_DURATION, METRIC_DOTNET_ASSEMBLY_COUNT, METRIC_DOTNET_EXCEPTIONS, METRIC_DOTNET_GC_COLLECTIONS, METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED, METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE, METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE, METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE, METRIC_DOTNET_GC_PAUSE_TIME, METRIC_DOTNET_JIT_COMPILATION_TIME, METRIC_DOTNET_JIT_COMPILED_IL_SIZE, METRIC_DOTNET_JIT_COMPILED_METHODS, METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS, METRIC_DOTNET_PROCESS_CPU_COUNT, METRIC_DOTNET_PROCESS_CPU_TIME, METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET, METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH, METRIC_DOTNET_THREAD_POOL_THREAD_COUNT, METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT, METRIC_DOTNET_TIMER_COUNT, METRIC_HTTP_CLIENT_REQUEST_DURATION, METRIC_HTTP_SERVER_REQUEST_DURATION, METRIC_JVM_CLASS_COUNT, METRIC_JVM_CLASS_LOADED, METRIC_JVM_CLASS_UNLOADED, METRIC_JVM_CPU_COUNT, METRIC_JVM_CPU_RECENT_UTILIZATION, METRIC_JVM_CPU_TIME, METRIC_JVM_GC_DURATION, METRIC_JVM_MEMORY_COMMITTED, METRIC_JVM_MEMORY_LIMIT, METRIC_JVM_MEMORY_USED, METRIC_JVM_MEMORY_USED_AFTER_LAST_GC, METRIC_JVM_THREAD_COUNT, METRIC_KESTREL_ACTIVE_CONNECTIONS, METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES, METRIC_KESTREL_CONNECTION_DURATION, METRIC_KESTREL_QUEUED_CONNECTIONS, METRIC_KESTREL_QUEUED_REQUESTS, METRIC_KESTREL_REJECTED_CONNECTIONS, METRIC_KESTREL_TLS_HANDSHAKE_DURATION, METRIC_KESTREL_UPGRADED_CONNECTIONS, METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS, METRIC_SIGNALR_SERVER_CONNECTION_DURATION; +var init_stable_metrics = __esmMin((() => { + METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions"; + METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases"; + METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests"; + METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue"; + METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration"; + METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests"; + METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts"; + METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration"; + METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count"; + METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions"; + METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections"; + METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated"; + METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size"; + METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size"; + METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size"; + METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time"; + METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time"; + METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size"; + METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods"; + METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions"; + METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count"; + METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time"; + METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set"; + METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length"; + METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count"; + METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count"; + METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count"; + METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration"; + METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration"; + METRIC_JVM_CLASS_COUNT = "jvm.class.count"; + METRIC_JVM_CLASS_LOADED = "jvm.class.loaded"; + METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded"; + METRIC_JVM_CPU_COUNT = "jvm.cpu.count"; + METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization"; + METRIC_JVM_CPU_TIME = "jvm.cpu.time"; + METRIC_JVM_GC_DURATION = "jvm.gc.duration"; + METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed"; + METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit"; + METRIC_JVM_MEMORY_USED = "jvm.memory.used"; + METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc"; + METRIC_JVM_THREAD_COUNT = "jvm.thread.count"; + METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections"; + METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes"; + METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration"; + METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections"; + METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests"; + METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections"; + METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration"; + METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections"; + METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections"; + METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.js +var EVENT_EXCEPTION; +var init_stable_events = __esmMin((() => { + EVENT_EXCEPTION = "exception"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.43.0/node_modules/@opentelemetry/semantic-conventions/build/esm/index.js +var esm_exports$1 = /* @__PURE__ */ __exportAll({ + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED, + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED, + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED, + ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED: () => ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED, + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED, + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER, + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER, + ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED: () => ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED, + ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE: () => ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE, + ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS: () => ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS, + ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT: () => ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT, + ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE: () => ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE, + ATTR_ASPNETCORE_RATE_LIMITING_POLICY: () => ATTR_ASPNETCORE_RATE_LIMITING_POLICY, + ATTR_ASPNETCORE_RATE_LIMITING_RESULT: () => ATTR_ASPNETCORE_RATE_LIMITING_RESULT, + ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED: () => ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED, + ATTR_ASPNETCORE_ROUTING_IS_FALLBACK: () => ATTR_ASPNETCORE_ROUTING_IS_FALLBACK, + ATTR_ASPNETCORE_ROUTING_MATCH_STATUS: () => ATTR_ASPNETCORE_ROUTING_MATCH_STATUS, + ATTR_ASPNETCORE_USER_IS_AUTHENTICATED: () => ATTR_ASPNETCORE_USER_IS_AUTHENTICATED, + ATTR_CLIENT_ADDRESS: () => ATTR_CLIENT_ADDRESS, + ATTR_CLIENT_PORT: () => ATTR_CLIENT_PORT, + ATTR_CODE_COLUMN_NUMBER: () => ATTR_CODE_COLUMN_NUMBER, + ATTR_CODE_FILE_PATH: () => ATTR_CODE_FILE_PATH, + ATTR_CODE_FUNCTION_NAME: () => ATTR_CODE_FUNCTION_NAME, + ATTR_CODE_LINE_NUMBER: () => ATTR_CODE_LINE_NUMBER, + ATTR_CODE_STACKTRACE: () => ATTR_CODE_STACKTRACE, + ATTR_CONTAINER_ID: () => ATTR_CONTAINER_ID, + ATTR_CONTAINER_IMAGE_NAME: () => ATTR_CONTAINER_IMAGE_NAME, + ATTR_CONTAINER_IMAGE_REPO_DIGESTS: () => ATTR_CONTAINER_IMAGE_REPO_DIGESTS, + ATTR_CONTAINER_IMAGE_TAGS: () => ATTR_CONTAINER_IMAGE_TAGS, + ATTR_DB_COLLECTION_NAME: () => ATTR_DB_COLLECTION_NAME, + ATTR_DB_NAMESPACE: () => ATTR_DB_NAMESPACE, + ATTR_DB_OPERATION_BATCH_SIZE: () => ATTR_DB_OPERATION_BATCH_SIZE, + ATTR_DB_OPERATION_NAME: () => ATTR_DB_OPERATION_NAME, + ATTR_DB_QUERY_SUMMARY: () => ATTR_DB_QUERY_SUMMARY, + ATTR_DB_QUERY_TEXT: () => ATTR_DB_QUERY_TEXT, + ATTR_DB_RESPONSE_STATUS_CODE: () => ATTR_DB_RESPONSE_STATUS_CODE, + ATTR_DB_STORED_PROCEDURE_NAME: () => ATTR_DB_STORED_PROCEDURE_NAME, + ATTR_DB_SYSTEM_NAME: () => ATTR_DB_SYSTEM_NAME, + ATTR_DEPLOYMENT_ENVIRONMENT_NAME: () => ATTR_DEPLOYMENT_ENVIRONMENT_NAME, + ATTR_DOTNET_GC_HEAP_GENERATION: () => ATTR_DOTNET_GC_HEAP_GENERATION, + ATTR_ERROR_TYPE: () => ATTR_ERROR_TYPE$1, + ATTR_EXCEPTION_ESCAPED: () => ATTR_EXCEPTION_ESCAPED, + ATTR_EXCEPTION_MESSAGE: () => ATTR_EXCEPTION_MESSAGE, + ATTR_EXCEPTION_STACKTRACE: () => ATTR_EXCEPTION_STACKTRACE, + ATTR_EXCEPTION_TYPE: () => ATTR_EXCEPTION_TYPE, + ATTR_HTTP_REQUEST_HEADER: () => ATTR_HTTP_REQUEST_HEADER, + ATTR_HTTP_REQUEST_METHOD: () => ATTR_HTTP_REQUEST_METHOD, + ATTR_HTTP_REQUEST_METHOD_ORIGINAL: () => ATTR_HTTP_REQUEST_METHOD_ORIGINAL, + ATTR_HTTP_REQUEST_RESEND_COUNT: () => ATTR_HTTP_REQUEST_RESEND_COUNT, + ATTR_HTTP_RESPONSE_HEADER: () => ATTR_HTTP_RESPONSE_HEADER, + ATTR_HTTP_RESPONSE_STATUS_CODE: () => ATTR_HTTP_RESPONSE_STATUS_CODE$1, + ATTR_HTTP_ROUTE: () => ATTR_HTTP_ROUTE, + ATTR_JVM_GC_ACTION: () => ATTR_JVM_GC_ACTION, + ATTR_JVM_GC_NAME: () => ATTR_JVM_GC_NAME, + ATTR_JVM_MEMORY_POOL_NAME: () => ATTR_JVM_MEMORY_POOL_NAME, + ATTR_JVM_MEMORY_TYPE: () => ATTR_JVM_MEMORY_TYPE, + ATTR_JVM_THREAD_DAEMON: () => ATTR_JVM_THREAD_DAEMON, + ATTR_JVM_THREAD_STATE: () => ATTR_JVM_THREAD_STATE, + ATTR_K8S_CLUSTER_NAME: () => ATTR_K8S_CLUSTER_NAME, + ATTR_K8S_CLUSTER_UID: () => ATTR_K8S_CLUSTER_UID, + ATTR_K8S_CONTAINER_NAME: () => ATTR_K8S_CONTAINER_NAME, + ATTR_K8S_CONTAINER_RESTART_COUNT: () => ATTR_K8S_CONTAINER_RESTART_COUNT, + ATTR_K8S_CRONJOB_ANNOTATION: () => ATTR_K8S_CRONJOB_ANNOTATION, + ATTR_K8S_CRONJOB_LABEL: () => ATTR_K8S_CRONJOB_LABEL, + ATTR_K8S_CRONJOB_NAME: () => ATTR_K8S_CRONJOB_NAME, + ATTR_K8S_CRONJOB_UID: () => ATTR_K8S_CRONJOB_UID, + ATTR_K8S_DAEMONSET_ANNOTATION: () => ATTR_K8S_DAEMONSET_ANNOTATION, + ATTR_K8S_DAEMONSET_LABEL: () => ATTR_K8S_DAEMONSET_LABEL, + ATTR_K8S_DAEMONSET_NAME: () => ATTR_K8S_DAEMONSET_NAME, + ATTR_K8S_DAEMONSET_UID: () => ATTR_K8S_DAEMONSET_UID, + ATTR_K8S_DEPLOYMENT_ANNOTATION: () => ATTR_K8S_DEPLOYMENT_ANNOTATION, + ATTR_K8S_DEPLOYMENT_LABEL: () => ATTR_K8S_DEPLOYMENT_LABEL, + ATTR_K8S_DEPLOYMENT_NAME: () => ATTR_K8S_DEPLOYMENT_NAME, + ATTR_K8S_DEPLOYMENT_UID: () => ATTR_K8S_DEPLOYMENT_UID, + ATTR_K8S_JOB_ANNOTATION: () => ATTR_K8S_JOB_ANNOTATION, + ATTR_K8S_JOB_LABEL: () => ATTR_K8S_JOB_LABEL, + ATTR_K8S_JOB_NAME: () => ATTR_K8S_JOB_NAME, + ATTR_K8S_JOB_UID: () => ATTR_K8S_JOB_UID, + ATTR_K8S_NAMESPACE_ANNOTATION: () => ATTR_K8S_NAMESPACE_ANNOTATION, + ATTR_K8S_NAMESPACE_LABEL: () => ATTR_K8S_NAMESPACE_LABEL, + ATTR_K8S_NAMESPACE_NAME: () => ATTR_K8S_NAMESPACE_NAME, + ATTR_K8S_NODE_ANNOTATION: () => ATTR_K8S_NODE_ANNOTATION, + ATTR_K8S_NODE_LABEL: () => ATTR_K8S_NODE_LABEL, + ATTR_K8S_NODE_NAME: () => ATTR_K8S_NODE_NAME, + ATTR_K8S_NODE_UID: () => ATTR_K8S_NODE_UID, + ATTR_K8S_POD_ANNOTATION: () => ATTR_K8S_POD_ANNOTATION, + ATTR_K8S_POD_HOSTNAME: () => ATTR_K8S_POD_HOSTNAME, + ATTR_K8S_POD_IP: () => ATTR_K8S_POD_IP, + ATTR_K8S_POD_LABEL: () => ATTR_K8S_POD_LABEL, + ATTR_K8S_POD_NAME: () => ATTR_K8S_POD_NAME, + ATTR_K8S_POD_START_TIME: () => ATTR_K8S_POD_START_TIME, + ATTR_K8S_POD_UID: () => ATTR_K8S_POD_UID, + ATTR_K8S_REPLICASET_ANNOTATION: () => ATTR_K8S_REPLICASET_ANNOTATION, + ATTR_K8S_REPLICASET_LABEL: () => ATTR_K8S_REPLICASET_LABEL, + ATTR_K8S_REPLICASET_NAME: () => ATTR_K8S_REPLICASET_NAME, + ATTR_K8S_REPLICASET_UID: () => ATTR_K8S_REPLICASET_UID, + ATTR_K8S_STATEFULSET_ANNOTATION: () => ATTR_K8S_STATEFULSET_ANNOTATION, + ATTR_K8S_STATEFULSET_LABEL: () => ATTR_K8S_STATEFULSET_LABEL, + ATTR_K8S_STATEFULSET_NAME: () => ATTR_K8S_STATEFULSET_NAME, + ATTR_K8S_STATEFULSET_UID: () => ATTR_K8S_STATEFULSET_UID, + ATTR_NETWORK_LOCAL_ADDRESS: () => ATTR_NETWORK_LOCAL_ADDRESS, + ATTR_NETWORK_LOCAL_PORT: () => ATTR_NETWORK_LOCAL_PORT, + ATTR_NETWORK_PEER_ADDRESS: () => ATTR_NETWORK_PEER_ADDRESS, + ATTR_NETWORK_PEER_PORT: () => ATTR_NETWORK_PEER_PORT, + ATTR_NETWORK_PROTOCOL_NAME: () => ATTR_NETWORK_PROTOCOL_NAME, + ATTR_NETWORK_PROTOCOL_VERSION: () => ATTR_NETWORK_PROTOCOL_VERSION, + ATTR_NETWORK_TRANSPORT: () => ATTR_NETWORK_TRANSPORT, + ATTR_NETWORK_TYPE: () => ATTR_NETWORK_TYPE, + ATTR_OTEL_EVENT_NAME: () => ATTR_OTEL_EVENT_NAME, + ATTR_OTEL_SCOPE_NAME: () => ATTR_OTEL_SCOPE_NAME, + ATTR_OTEL_SCOPE_VERSION: () => ATTR_OTEL_SCOPE_VERSION, + ATTR_OTEL_STATUS_CODE: () => ATTR_OTEL_STATUS_CODE, + ATTR_OTEL_STATUS_DESCRIPTION: () => ATTR_OTEL_STATUS_DESCRIPTION, + ATTR_SERVER_ADDRESS: () => ATTR_SERVER_ADDRESS$1, + ATTR_SERVER_PORT: () => ATTR_SERVER_PORT$1, + ATTR_SERVICE_INSTANCE_ID: () => ATTR_SERVICE_INSTANCE_ID, + ATTR_SERVICE_NAME: () => ATTR_SERVICE_NAME, + ATTR_SERVICE_NAMESPACE: () => ATTR_SERVICE_NAMESPACE, + ATTR_SERVICE_VERSION: () => ATTR_SERVICE_VERSION, + ATTR_SIGNALR_CONNECTION_STATUS: () => ATTR_SIGNALR_CONNECTION_STATUS, + ATTR_SIGNALR_TRANSPORT: () => ATTR_SIGNALR_TRANSPORT, + ATTR_TELEMETRY_DISTRO_NAME: () => ATTR_TELEMETRY_DISTRO_NAME, + ATTR_TELEMETRY_DISTRO_VERSION: () => ATTR_TELEMETRY_DISTRO_VERSION, + ATTR_TELEMETRY_SDK_LANGUAGE: () => ATTR_TELEMETRY_SDK_LANGUAGE, + ATTR_TELEMETRY_SDK_NAME: () => ATTR_TELEMETRY_SDK_NAME, + ATTR_TELEMETRY_SDK_VERSION: () => ATTR_TELEMETRY_SDK_VERSION, + ATTR_URL_FRAGMENT: () => ATTR_URL_FRAGMENT, + ATTR_URL_FULL: () => ATTR_URL_FULL, + ATTR_URL_PATH: () => ATTR_URL_PATH, + ATTR_URL_QUERY: () => ATTR_URL_QUERY, + ATTR_URL_SCHEME: () => ATTR_URL_SCHEME, + ATTR_USER_AGENT_ORIGINAL: () => ATTR_USER_AGENT_ORIGINAL, + AWSECSLAUNCHTYPEVALUES_EC2: () => "ec2", + AWSECSLAUNCHTYPEVALUES_FARGATE: () => AWSECSLAUNCHTYPEVALUES_FARGATE, + AwsEcsLaunchtypeValues: () => AwsEcsLaunchtypeValues, + CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS: () => CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, + CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC: () => CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, + CLOUDPLATFORMVALUES_AWS_EC2: () => CLOUDPLATFORMVALUES_AWS_EC2, + CLOUDPLATFORMVALUES_AWS_ECS: () => CLOUDPLATFORMVALUES_AWS_ECS, + CLOUDPLATFORMVALUES_AWS_EKS: () => CLOUDPLATFORMVALUES_AWS_EKS, + CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK: () => CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, + CLOUDPLATFORMVALUES_AWS_LAMBDA: () => CLOUDPLATFORMVALUES_AWS_LAMBDA, + CLOUDPLATFORMVALUES_AZURE_AKS: () => CLOUDPLATFORMVALUES_AZURE_AKS, + CLOUDPLATFORMVALUES_AZURE_APP_SERVICE: () => CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, + CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES: () => CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, + CLOUDPLATFORMVALUES_AZURE_FUNCTIONS: () => CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, + CLOUDPLATFORMVALUES_AZURE_VM: () => CLOUDPLATFORMVALUES_AZURE_VM, + CLOUDPLATFORMVALUES_GCP_APP_ENGINE: () => CLOUDPLATFORMVALUES_GCP_APP_ENGINE, + CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS: () => CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, + CLOUDPLATFORMVALUES_GCP_CLOUD_RUN: () => CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, + CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE: () => CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, + CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE: () => CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, + CLOUDPROVIDERVALUES_ALIBABA_CLOUD: () => CLOUDPROVIDERVALUES_ALIBABA_CLOUD, + CLOUDPROVIDERVALUES_AWS: () => "aws", + CLOUDPROVIDERVALUES_AZURE: () => CLOUDPROVIDERVALUES_AZURE, + CLOUDPROVIDERVALUES_GCP: () => "gcp", + CloudPlatformValues: () => CloudPlatformValues, + CloudProviderValues: () => CloudProviderValues, + DBCASSANDRACONSISTENCYLEVELVALUES_ALL: () => "all", + DBCASSANDRACONSISTENCYLEVELVALUES_ANY: () => "any", + DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM: () => DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, + DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE: () => DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, + DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM: () => DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, + DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL: () => DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, + DBCASSANDRACONSISTENCYLEVELVALUES_ONE: () => "one", + DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM: () => DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, + DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL: () => DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, + DBCASSANDRACONSISTENCYLEVELVALUES_THREE: () => DBCASSANDRACONSISTENCYLEVELVALUES_THREE, + DBCASSANDRACONSISTENCYLEVELVALUES_TWO: () => "two", + DBSYSTEMVALUES_ADABAS: () => DBSYSTEMVALUES_ADABAS, + DBSYSTEMVALUES_CACHE: () => DBSYSTEMVALUES_CACHE, + DBSYSTEMVALUES_CASSANDRA: () => DBSYSTEMVALUES_CASSANDRA, + DBSYSTEMVALUES_CLOUDSCAPE: () => DBSYSTEMVALUES_CLOUDSCAPE, + DBSYSTEMVALUES_COCKROACHDB: () => DBSYSTEMVALUES_COCKROACHDB, + DBSYSTEMVALUES_COLDFUSION: () => DBSYSTEMVALUES_COLDFUSION, + DBSYSTEMVALUES_COSMOSDB: () => DBSYSTEMVALUES_COSMOSDB, + DBSYSTEMVALUES_COUCHBASE: () => DBSYSTEMVALUES_COUCHBASE, + DBSYSTEMVALUES_COUCHDB: () => DBSYSTEMVALUES_COUCHDB, + DBSYSTEMVALUES_DB2: () => "db2", + DBSYSTEMVALUES_DERBY: () => DBSYSTEMVALUES_DERBY, + DBSYSTEMVALUES_DYNAMODB: () => DBSYSTEMVALUES_DYNAMODB, + DBSYSTEMVALUES_EDB: () => "edb", + DBSYSTEMVALUES_ELASTICSEARCH: () => DBSYSTEMVALUES_ELASTICSEARCH, + DBSYSTEMVALUES_FILEMAKER: () => DBSYSTEMVALUES_FILEMAKER, + DBSYSTEMVALUES_FIREBIRD: () => DBSYSTEMVALUES_FIREBIRD, + DBSYSTEMVALUES_FIRSTSQL: () => DBSYSTEMVALUES_FIRSTSQL, + DBSYSTEMVALUES_GEODE: () => DBSYSTEMVALUES_GEODE, + DBSYSTEMVALUES_H2: () => "h2", + DBSYSTEMVALUES_HANADB: () => DBSYSTEMVALUES_HANADB, + DBSYSTEMVALUES_HBASE: () => DBSYSTEMVALUES_HBASE, + DBSYSTEMVALUES_HIVE: () => DBSYSTEMVALUES_HIVE, + DBSYSTEMVALUES_HSQLDB: () => DBSYSTEMVALUES_HSQLDB, + DBSYSTEMVALUES_INFORMIX: () => DBSYSTEMVALUES_INFORMIX, + DBSYSTEMVALUES_INGRES: () => DBSYSTEMVALUES_INGRES, + DBSYSTEMVALUES_INSTANTDB: () => DBSYSTEMVALUES_INSTANTDB, + DBSYSTEMVALUES_INTERBASE: () => DBSYSTEMVALUES_INTERBASE, + DBSYSTEMVALUES_MARIADB: () => DBSYSTEMVALUES_MARIADB, + DBSYSTEMVALUES_MAXDB: () => DBSYSTEMVALUES_MAXDB, + DBSYSTEMVALUES_MEMCACHED: () => DBSYSTEMVALUES_MEMCACHED, + DBSYSTEMVALUES_MONGODB: () => DBSYSTEMVALUES_MONGODB, + DBSYSTEMVALUES_MSSQL: () => DBSYSTEMVALUES_MSSQL, + DBSYSTEMVALUES_MYSQL: () => DBSYSTEMVALUES_MYSQL, + DBSYSTEMVALUES_NEO4J: () => DBSYSTEMVALUES_NEO4J, + DBSYSTEMVALUES_NETEZZA: () => DBSYSTEMVALUES_NETEZZA, + DBSYSTEMVALUES_ORACLE: () => DBSYSTEMVALUES_ORACLE, + DBSYSTEMVALUES_OTHER_SQL: () => DBSYSTEMVALUES_OTHER_SQL, + DBSYSTEMVALUES_PERVASIVE: () => DBSYSTEMVALUES_PERVASIVE, + DBSYSTEMVALUES_POINTBASE: () => DBSYSTEMVALUES_POINTBASE, + DBSYSTEMVALUES_POSTGRESQL: () => DBSYSTEMVALUES_POSTGRESQL, + DBSYSTEMVALUES_PROGRESS: () => DBSYSTEMVALUES_PROGRESS, + DBSYSTEMVALUES_REDIS: () => DBSYSTEMVALUES_REDIS, + DBSYSTEMVALUES_REDSHIFT: () => DBSYSTEMVALUES_REDSHIFT, + DBSYSTEMVALUES_SQLITE: () => DBSYSTEMVALUES_SQLITE, + DBSYSTEMVALUES_SYBASE: () => DBSYSTEMVALUES_SYBASE, + DBSYSTEMVALUES_TERADATA: () => DBSYSTEMVALUES_TERADATA, + DBSYSTEMVALUES_VERTICA: () => DBSYSTEMVALUES_VERTICA, + DB_SYSTEM_NAME_VALUE_MARIADB: () => DB_SYSTEM_NAME_VALUE_MARIADB, + DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER: () => DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER, + DB_SYSTEM_NAME_VALUE_MYSQL: () => DB_SYSTEM_NAME_VALUE_MYSQL, + DB_SYSTEM_NAME_VALUE_POSTGRESQL: () => DB_SYSTEM_NAME_VALUE_POSTGRESQL, + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT: () => DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT, + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION: () => DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION, + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING: () => DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING, + DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST: () => DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST, + DOTNET_GC_HEAP_GENERATION_VALUE_GEN0: () => DOTNET_GC_HEAP_GENERATION_VALUE_GEN0, + DOTNET_GC_HEAP_GENERATION_VALUE_GEN1: () => DOTNET_GC_HEAP_GENERATION_VALUE_GEN1, + DOTNET_GC_HEAP_GENERATION_VALUE_GEN2: () => DOTNET_GC_HEAP_GENERATION_VALUE_GEN2, + DOTNET_GC_HEAP_GENERATION_VALUE_LOH: () => "loh", + DOTNET_GC_HEAP_GENERATION_VALUE_POH: () => "poh", + DbCassandraConsistencyLevelValues: () => DbCassandraConsistencyLevelValues, + DbSystemValues: () => DbSystemValues, + ERROR_TYPE_VALUE_OTHER: () => ERROR_TYPE_VALUE_OTHER, + EVENT_EXCEPTION: () => EVENT_EXCEPTION, + FAASDOCUMENTOPERATIONVALUES_DELETE: () => FAASDOCUMENTOPERATIONVALUES_DELETE, + FAASDOCUMENTOPERATIONVALUES_EDIT: () => FAASDOCUMENTOPERATIONVALUES_EDIT, + FAASDOCUMENTOPERATIONVALUES_INSERT: () => FAASDOCUMENTOPERATIONVALUES_INSERT, + FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD: () => FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, + FAASINVOKEDPROVIDERVALUES_AWS: () => "aws", + FAASINVOKEDPROVIDERVALUES_AZURE: () => FAASINVOKEDPROVIDERVALUES_AZURE, + FAASINVOKEDPROVIDERVALUES_GCP: () => "gcp", + FAASTRIGGERVALUES_DATASOURCE: () => FAASTRIGGERVALUES_DATASOURCE, + FAASTRIGGERVALUES_HTTP: () => FAASTRIGGERVALUES_HTTP, + FAASTRIGGERVALUES_OTHER: () => FAASTRIGGERVALUES_OTHER, + FAASTRIGGERVALUES_PUBSUB: () => FAASTRIGGERVALUES_PUBSUB, + FAASTRIGGERVALUES_TIMER: () => FAASTRIGGERVALUES_TIMER, + FaasDocumentOperationValues: () => FaasDocumentOperationValues, + FaasInvokedProviderValues: () => FaasInvokedProviderValues, + FaasTriggerValues: () => FaasTriggerValues, + HOSTARCHVALUES_AMD64: () => HOSTARCHVALUES_AMD64, + HOSTARCHVALUES_ARM32: () => HOSTARCHVALUES_ARM32, + HOSTARCHVALUES_ARM64: () => HOSTARCHVALUES_ARM64, + HOSTARCHVALUES_IA64: () => HOSTARCHVALUES_IA64, + HOSTARCHVALUES_PPC32: () => HOSTARCHVALUES_PPC32, + HOSTARCHVALUES_PPC64: () => HOSTARCHVALUES_PPC64, + HOSTARCHVALUES_X86: () => "x86", + HTTPFLAVORVALUES_HTTP_1_0: () => "1.0", + HTTPFLAVORVALUES_HTTP_1_1: () => "1.1", + HTTPFLAVORVALUES_HTTP_2_0: () => "2.0", + HTTPFLAVORVALUES_QUIC: () => HTTPFLAVORVALUES_QUIC, + HTTPFLAVORVALUES_SPDY: () => HTTPFLAVORVALUES_SPDY, + HTTP_REQUEST_METHOD_VALUE_CONNECT: () => HTTP_REQUEST_METHOD_VALUE_CONNECT, + HTTP_REQUEST_METHOD_VALUE_DELETE: () => HTTP_REQUEST_METHOD_VALUE_DELETE, + HTTP_REQUEST_METHOD_VALUE_GET: () => "GET", + HTTP_REQUEST_METHOD_VALUE_HEAD: () => HTTP_REQUEST_METHOD_VALUE_HEAD, + HTTP_REQUEST_METHOD_VALUE_OPTIONS: () => HTTP_REQUEST_METHOD_VALUE_OPTIONS, + HTTP_REQUEST_METHOD_VALUE_OTHER: () => HTTP_REQUEST_METHOD_VALUE_OTHER, + HTTP_REQUEST_METHOD_VALUE_PATCH: () => HTTP_REQUEST_METHOD_VALUE_PATCH, + HTTP_REQUEST_METHOD_VALUE_POST: () => HTTP_REQUEST_METHOD_VALUE_POST, + HTTP_REQUEST_METHOD_VALUE_PUT: () => "PUT", + HTTP_REQUEST_METHOD_VALUE_TRACE: () => HTTP_REQUEST_METHOD_VALUE_TRACE, + HostArchValues: () => HostArchValues, + HttpFlavorValues: () => HttpFlavorValues, + JVM_MEMORY_TYPE_VALUE_HEAP: () => JVM_MEMORY_TYPE_VALUE_HEAP, + JVM_MEMORY_TYPE_VALUE_NON_HEAP: () => JVM_MEMORY_TYPE_VALUE_NON_HEAP, + JVM_THREAD_STATE_VALUE_BLOCKED: () => JVM_THREAD_STATE_VALUE_BLOCKED, + JVM_THREAD_STATE_VALUE_NEW: () => "new", + JVM_THREAD_STATE_VALUE_RUNNABLE: () => JVM_THREAD_STATE_VALUE_RUNNABLE, + JVM_THREAD_STATE_VALUE_TERMINATED: () => JVM_THREAD_STATE_VALUE_TERMINATED, + JVM_THREAD_STATE_VALUE_TIMED_WAITING: () => JVM_THREAD_STATE_VALUE_TIMED_WAITING, + JVM_THREAD_STATE_VALUE_WAITING: () => JVM_THREAD_STATE_VALUE_WAITING, + MESSAGETYPEVALUES_RECEIVED: () => MESSAGETYPEVALUES_RECEIVED, + MESSAGETYPEVALUES_SENT: () => MESSAGETYPEVALUES_SENT, + MESSAGINGDESTINATIONKINDVALUES_QUEUE: () => MESSAGINGDESTINATIONKINDVALUES_QUEUE, + MESSAGINGDESTINATIONKINDVALUES_TOPIC: () => MESSAGINGDESTINATIONKINDVALUES_TOPIC, + MESSAGINGOPERATIONVALUES_PROCESS: () => MESSAGINGOPERATIONVALUES_PROCESS, + MESSAGINGOPERATIONVALUES_RECEIVE: () => MESSAGINGOPERATIONVALUES_RECEIVE, + METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS: () => METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS, + METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES: () => METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES, + METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS: () => METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS, + METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS: () => METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS, + METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION: () => METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION, + METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE: () => METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE, + METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS: () => METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS, + METRIC_DB_CLIENT_OPERATION_DURATION: () => METRIC_DB_CLIENT_OPERATION_DURATION, + METRIC_DOTNET_ASSEMBLY_COUNT: () => METRIC_DOTNET_ASSEMBLY_COUNT, + METRIC_DOTNET_EXCEPTIONS: () => METRIC_DOTNET_EXCEPTIONS, + METRIC_DOTNET_GC_COLLECTIONS: () => METRIC_DOTNET_GC_COLLECTIONS, + METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED: () => METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED, + METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE: () => METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE, + METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE: () => METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE, + METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE: () => METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE, + METRIC_DOTNET_GC_PAUSE_TIME: () => METRIC_DOTNET_GC_PAUSE_TIME, + METRIC_DOTNET_JIT_COMPILATION_TIME: () => METRIC_DOTNET_JIT_COMPILATION_TIME, + METRIC_DOTNET_JIT_COMPILED_IL_SIZE: () => METRIC_DOTNET_JIT_COMPILED_IL_SIZE, + METRIC_DOTNET_JIT_COMPILED_METHODS: () => METRIC_DOTNET_JIT_COMPILED_METHODS, + METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS: () => METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS, + METRIC_DOTNET_PROCESS_CPU_COUNT: () => METRIC_DOTNET_PROCESS_CPU_COUNT, + METRIC_DOTNET_PROCESS_CPU_TIME: () => METRIC_DOTNET_PROCESS_CPU_TIME, + METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET: () => METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET, + METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH: () => METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH, + METRIC_DOTNET_THREAD_POOL_THREAD_COUNT: () => METRIC_DOTNET_THREAD_POOL_THREAD_COUNT, + METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT: () => METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT, + METRIC_DOTNET_TIMER_COUNT: () => METRIC_DOTNET_TIMER_COUNT, + METRIC_HTTP_CLIENT_REQUEST_DURATION: () => METRIC_HTTP_CLIENT_REQUEST_DURATION, + METRIC_HTTP_SERVER_REQUEST_DURATION: () => METRIC_HTTP_SERVER_REQUEST_DURATION, + METRIC_JVM_CLASS_COUNT: () => METRIC_JVM_CLASS_COUNT, + METRIC_JVM_CLASS_LOADED: () => METRIC_JVM_CLASS_LOADED, + METRIC_JVM_CLASS_UNLOADED: () => METRIC_JVM_CLASS_UNLOADED, + METRIC_JVM_CPU_COUNT: () => METRIC_JVM_CPU_COUNT, + METRIC_JVM_CPU_RECENT_UTILIZATION: () => METRIC_JVM_CPU_RECENT_UTILIZATION, + METRIC_JVM_CPU_TIME: () => METRIC_JVM_CPU_TIME, + METRIC_JVM_GC_DURATION: () => METRIC_JVM_GC_DURATION, + METRIC_JVM_MEMORY_COMMITTED: () => METRIC_JVM_MEMORY_COMMITTED, + METRIC_JVM_MEMORY_LIMIT: () => METRIC_JVM_MEMORY_LIMIT, + METRIC_JVM_MEMORY_USED: () => METRIC_JVM_MEMORY_USED, + METRIC_JVM_MEMORY_USED_AFTER_LAST_GC: () => METRIC_JVM_MEMORY_USED_AFTER_LAST_GC, + METRIC_JVM_THREAD_COUNT: () => METRIC_JVM_THREAD_COUNT, + METRIC_KESTREL_ACTIVE_CONNECTIONS: () => METRIC_KESTREL_ACTIVE_CONNECTIONS, + METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES: () => METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES, + METRIC_KESTREL_CONNECTION_DURATION: () => METRIC_KESTREL_CONNECTION_DURATION, + METRIC_KESTREL_QUEUED_CONNECTIONS: () => METRIC_KESTREL_QUEUED_CONNECTIONS, + METRIC_KESTREL_QUEUED_REQUESTS: () => METRIC_KESTREL_QUEUED_REQUESTS, + METRIC_KESTREL_REJECTED_CONNECTIONS: () => METRIC_KESTREL_REJECTED_CONNECTIONS, + METRIC_KESTREL_TLS_HANDSHAKE_DURATION: () => METRIC_KESTREL_TLS_HANDSHAKE_DURATION, + METRIC_KESTREL_UPGRADED_CONNECTIONS: () => METRIC_KESTREL_UPGRADED_CONNECTIONS, + METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS: () => METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS, + METRIC_SIGNALR_SERVER_CONNECTION_DURATION: () => METRIC_SIGNALR_SERVER_CONNECTION_DURATION, + MessageTypeValues: () => MessageTypeValues, + MessagingDestinationKindValues: () => MessagingDestinationKindValues, + MessagingOperationValues: () => MessagingOperationValues, + NETHOSTCONNECTIONSUBTYPEVALUES_CDMA: () => NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, + NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT: () => NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, + NETHOSTCONNECTIONSUBTYPEVALUES_EDGE: () => NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, + NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD: () => NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, + NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0: () => NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, + NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A: () => NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, + NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B: () => NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, + NETHOSTCONNECTIONSUBTYPEVALUES_GPRS: () => NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, + NETHOSTCONNECTIONSUBTYPEVALUES_GSM: () => "gsm", + NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, + NETHOSTCONNECTIONSUBTYPEVALUES_HSPA: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, + NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, + NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA: () => NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, + NETHOSTCONNECTIONSUBTYPEVALUES_IDEN: () => NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, + NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN: () => NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, + NETHOSTCONNECTIONSUBTYPEVALUES_LTE: () => "lte", + NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA: () => NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, + NETHOSTCONNECTIONSUBTYPEVALUES_NR: () => "nr", + NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA: () => NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, + NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA: () => NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, + NETHOSTCONNECTIONSUBTYPEVALUES_UMTS: () => NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, + NETHOSTCONNECTIONTYPEVALUES_CELL: () => NETHOSTCONNECTIONTYPEVALUES_CELL, + NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE: () => NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, + NETHOSTCONNECTIONTYPEVALUES_UNKNOWN: () => NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, + NETHOSTCONNECTIONTYPEVALUES_WIFI: () => NETHOSTCONNECTIONTYPEVALUES_WIFI, + NETHOSTCONNECTIONTYPEVALUES_WIRED: () => NETHOSTCONNECTIONTYPEVALUES_WIRED, + NETTRANSPORTVALUES_INPROC: () => NETTRANSPORTVALUES_INPROC, + NETTRANSPORTVALUES_IP: () => "ip", + NETTRANSPORTVALUES_IP_TCP: () => NETTRANSPORTVALUES_IP_TCP, + NETTRANSPORTVALUES_IP_UDP: () => NETTRANSPORTVALUES_IP_UDP, + NETTRANSPORTVALUES_OTHER: () => NETTRANSPORTVALUES_OTHER, + NETTRANSPORTVALUES_PIPE: () => NETTRANSPORTVALUES_PIPE, + NETTRANSPORTVALUES_UNIX: () => NETTRANSPORTVALUES_UNIX, + NETWORK_TRANSPORT_VALUE_PIPE: () => NETWORK_TRANSPORT_VALUE_PIPE, + NETWORK_TRANSPORT_VALUE_QUIC: () => NETWORK_TRANSPORT_VALUE_QUIC, + NETWORK_TRANSPORT_VALUE_TCP: () => "tcp", + NETWORK_TRANSPORT_VALUE_UDP: () => "udp", + NETWORK_TRANSPORT_VALUE_UNIX: () => NETWORK_TRANSPORT_VALUE_UNIX, + NETWORK_TYPE_VALUE_IPV4: () => NETWORK_TYPE_VALUE_IPV4, + NETWORK_TYPE_VALUE_IPV6: () => NETWORK_TYPE_VALUE_IPV6, + NetHostConnectionSubtypeValues: () => NetHostConnectionSubtypeValues, + NetHostConnectionTypeValues: () => NetHostConnectionTypeValues, + NetTransportValues: () => NetTransportValues, + OSTYPEVALUES_AIX: () => "aix", + OSTYPEVALUES_DARWIN: () => OSTYPEVALUES_DARWIN, + OSTYPEVALUES_DRAGONFLYBSD: () => OSTYPEVALUES_DRAGONFLYBSD, + OSTYPEVALUES_FREEBSD: () => OSTYPEVALUES_FREEBSD, + OSTYPEVALUES_HPUX: () => OSTYPEVALUES_HPUX, + OSTYPEVALUES_LINUX: () => OSTYPEVALUES_LINUX, + OSTYPEVALUES_NETBSD: () => OSTYPEVALUES_NETBSD, + OSTYPEVALUES_OPENBSD: () => OSTYPEVALUES_OPENBSD, + OSTYPEVALUES_SOLARIS: () => OSTYPEVALUES_SOLARIS, + OSTYPEVALUES_WINDOWS: () => OSTYPEVALUES_WINDOWS, + OSTYPEVALUES_Z_OS: () => OSTYPEVALUES_Z_OS, + OTEL_STATUS_CODE_VALUE_ERROR: () => OTEL_STATUS_CODE_VALUE_ERROR, + OTEL_STATUS_CODE_VALUE_OK: () => "OK", + OsTypeValues: () => OsTypeValues, + RPCGRPCSTATUSCODEVALUES_ABORTED: () => 10, + RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS: () => 6, + RPCGRPCSTATUSCODEVALUES_CANCELLED: () => 1, + RPCGRPCSTATUSCODEVALUES_DATA_LOSS: () => 15, + RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED: () => 4, + RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION: () => 9, + RPCGRPCSTATUSCODEVALUES_INTERNAL: () => 13, + RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT: () => 3, + RPCGRPCSTATUSCODEVALUES_NOT_FOUND: () => 5, + RPCGRPCSTATUSCODEVALUES_OK: () => 0, + RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE: () => 11, + RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED: () => 7, + RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED: () => 8, + RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED: () => 16, + RPCGRPCSTATUSCODEVALUES_UNAVAILABLE: () => 14, + RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED: () => 12, + RPCGRPCSTATUSCODEVALUES_UNKNOWN: () => 2, + RpcGrpcStatusCodeValues: () => RpcGrpcStatusCodeValues, + SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET: () => SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET, + SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS: () => SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, + SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ: () => SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ, + SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY: () => SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY, + SEMATTRS_AWS_DYNAMODB_COUNT: () => SEMATTRS_AWS_DYNAMODB_COUNT, + SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE: () => SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, + SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES: () => SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, + SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES: () => SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, + SEMATTRS_AWS_DYNAMODB_INDEX_NAME: () => SEMATTRS_AWS_DYNAMODB_INDEX_NAME, + SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS: () => SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, + SEMATTRS_AWS_DYNAMODB_LIMIT: () => SEMATTRS_AWS_DYNAMODB_LIMIT, + SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES: () => SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, + SEMATTRS_AWS_DYNAMODB_PROJECTION: () => SEMATTRS_AWS_DYNAMODB_PROJECTION, + SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY: () => SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, + SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY: () => SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, + SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT: () => SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT, + SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD: () => SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD, + SEMATTRS_AWS_DYNAMODB_SEGMENT: () => SEMATTRS_AWS_DYNAMODB_SEGMENT, + SEMATTRS_AWS_DYNAMODB_SELECT: () => SEMATTRS_AWS_DYNAMODB_SELECT, + SEMATTRS_AWS_DYNAMODB_TABLE_COUNT: () => SEMATTRS_AWS_DYNAMODB_TABLE_COUNT, + SEMATTRS_AWS_DYNAMODB_TABLE_NAMES: () => SEMATTRS_AWS_DYNAMODB_TABLE_NAMES, + SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS: () => SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS, + SEMATTRS_AWS_LAMBDA_INVOKED_ARN: () => SEMATTRS_AWS_LAMBDA_INVOKED_ARN, + SEMATTRS_CODE_FILEPATH: () => SEMATTRS_CODE_FILEPATH, + SEMATTRS_CODE_FUNCTION: () => SEMATTRS_CODE_FUNCTION, + SEMATTRS_CODE_LINENO: () => SEMATTRS_CODE_LINENO, + SEMATTRS_CODE_NAMESPACE: () => SEMATTRS_CODE_NAMESPACE, + SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL: () => SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL, + SEMATTRS_DB_CASSANDRA_COORDINATOR_DC: () => SEMATTRS_DB_CASSANDRA_COORDINATOR_DC, + SEMATTRS_DB_CASSANDRA_COORDINATOR_ID: () => SEMATTRS_DB_CASSANDRA_COORDINATOR_ID, + SEMATTRS_DB_CASSANDRA_IDEMPOTENCE: () => SEMATTRS_DB_CASSANDRA_IDEMPOTENCE, + SEMATTRS_DB_CASSANDRA_KEYSPACE: () => SEMATTRS_DB_CASSANDRA_KEYSPACE, + SEMATTRS_DB_CASSANDRA_PAGE_SIZE: () => SEMATTRS_DB_CASSANDRA_PAGE_SIZE, + SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT: () => SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, + SEMATTRS_DB_CASSANDRA_TABLE: () => SEMATTRS_DB_CASSANDRA_TABLE, + SEMATTRS_DB_CONNECTION_STRING: () => SEMATTRS_DB_CONNECTION_STRING, + SEMATTRS_DB_HBASE_NAMESPACE: () => SEMATTRS_DB_HBASE_NAMESPACE, + SEMATTRS_DB_JDBC_DRIVER_CLASSNAME: () => SEMATTRS_DB_JDBC_DRIVER_CLASSNAME, + SEMATTRS_DB_MONGODB_COLLECTION: () => SEMATTRS_DB_MONGODB_COLLECTION, + SEMATTRS_DB_MSSQL_INSTANCE_NAME: () => SEMATTRS_DB_MSSQL_INSTANCE_NAME, + SEMATTRS_DB_NAME: () => SEMATTRS_DB_NAME, + SEMATTRS_DB_OPERATION: () => SEMATTRS_DB_OPERATION, + SEMATTRS_DB_REDIS_DATABASE_INDEX: () => SEMATTRS_DB_REDIS_DATABASE_INDEX, + SEMATTRS_DB_SQL_TABLE: () => SEMATTRS_DB_SQL_TABLE, + SEMATTRS_DB_STATEMENT: () => SEMATTRS_DB_STATEMENT, + SEMATTRS_DB_SYSTEM: () => SEMATTRS_DB_SYSTEM, + SEMATTRS_DB_USER: () => SEMATTRS_DB_USER, + SEMATTRS_ENDUSER_ID: () => SEMATTRS_ENDUSER_ID, + SEMATTRS_ENDUSER_ROLE: () => SEMATTRS_ENDUSER_ROLE, + SEMATTRS_ENDUSER_SCOPE: () => SEMATTRS_ENDUSER_SCOPE, + SEMATTRS_EXCEPTION_ESCAPED: () => SEMATTRS_EXCEPTION_ESCAPED, + SEMATTRS_EXCEPTION_MESSAGE: () => SEMATTRS_EXCEPTION_MESSAGE, + SEMATTRS_EXCEPTION_STACKTRACE: () => SEMATTRS_EXCEPTION_STACKTRACE, + SEMATTRS_EXCEPTION_TYPE: () => SEMATTRS_EXCEPTION_TYPE, + SEMATTRS_FAAS_COLDSTART: () => SEMATTRS_FAAS_COLDSTART, + SEMATTRS_FAAS_CRON: () => SEMATTRS_FAAS_CRON, + SEMATTRS_FAAS_DOCUMENT_COLLECTION: () => SEMATTRS_FAAS_DOCUMENT_COLLECTION, + SEMATTRS_FAAS_DOCUMENT_NAME: () => SEMATTRS_FAAS_DOCUMENT_NAME, + SEMATTRS_FAAS_DOCUMENT_OPERATION: () => SEMATTRS_FAAS_DOCUMENT_OPERATION, + SEMATTRS_FAAS_DOCUMENT_TIME: () => SEMATTRS_FAAS_DOCUMENT_TIME, + SEMATTRS_FAAS_EXECUTION: () => SEMATTRS_FAAS_EXECUTION, + SEMATTRS_FAAS_INVOKED_NAME: () => SEMATTRS_FAAS_INVOKED_NAME, + SEMATTRS_FAAS_INVOKED_PROVIDER: () => SEMATTRS_FAAS_INVOKED_PROVIDER, + SEMATTRS_FAAS_INVOKED_REGION: () => SEMATTRS_FAAS_INVOKED_REGION, + SEMATTRS_FAAS_TIME: () => SEMATTRS_FAAS_TIME, + SEMATTRS_FAAS_TRIGGER: () => SEMATTRS_FAAS_TRIGGER, + SEMATTRS_HTTP_CLIENT_IP: () => SEMATTRS_HTTP_CLIENT_IP, + SEMATTRS_HTTP_FLAVOR: () => SEMATTRS_HTTP_FLAVOR, + SEMATTRS_HTTP_HOST: () => SEMATTRS_HTTP_HOST, + SEMATTRS_HTTP_METHOD: () => SEMATTRS_HTTP_METHOD, + SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH: () => SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH, + SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED: () => SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, + SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH: () => SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, + SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED: () => SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, + SEMATTRS_HTTP_ROUTE: () => SEMATTRS_HTTP_ROUTE, + SEMATTRS_HTTP_SCHEME: () => SEMATTRS_HTTP_SCHEME, + SEMATTRS_HTTP_SERVER_NAME: () => SEMATTRS_HTTP_SERVER_NAME, + SEMATTRS_HTTP_STATUS_CODE: () => SEMATTRS_HTTP_STATUS_CODE, + SEMATTRS_HTTP_TARGET: () => SEMATTRS_HTTP_TARGET, + SEMATTRS_HTTP_URL: () => SEMATTRS_HTTP_URL, + SEMATTRS_HTTP_USER_AGENT: () => SEMATTRS_HTTP_USER_AGENT, + SEMATTRS_MESSAGE_COMPRESSED_SIZE: () => SEMATTRS_MESSAGE_COMPRESSED_SIZE, + SEMATTRS_MESSAGE_ID: () => SEMATTRS_MESSAGE_ID, + SEMATTRS_MESSAGE_TYPE: () => SEMATTRS_MESSAGE_TYPE, + SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE: () => SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE, + SEMATTRS_MESSAGING_CONSUMER_ID: () => SEMATTRS_MESSAGING_CONSUMER_ID, + SEMATTRS_MESSAGING_CONVERSATION_ID: () => SEMATTRS_MESSAGING_CONVERSATION_ID, + SEMATTRS_MESSAGING_DESTINATION: () => SEMATTRS_MESSAGING_DESTINATION, + SEMATTRS_MESSAGING_DESTINATION_KIND: () => SEMATTRS_MESSAGING_DESTINATION_KIND, + SEMATTRS_MESSAGING_KAFKA_CLIENT_ID: () => SEMATTRS_MESSAGING_KAFKA_CLIENT_ID, + SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP: () => SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP, + SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY: () => SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY, + SEMATTRS_MESSAGING_KAFKA_PARTITION: () => SEMATTRS_MESSAGING_KAFKA_PARTITION, + SEMATTRS_MESSAGING_KAFKA_TOMBSTONE: () => SEMATTRS_MESSAGING_KAFKA_TOMBSTONE, + SEMATTRS_MESSAGING_MESSAGE_ID: () => SEMATTRS_MESSAGING_MESSAGE_ID, + SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES: () => SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, + SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES: () => SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, + SEMATTRS_MESSAGING_OPERATION: () => SEMATTRS_MESSAGING_OPERATION, + SEMATTRS_MESSAGING_PROTOCOL: () => SEMATTRS_MESSAGING_PROTOCOL, + SEMATTRS_MESSAGING_PROTOCOL_VERSION: () => SEMATTRS_MESSAGING_PROTOCOL_VERSION, + SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY: () => SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY, + SEMATTRS_MESSAGING_SYSTEM: () => SEMATTRS_MESSAGING_SYSTEM, + SEMATTRS_MESSAGING_TEMP_DESTINATION: () => SEMATTRS_MESSAGING_TEMP_DESTINATION, + SEMATTRS_MESSAGING_URL: () => SEMATTRS_MESSAGING_URL, + SEMATTRS_NET_HOST_CARRIER_ICC: () => SEMATTRS_NET_HOST_CARRIER_ICC, + SEMATTRS_NET_HOST_CARRIER_MCC: () => SEMATTRS_NET_HOST_CARRIER_MCC, + SEMATTRS_NET_HOST_CARRIER_MNC: () => SEMATTRS_NET_HOST_CARRIER_MNC, + SEMATTRS_NET_HOST_CARRIER_NAME: () => SEMATTRS_NET_HOST_CARRIER_NAME, + SEMATTRS_NET_HOST_CONNECTION_SUBTYPE: () => SEMATTRS_NET_HOST_CONNECTION_SUBTYPE, + SEMATTRS_NET_HOST_CONNECTION_TYPE: () => SEMATTRS_NET_HOST_CONNECTION_TYPE, + SEMATTRS_NET_HOST_IP: () => SEMATTRS_NET_HOST_IP, + SEMATTRS_NET_HOST_NAME: () => SEMATTRS_NET_HOST_NAME, + SEMATTRS_NET_HOST_PORT: () => SEMATTRS_NET_HOST_PORT, + SEMATTRS_NET_PEER_IP: () => SEMATTRS_NET_PEER_IP, + SEMATTRS_NET_PEER_NAME: () => SEMATTRS_NET_PEER_NAME, + SEMATTRS_NET_PEER_PORT: () => SEMATTRS_NET_PEER_PORT, + SEMATTRS_NET_TRANSPORT: () => SEMATTRS_NET_TRANSPORT, + SEMATTRS_PEER_SERVICE: () => SEMATTRS_PEER_SERVICE, + SEMATTRS_RPC_GRPC_STATUS_CODE: () => SEMATTRS_RPC_GRPC_STATUS_CODE, + SEMATTRS_RPC_JSONRPC_ERROR_CODE: () => SEMATTRS_RPC_JSONRPC_ERROR_CODE, + SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE: () => SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE, + SEMATTRS_RPC_JSONRPC_REQUEST_ID: () => SEMATTRS_RPC_JSONRPC_REQUEST_ID, + SEMATTRS_RPC_JSONRPC_VERSION: () => SEMATTRS_RPC_JSONRPC_VERSION, + SEMATTRS_RPC_METHOD: () => SEMATTRS_RPC_METHOD, + SEMATTRS_RPC_SERVICE: () => SEMATTRS_RPC_SERVICE, + SEMATTRS_RPC_SYSTEM: () => SEMATTRS_RPC_SYSTEM, + SEMATTRS_THREAD_ID: () => SEMATTRS_THREAD_ID, + SEMATTRS_THREAD_NAME: () => SEMATTRS_THREAD_NAME, + SEMRESATTRS_AWS_ECS_CLUSTER_ARN: () => SEMRESATTRS_AWS_ECS_CLUSTER_ARN, + SEMRESATTRS_AWS_ECS_CONTAINER_ARN: () => SEMRESATTRS_AWS_ECS_CONTAINER_ARN, + SEMRESATTRS_AWS_ECS_LAUNCHTYPE: () => SEMRESATTRS_AWS_ECS_LAUNCHTYPE, + SEMRESATTRS_AWS_ECS_TASK_ARN: () => SEMRESATTRS_AWS_ECS_TASK_ARN, + SEMRESATTRS_AWS_ECS_TASK_FAMILY: () => SEMRESATTRS_AWS_ECS_TASK_FAMILY, + SEMRESATTRS_AWS_ECS_TASK_REVISION: () => SEMRESATTRS_AWS_ECS_TASK_REVISION, + SEMRESATTRS_AWS_EKS_CLUSTER_ARN: () => SEMRESATTRS_AWS_EKS_CLUSTER_ARN, + SEMRESATTRS_AWS_LOG_GROUP_ARNS: () => SEMRESATTRS_AWS_LOG_GROUP_ARNS, + SEMRESATTRS_AWS_LOG_GROUP_NAMES: () => SEMRESATTRS_AWS_LOG_GROUP_NAMES, + SEMRESATTRS_AWS_LOG_STREAM_ARNS: () => SEMRESATTRS_AWS_LOG_STREAM_ARNS, + SEMRESATTRS_AWS_LOG_STREAM_NAMES: () => SEMRESATTRS_AWS_LOG_STREAM_NAMES, + SEMRESATTRS_CLOUD_ACCOUNT_ID: () => SEMRESATTRS_CLOUD_ACCOUNT_ID, + SEMRESATTRS_CLOUD_AVAILABILITY_ZONE: () => SEMRESATTRS_CLOUD_AVAILABILITY_ZONE, + SEMRESATTRS_CLOUD_PLATFORM: () => SEMRESATTRS_CLOUD_PLATFORM, + SEMRESATTRS_CLOUD_PROVIDER: () => SEMRESATTRS_CLOUD_PROVIDER, + SEMRESATTRS_CLOUD_REGION: () => SEMRESATTRS_CLOUD_REGION, + SEMRESATTRS_CONTAINER_ID: () => SEMRESATTRS_CONTAINER_ID, + SEMRESATTRS_CONTAINER_IMAGE_NAME: () => SEMRESATTRS_CONTAINER_IMAGE_NAME, + SEMRESATTRS_CONTAINER_IMAGE_TAG: () => SEMRESATTRS_CONTAINER_IMAGE_TAG, + SEMRESATTRS_CONTAINER_NAME: () => SEMRESATTRS_CONTAINER_NAME, + SEMRESATTRS_CONTAINER_RUNTIME: () => SEMRESATTRS_CONTAINER_RUNTIME, + SEMRESATTRS_DEPLOYMENT_ENVIRONMENT: () => SEMRESATTRS_DEPLOYMENT_ENVIRONMENT, + SEMRESATTRS_DEVICE_ID: () => SEMRESATTRS_DEVICE_ID, + SEMRESATTRS_DEVICE_MODEL_IDENTIFIER: () => SEMRESATTRS_DEVICE_MODEL_IDENTIFIER, + SEMRESATTRS_DEVICE_MODEL_NAME: () => SEMRESATTRS_DEVICE_MODEL_NAME, + SEMRESATTRS_FAAS_ID: () => SEMRESATTRS_FAAS_ID, + SEMRESATTRS_FAAS_INSTANCE: () => SEMRESATTRS_FAAS_INSTANCE, + SEMRESATTRS_FAAS_MAX_MEMORY: () => SEMRESATTRS_FAAS_MAX_MEMORY, + SEMRESATTRS_FAAS_NAME: () => SEMRESATTRS_FAAS_NAME, + SEMRESATTRS_FAAS_VERSION: () => SEMRESATTRS_FAAS_VERSION, + SEMRESATTRS_HOST_ARCH: () => SEMRESATTRS_HOST_ARCH, + SEMRESATTRS_HOST_ID: () => SEMRESATTRS_HOST_ID, + SEMRESATTRS_HOST_IMAGE_ID: () => SEMRESATTRS_HOST_IMAGE_ID, + SEMRESATTRS_HOST_IMAGE_NAME: () => SEMRESATTRS_HOST_IMAGE_NAME, + SEMRESATTRS_HOST_IMAGE_VERSION: () => SEMRESATTRS_HOST_IMAGE_VERSION, + SEMRESATTRS_HOST_NAME: () => SEMRESATTRS_HOST_NAME, + SEMRESATTRS_HOST_TYPE: () => SEMRESATTRS_HOST_TYPE, + SEMRESATTRS_K8S_CLUSTER_NAME: () => SEMRESATTRS_K8S_CLUSTER_NAME, + SEMRESATTRS_K8S_CONTAINER_NAME: () => SEMRESATTRS_K8S_CONTAINER_NAME, + SEMRESATTRS_K8S_CRONJOB_NAME: () => SEMRESATTRS_K8S_CRONJOB_NAME, + SEMRESATTRS_K8S_CRONJOB_UID: () => SEMRESATTRS_K8S_CRONJOB_UID, + SEMRESATTRS_K8S_DAEMONSET_NAME: () => SEMRESATTRS_K8S_DAEMONSET_NAME, + SEMRESATTRS_K8S_DAEMONSET_UID: () => SEMRESATTRS_K8S_DAEMONSET_UID, + SEMRESATTRS_K8S_DEPLOYMENT_NAME: () => SEMRESATTRS_K8S_DEPLOYMENT_NAME, + SEMRESATTRS_K8S_DEPLOYMENT_UID: () => SEMRESATTRS_K8S_DEPLOYMENT_UID, + SEMRESATTRS_K8S_JOB_NAME: () => SEMRESATTRS_K8S_JOB_NAME, + SEMRESATTRS_K8S_JOB_UID: () => SEMRESATTRS_K8S_JOB_UID, + SEMRESATTRS_K8S_NAMESPACE_NAME: () => SEMRESATTRS_K8S_NAMESPACE_NAME, + SEMRESATTRS_K8S_NODE_NAME: () => SEMRESATTRS_K8S_NODE_NAME, + SEMRESATTRS_K8S_NODE_UID: () => SEMRESATTRS_K8S_NODE_UID, + SEMRESATTRS_K8S_POD_NAME: () => SEMRESATTRS_K8S_POD_NAME, + SEMRESATTRS_K8S_POD_UID: () => SEMRESATTRS_K8S_POD_UID, + SEMRESATTRS_K8S_REPLICASET_NAME: () => SEMRESATTRS_K8S_REPLICASET_NAME, + SEMRESATTRS_K8S_REPLICASET_UID: () => SEMRESATTRS_K8S_REPLICASET_UID, + SEMRESATTRS_K8S_STATEFULSET_NAME: () => SEMRESATTRS_K8S_STATEFULSET_NAME, + SEMRESATTRS_K8S_STATEFULSET_UID: () => SEMRESATTRS_K8S_STATEFULSET_UID, + SEMRESATTRS_OS_DESCRIPTION: () => SEMRESATTRS_OS_DESCRIPTION, + SEMRESATTRS_OS_NAME: () => SEMRESATTRS_OS_NAME, + SEMRESATTRS_OS_TYPE: () => SEMRESATTRS_OS_TYPE, + SEMRESATTRS_OS_VERSION: () => SEMRESATTRS_OS_VERSION, + SEMRESATTRS_PROCESS_COMMAND: () => SEMRESATTRS_PROCESS_COMMAND, + SEMRESATTRS_PROCESS_COMMAND_ARGS: () => SEMRESATTRS_PROCESS_COMMAND_ARGS, + SEMRESATTRS_PROCESS_COMMAND_LINE: () => SEMRESATTRS_PROCESS_COMMAND_LINE, + SEMRESATTRS_PROCESS_EXECUTABLE_NAME: () => SEMRESATTRS_PROCESS_EXECUTABLE_NAME, + SEMRESATTRS_PROCESS_EXECUTABLE_PATH: () => SEMRESATTRS_PROCESS_EXECUTABLE_PATH, + SEMRESATTRS_PROCESS_OWNER: () => SEMRESATTRS_PROCESS_OWNER, + SEMRESATTRS_PROCESS_PID: () => SEMRESATTRS_PROCESS_PID, + SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION: () => SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION, + SEMRESATTRS_PROCESS_RUNTIME_NAME: () => SEMRESATTRS_PROCESS_RUNTIME_NAME, + SEMRESATTRS_PROCESS_RUNTIME_VERSION: () => SEMRESATTRS_PROCESS_RUNTIME_VERSION, + SEMRESATTRS_SERVICE_INSTANCE_ID: () => SEMRESATTRS_SERVICE_INSTANCE_ID, + SEMRESATTRS_SERVICE_NAME: () => SEMRESATTRS_SERVICE_NAME, + SEMRESATTRS_SERVICE_NAMESPACE: () => SEMRESATTRS_SERVICE_NAMESPACE, + SEMRESATTRS_SERVICE_VERSION: () => SEMRESATTRS_SERVICE_VERSION, + SEMRESATTRS_TELEMETRY_AUTO_VERSION: () => SEMRESATTRS_TELEMETRY_AUTO_VERSION, + SEMRESATTRS_TELEMETRY_SDK_LANGUAGE: () => SEMRESATTRS_TELEMETRY_SDK_LANGUAGE, + SEMRESATTRS_TELEMETRY_SDK_NAME: () => SEMRESATTRS_TELEMETRY_SDK_NAME, + SEMRESATTRS_TELEMETRY_SDK_VERSION: () => SEMRESATTRS_TELEMETRY_SDK_VERSION, + SEMRESATTRS_WEBENGINE_DESCRIPTION: () => SEMRESATTRS_WEBENGINE_DESCRIPTION, + SEMRESATTRS_WEBENGINE_NAME: () => SEMRESATTRS_WEBENGINE_NAME, + SEMRESATTRS_WEBENGINE_VERSION: () => SEMRESATTRS_WEBENGINE_VERSION, + SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN: () => SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN, + SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE: () => SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE, + SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT: () => SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT, + SIGNALR_TRANSPORT_VALUE_LONG_POLLING: () => SIGNALR_TRANSPORT_VALUE_LONG_POLLING, + SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS: () => SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS, + SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS: () => SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS, + SemanticAttributes: () => SemanticAttributes, + SemanticResourceAttributes: () => SemanticResourceAttributes, + TELEMETRYSDKLANGUAGEVALUES_CPP: () => "cpp", + TELEMETRYSDKLANGUAGEVALUES_DOTNET: () => TELEMETRYSDKLANGUAGEVALUES_DOTNET, + TELEMETRYSDKLANGUAGEVALUES_ERLANG: () => TELEMETRYSDKLANGUAGEVALUES_ERLANG, + TELEMETRYSDKLANGUAGEVALUES_GO: () => "go", + TELEMETRYSDKLANGUAGEVALUES_JAVA: () => TELEMETRYSDKLANGUAGEVALUES_JAVA, + TELEMETRYSDKLANGUAGEVALUES_NODEJS: () => TELEMETRYSDKLANGUAGEVALUES_NODEJS, + TELEMETRYSDKLANGUAGEVALUES_PHP: () => "php", + TELEMETRYSDKLANGUAGEVALUES_PYTHON: () => TELEMETRYSDKLANGUAGEVALUES_PYTHON, + TELEMETRYSDKLANGUAGEVALUES_RUBY: () => TELEMETRYSDKLANGUAGEVALUES_RUBY, + TELEMETRYSDKLANGUAGEVALUES_WEBJS: () => TELEMETRYSDKLANGUAGEVALUES_WEBJS, + TELEMETRY_SDK_LANGUAGE_VALUE_CPP: () => "cpp", + TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET: () => TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET, + TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG: () => TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG, + TELEMETRY_SDK_LANGUAGE_VALUE_GO: () => "go", + TELEMETRY_SDK_LANGUAGE_VALUE_JAVA: () => TELEMETRY_SDK_LANGUAGE_VALUE_JAVA, + TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN: () => TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN, + TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS: () => TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, + TELEMETRY_SDK_LANGUAGE_VALUE_PHP: () => "php", + TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON: () => TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON, + TELEMETRY_SDK_LANGUAGE_VALUE_RUBY: () => TELEMETRY_SDK_LANGUAGE_VALUE_RUBY, + TELEMETRY_SDK_LANGUAGE_VALUE_RUST: () => TELEMETRY_SDK_LANGUAGE_VALUE_RUST, + TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT: () => TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT, + TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS: () => TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS, + TelemetrySdkLanguageValues: () => TelemetrySdkLanguageValues +}); +var init_esm$1 = __esmMin((() => { + init_trace(); + init_resource(); + init_stable_attributes(); + init_stable_metrics(); + init_stable_events(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/semconv.js +var require_semconv$4 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_PROCESS_RUNTIME_NAME = void 0; + /** + * The name of the runtime of this process. + * + * @example OpenJDK Runtime Environment + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js +var require_sdk_info = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDK_INFO = void 0; + const version_1 = require_version$2(); + const semantic_conventions_1 = (init_esm$1(), __toCommonJS(esm_exports$1)); + const semconv_1 = require_semconv$4(); + /** Constants describing the SDK in use */ + exports.SDK_INFO = { + [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: "opentelemetry", + [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "node", + [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: semantic_conventions_1.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, + [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: version_1.VERSION + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/platform/node/index.js +var require_node$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.otperformance = exports.SDK_INFO = exports._globalThis = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = void 0; + var environment_1 = require_environment(); + Object.defineProperty(exports, "getStringFromEnv", { + enumerable: true, + get: function() { + return environment_1.getStringFromEnv; + } + }); + Object.defineProperty(exports, "getBooleanFromEnv", { + enumerable: true, + get: function() { + return environment_1.getBooleanFromEnv; + } + }); + Object.defineProperty(exports, "getNumberFromEnv", { + enumerable: true, + get: function() { + return environment_1.getNumberFromEnv; + } + }); + Object.defineProperty(exports, "getStringListFromEnv", { + enumerable: true, + get: function() { + return environment_1.getStringListFromEnv; + } + }); + var globalThis_1 = require_globalThis(); + Object.defineProperty(exports, "_globalThis", { + enumerable: true, + get: function() { + return globalThis_1._globalThis; + } + }); + var sdk_info_1 = require_sdk_info(); + Object.defineProperty(exports, "SDK_INFO", { + enumerable: true, + get: function() { + return sdk_info_1.SDK_INFO; + } + }); + /** + * @deprecated Use performance directly. + */ + exports.otperformance = performance; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/platform/index.js +var require_platform$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getStringFromEnv = exports.getBooleanFromEnv = exports.otperformance = exports._globalThis = exports.SDK_INFO = void 0; + var node_1 = require_node$3(); + Object.defineProperty(exports, "SDK_INFO", { + enumerable: true, + get: function() { + return node_1.SDK_INFO; + } + }); + Object.defineProperty(exports, "_globalThis", { + enumerable: true, + get: function() { + return node_1._globalThis; + } + }); + Object.defineProperty(exports, "otperformance", { + enumerable: true, + get: function() { + return node_1.otperformance; + } + }); + Object.defineProperty(exports, "getBooleanFromEnv", { + enumerable: true, + get: function() { + return node_1.getBooleanFromEnv; + } + }); + Object.defineProperty(exports, "getStringFromEnv", { + enumerable: true, + get: function() { + return node_1.getStringFromEnv; + } + }); + Object.defineProperty(exports, "getNumberFromEnv", { + enumerable: true, + get: function() { + return node_1.getNumberFromEnv; + } + }); + Object.defineProperty(exports, "getStringListFromEnv", { + enumerable: true, + get: function() { + return node_1.getStringListFromEnv; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/common/time.js +var require_time = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.addHrTimes = exports.isTimeInput = exports.isTimeInputHrTime = exports.hrTimeToSeconds = exports.hrTimeToMilliseconds = exports.hrTimeToMicroseconds = exports.hrTimeToNanoseconds = exports.hrTimeToTimeStamp = exports.hrTimeDuration = exports.timeInputToHrTime = exports.hrTime = exports.getTimeOrigin = exports.millisToHrTime = void 0; + const platform_1 = require_platform$3(); + const NANOSECOND_DIGITS = 9; + const MILLISECONDS_TO_NANOSECONDS = Math.pow(10, 6); + const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); + /** + * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]). + * @param epochMillis + */ + function millisToHrTime(epochMillis) { + const epochSeconds = epochMillis / 1e3; + return [Math.trunc(epochSeconds), Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS)]; + } + exports.millisToHrTime = millisToHrTime; + /** + * @deprecated Use `performance.timeOrigin` directly. + */ + function getTimeOrigin() { + return platform_1.otperformance.timeOrigin; + } + exports.getTimeOrigin = getTimeOrigin; + /** + * Returns an hrtime calculated via performance component. + * @param performanceNow + */ + function hrTime(performanceNow) { + return addHrTimes(millisToHrTime(platform_1.otperformance.timeOrigin), millisToHrTime(typeof performanceNow === "number" ? performanceNow : platform_1.otperformance.now())); + } + exports.hrTime = hrTime; + /** + * + * Converts a TimeInput to an HrTime, defaults to _hrtime(). + * @param time + */ + function timeInputToHrTime(time) { + if (isTimeInputHrTime(time)) return time; + else if (typeof time === "number") { + if (time < platform_1.otperformance.timeOrigin / 2) return hrTime(time); + else return millisToHrTime(time); + } else if (time instanceof Date) return millisToHrTime(time.getTime()); + else throw TypeError("Invalid input type"); + } + exports.timeInputToHrTime = timeInputToHrTime; + /** + * Returns a duration of two hrTime. + * @param startTime + * @param endTime + */ + function hrTimeDuration(startTime, endTime) { + let seconds = endTime[0] - startTime[0]; + let nanos = endTime[1] - startTime[1]; + if (nanos < 0) { + seconds -= 1; + nanos += SECOND_TO_NANOSECONDS; + } + return [seconds, nanos]; + } + exports.hrTimeDuration = hrTimeDuration; + /** + * Convert hrTime to timestamp, for example "2019-05-14T17:00:00.000123456Z" + * @param time + */ + function hrTimeToTimeStamp(time) { + const precision = NANOSECOND_DIGITS; + const tmp = `${"0".repeat(precision)}${time[1]}Z`; + const nanoString = tmp.substring(tmp.length - precision - 1); + return (/* @__PURE__ */ new Date(time[0] * 1e3)).toISOString().replace("000Z", nanoString); + } + exports.hrTimeToTimeStamp = hrTimeToTimeStamp; + /** + * Convert hrTime to nanoseconds. + * @param time + */ + function hrTimeToNanoseconds(time) { + return time[0] * SECOND_TO_NANOSECONDS + time[1]; + } + exports.hrTimeToNanoseconds = hrTimeToNanoseconds; + /** + * Convert hrTime to microseconds. + * @param time + */ + function hrTimeToMicroseconds(time) { + return time[0] * 1e6 + time[1] / 1e3; + } + exports.hrTimeToMicroseconds = hrTimeToMicroseconds; + /** + * Convert hrTime to milliseconds. + * @param time + */ + function hrTimeToMilliseconds(time) { + return time[0] * 1e3 + time[1] / 1e6; + } + exports.hrTimeToMilliseconds = hrTimeToMilliseconds; + /** + * Convert hrTime to seconds. + * @param time + */ + function hrTimeToSeconds(time) { + return time[0] + time[1] / SECOND_TO_NANOSECONDS; + } + exports.hrTimeToSeconds = hrTimeToSeconds; + /** + * check if time is HrTime + * @param value + */ + function isTimeInputHrTime(value) { + return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number"; + } + exports.isTimeInputHrTime = isTimeInputHrTime; + /** + * check if input value is a correct types.TimeInput + * @param value + */ + function isTimeInput(value) { + return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date; + } + exports.isTimeInput = isTimeInput; + /** + * Given 2 HrTime formatted times, return their sum as an HrTime. + */ + function addHrTimes(time1, time2) { + const out = [time1[0] + time2[0], time1[1] + time2[1]]; + if (out[1] >= SECOND_TO_NANOSECONDS) { + out[1] -= SECOND_TO_NANOSECONDS; + out[0] += 1; + } + return out; + } + exports.addHrTimes = addHrTimes; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/common/timer-util.js +var require_timer_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.unrefTimer = void 0; + /** + * @deprecated please copy this code to your implementation instead, this function will be removed in the next major version of this package. + * @param timer + */ + function unrefTimer(timer) { + if (typeof timer !== "number") timer.unref(); + } + exports.unrefTimer = unrefTimer; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/ExportResult.js +var require_ExportResult = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExportResultCode = void 0; + var ExportResultCode; + (function(ExportResultCode) { + ExportResultCode[ExportResultCode["SUCCESS"] = 0] = "SUCCESS"; + ExportResultCode[ExportResultCode["FAILED"] = 1] = "FAILED"; + })(ExportResultCode || (exports.ExportResultCode = ExportResultCode = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/propagation/composite.js +var require_composite = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompositePropagator = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + /** Combines multiple propagators into a single propagator. */ + var CompositePropagator = class { + _propagators; + _fields; + /** + * Construct a composite propagator from a list of propagators. + * + * @param [config] Configuration object for composite propagator + */ + constructor(config = {}) { + this._propagators = config.propagators ?? []; + const fields = /* @__PURE__ */ new Set(); + for (const propagator of this._propagators) { + const propagatorFields = typeof propagator.fields === "function" ? propagator.fields() : []; + for (const field of propagatorFields) fields.add(field); + } + this._fields = Array.from(fields); + } + /** + * Run each of the configured propagators with the given context and carrier. + * Propagators are run in the order they are configured, so if multiple + * propagators write the same carrier key, the propagator later in the list + * will "win". + * + * @param context Context to inject + * @param carrier Carrier into which context will be injected + */ + inject(context, carrier, setter) { + for (const propagator of this._propagators) try { + propagator.inject(context, carrier, setter); + } catch (err) { + api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`); + } + } + /** + * Run each of the configured propagators with the given context and carrier. + * Propagators are run in the order they are configured, so if multiple + * propagators write the same context key, the propagator later in the list + * will "win". + * + * @param context Context to add values to + * @param carrier Carrier from which to extract context + */ + extract(context, carrier, getter) { + return this._propagators.reduce((ctx, propagator) => { + try { + return propagator.extract(ctx, carrier, getter); + } catch (err) { + api_1.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`); + } + return ctx; + }, context); + } + fields() { + return this._fields.slice(); + } + }; + exports.CompositePropagator = CompositePropagator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/internal/validators.js +var require_validators = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateValue = exports.validateKey = void 0; + const VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]"; + const VALID_KEY_REGEX = new RegExp(`^(?:${`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`}|${`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`})$`); + const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; + const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; + /** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ + function validateKey(key) { + return VALID_KEY_REGEX.test(key); + } + exports.validateKey = validateKey; + /** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ + function validateValue(value) { + return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value); + } + exports.validateValue = validateValue; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/trace/TraceState.js +var require_TraceState = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceState = void 0; + const validators_1 = require_validators(); + const MAX_TRACE_STATE_ITEMS = 32; + const MAX_TRACE_STATE_LEN = 512; + const LIST_MEMBERS_SEPARATOR = ","; + const LIST_MEMBER_KEY_VALUE_SPLITTER = "="; + /** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ + var TraceState = class TraceState { + _length; + _rawTraceState; + _internalState; + constructor(rawTraceState) { + this._rawTraceState = typeof rawTraceState === "string" ? rawTraceState : ""; + this._length = this._rawTraceState.length; + } + set(key, value) { + if (!(0, validators_1.validateKey)(key) || !(0, validators_1.validateValue)(value)) return this; + const currState = this._getState(); + const currValue = currState.get(key); + let newLength = this._length; + if (typeof currValue === "string") newLength += value.length - currValue.length; + else newLength += key.length + value.length + (currState.size > 0 ? 2 : 1); + if (newLength > MAX_TRACE_STATE_LEN) return this; + const newState = new Map(currState); + newState.delete(key); + newState.set(key, value); + return this._fromState(newState, newLength); + } + unset(key) { + const currState = this._getState(); + const currValue = currState.get(key); + if (typeof currValue !== "string") return this; + let newLength = this._length - (key.length + currValue.length + 1); + if (currState.size > 1) newLength = newLength - 1; + const newState = new Map(currState); + newState.delete(key); + return this._fromState(newState, newLength); + } + get(key) { + return this._getState().get(key); + } + serialize() { + let serialized = ""; + let index = 0; + for (const entry of this._getState()) { + if (index > 0) serialized = LIST_MEMBERS_SEPARATOR + serialized; + serialized = `${entry[0]}${LIST_MEMBER_KEY_VALUE_SPLITTER}${entry[1]}` + serialized; + index++; + } + return serialized; + } + _getState() { + if (this._internalState) return this._internalState; + const vendorMembers = this._rawTraceState.split(LIST_MEMBERS_SEPARATOR); + const vendorEntries = /* @__PURE__ */ new Map(); + let currentLength = 0; + for (const member of vendorMembers) { + const m = member.trim(); + const idx = m.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (idx === -1) continue; + const key = m.slice(0, idx); + const value = m.slice(idx + 1); + if (!(0, validators_1.validateKey)(key) || !(0, validators_1.validateValue)(value)) continue; + const futureLength = currentLength + m.length + (vendorEntries.size > 0 ? 1 : 0); + if (futureLength > MAX_TRACE_STATE_LEN) continue; + vendorEntries.set(key, value); + currentLength = futureLength; + if (vendorEntries.size >= MAX_TRACE_STATE_ITEMS) break; + } + this._length = currentLength; + this._internalState = new Map(Array.from(vendorEntries.entries()).reverse()); + return this._internalState; + } + _fromState(state, length) { + const traceState = Object.create(TraceState.prototype); + traceState._internalState = state; + traceState._length = length; + return traceState; + } + }; + exports.TraceState = TraceState; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js +var require_W3CTraceContextPropagator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.W3CTraceContextPropagator = exports.parseTraceParent = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const suppress_tracing_1 = require_suppress_tracing(); + const TraceState_1 = require_TraceState(); + exports.TRACE_PARENT_HEADER = "traceparent"; + exports.TRACE_STATE_HEADER = "tracestate"; + const VERSION = "00"; + const TRACE_PARENT_REGEX = new RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`); + /** + * Parses information from the [traceparent] span tag and converts it into {@link SpanContext} + * @param traceParent - A meta property that comes from server. + * It should be dynamically generated server side to have the server's request trace Id, + * a parent span Id that was set on the server's request span, + * and the trace flags to indicate the server's sampling decision + * (01 = sampled, 00 = not sampled). + * for example: '{version}-{traceId}-{spanId}-{sampleDecision}' + * For more information see {@link https://www.w3.org/TR/trace-context/} + */ + function parseTraceParent(traceParent) { + const match = TRACE_PARENT_REGEX.exec(traceParent); + if (!match) return null; + if (match[1] === "00" && match[5]) return null; + return { + traceId: match[2], + spanId: match[3], + traceFlags: parseInt(match[4], 16) + }; + } + exports.parseTraceParent = parseTraceParent; + /** + * Propagates {@link SpanContext} through Trace Context format propagation. + * + * Based on the Trace Context specification: + * https://www.w3.org/TR/trace-context/ + */ + var W3CTraceContextPropagator = class { + inject(context, carrier, setter) { + const spanContext = api_1.trace.getSpanContext(context); + if (!spanContext || (0, suppress_tracing_1.isTracingSuppressed)(context) || !(0, api_1.isSpanContextValid)(spanContext)) return; + const traceParent = `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`; + setter.set(carrier, exports.TRACE_PARENT_HEADER, traceParent); + if (spanContext.traceState) setter.set(carrier, exports.TRACE_STATE_HEADER, spanContext.traceState.serialize()); + } + extract(context, carrier, getter) { + const traceParentHeader = getter.get(carrier, exports.TRACE_PARENT_HEADER); + if (!traceParentHeader) return context; + const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader; + if (typeof traceParent !== "string") return context; + const spanContext = parseTraceParent(traceParent); + if (!spanContext) return context; + spanContext.isRemote = true; + const traceStateHeader = getter.get(carrier, exports.TRACE_STATE_HEADER); + if (traceStateHeader) { + const state = Array.isArray(traceStateHeader) ? traceStateHeader.join(",") : traceStateHeader; + spanContext.traceState = new TraceState_1.TraceState(typeof state === "string" ? state : void 0); + } + return api_1.trace.setSpanContext(context, spanContext); + } + fields() { + return [exports.TRACE_PARENT_HEADER, exports.TRACE_STATE_HEADER]; + } + }; + exports.W3CTraceContextPropagator = W3CTraceContextPropagator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js +var require_rpc_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRPCMetadata = exports.deleteRPCMetadata = exports.setRPCMetadata = exports.RPCType = void 0; + const RPC_METADATA_KEY = (0, (init_esm$2(), __toCommonJS(esm_exports$2)).createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"); + var RPCType; + (function(RPCType) { + RPCType["HTTP"] = "http"; + })(RPCType || (exports.RPCType = RPCType = {})); + function setRPCMetadata(context, meta) { + return context.setValue(RPC_METADATA_KEY, meta); + } + exports.setRPCMetadata = setRPCMetadata; + function deleteRPCMetadata(context) { + return context.deleteValue(RPC_METADATA_KEY); + } + exports.deleteRPCMetadata = deleteRPCMetadata; + function getRPCMetadata(context) { + return context.getValue(RPC_METADATA_KEY); + } + exports.getRPCMetadata = getRPCMetadata; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js +var require_lodash_merge = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPlainObject = void 0; + /** + * based on lodash in order to support esm builds without esModuleInterop. + * lodash is using MIT License. + **/ + const objectTag = "[object Object]"; + const nullTag = "[object Null]"; + const undefinedTag = "[object Undefined]"; + const funcToString = Function.prototype.toString; + const objectCtorString = funcToString.call(Object); + const getPrototypeOf = Object.getPrototypeOf; + const objectProto = Object.prototype; + const hasOwnProperty = objectProto.hasOwnProperty; + const symToStringTag = Symbol ? Symbol.toStringTag : void 0; + const nativeObjectToString = objectProto.toString; + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) !== objectTag) return false; + const proto = getPrototypeOf(value); + if (proto === null) return true; + const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString; + } + exports.isPlainObject = isPlainObject; + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) return value === void 0 ? undefinedTag : nullTag; + return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); + } + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + let unmasked = false; + try { + value[symToStringTag] = void 0; + unmasked = true; + } catch {} + const result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) value[symToStringTag] = tag; + else delete value[symToStringTag]; + } + return result; + } + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/utils/merge.js +var require_merge = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.merge = void 0; + const lodash_merge_1 = require_lodash_merge(); + const MAX_LEVEL = 20; + /** + * Merges objects together + * @param args - objects / values to be merged + */ + function merge(...args) { + let result = args.shift(); + const objects = /* @__PURE__ */ new WeakMap(); + while (args.length > 0) result = mergeTwoObjects(result, args.shift(), 0, objects); + return result; + } + exports.merge = merge; + function takeValue(value) { + if (isArray(value)) return value.slice(); + return value; + } + /** + * Merges two objects + * @param one - first object + * @param two - second object + * @param level - current deep level + * @param objects - objects holder that has been already referenced - to prevent + * cyclic dependency + */ + function mergeTwoObjects(one, two, level = 0, objects) { + let result; + if (level > MAX_LEVEL) return; + level++; + if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) result = takeValue(two); + else if (isArray(one)) { + result = one.slice(); + if (isArray(two)) for (let i = 0, j = two.length; i < j; i++) result.push(takeValue(two[i])); + else if (isObject(two)) { + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; + if (key === "__proto__" || key === "constructor" || key === "prototype") continue; + result[key] = takeValue(two[key]); + } + } + } else if (isObject(one)) { + if (isObject(two)) { + if (!shouldMerge(one, two)) return two; + result = Object.assign({}, one); + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; + if (key === "__proto__" || key === "constructor" || key === "prototype") continue; + const twoValue = two[key]; + if (isPrimitive(twoValue)) { + if (typeof twoValue === "undefined") delete result[key]; + else result[key] = twoValue; + } else { + const obj1 = result[key]; + const obj2 = twoValue; + if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) delete result[key]; + else { + if (isObject(obj1) && isObject(obj2)) { + const arr1 = objects.get(obj1) || []; + const arr2 = objects.get(obj2) || []; + arr1.push({ + obj: one, + key + }); + arr2.push({ + obj: two, + key + }); + objects.set(obj1, arr1); + objects.set(obj2, arr2); + } + result[key] = mergeTwoObjects(result[key], twoValue, level, objects); + } + } + } + } else result = two; + } + return result; + } + /** + * Function to check if object has been already reference + * @param obj + * @param key + * @param objects + */ + function wasObjectReferenced(obj, key, objects) { + const arr = objects.get(obj[key]) || []; + for (let i = 0, j = arr.length; i < j; i++) { + const info = arr[i]; + if (info.key === key && info.obj === obj) return true; + } + return false; + } + function isArray(value) { + return Array.isArray(value); + } + function isFunction(value) { + return typeof value === "function"; + } + function isObject(value) { + return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object"; + } + function isPrimitive(value) { + return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null; + } + function shouldMerge(one, two) { + if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) return false; + return true; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/utils/timeout.js +var require_timeout = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callWithTimeout = exports.TimeoutError = void 0; + /** + * Error that is thrown on timeouts. + */ + var TimeoutError = class TimeoutError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, TimeoutError.prototype); + } + }; + exports.TimeoutError = TimeoutError; + /** + * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise + * rejects, and resolves if the specified promise resolves. + * + *

NOTE: this operation will continue even after it throws a {@link TimeoutError}. + * + * @param promise promise to use with timeout. + * @param timeout the timeout in milliseconds until the returned promise is rejected. + */ + function callWithTimeout(promise, timeout) { + let timeoutHandle; + const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { + timeoutHandle = setTimeout(function timeoutHandler() { + reject(new TimeoutError("Operation timed out.")); + }, timeout); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }, (reason) => { + clearTimeout(timeoutHandle); + throw reason; + }); + } + exports.callWithTimeout = callWithTimeout; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/utils/url.js +var require_url = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isUrlIgnored = exports.urlMatches = void 0; + function urlMatches(url, urlToMatch) { + if (typeof urlToMatch === "string") return url === urlToMatch; + else return !!url.match(urlToMatch); + } + exports.urlMatches = urlMatches; + /** + * Check if {@param url} should be ignored when comparing against {@param ignoredUrls} + * @param url + * @param ignoredUrls + */ + function isUrlIgnored(url, ignoredUrls) { + if (!ignoredUrls) return false; + for (const ignoreUrl of ignoredUrls) if (urlMatches(url, ignoreUrl)) return true; + return false; + } + exports.isUrlIgnored = isUrlIgnored; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/utils/promise.js +var require_promise = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Deferred = void 0; + var Deferred = class { + _promise; + _resolve; + _reject; + constructor() { + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + get promise() { + return this._promise; + } + resolve(val) { + this._resolve(val); + } + reject(err) { + this._reject(err); + } + }; + exports.Deferred = Deferred; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/utils/callback.js +var require_callback = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BindOnceFuture = void 0; + const promise_1 = require_promise(); + /** + * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked. + */ + var BindOnceFuture = class { + _isCalled = false; + _deferred = new promise_1.Deferred(); + _callback; + _that; + constructor(callback, that) { + this._callback = callback; + this._that = that; + } + get isCalled() { + return this._isCalled; + } + get promise() { + return this._deferred.promise; + } + call(...args) { + if (!this._isCalled) { + this._isCalled = true; + try { + Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err)); + } catch (err) { + this._deferred.reject(err); + } + } + return this._deferred.promise; + } + }; + exports.BindOnceFuture = BindOnceFuture; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/utils/configuration.js +var require_configuration = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.diagLogLevelFromString = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const logLevelMap = { + ALL: api_1.DiagLogLevel.ALL, + VERBOSE: api_1.DiagLogLevel.VERBOSE, + DEBUG: api_1.DiagLogLevel.DEBUG, + INFO: api_1.DiagLogLevel.INFO, + WARN: api_1.DiagLogLevel.WARN, + ERROR: api_1.DiagLogLevel.ERROR, + NONE: api_1.DiagLogLevel.NONE + }; + /** + * Convert a string to a {@link DiagLogLevel}, defaults to {@link DiagLogLevel} if the log level does not exist or undefined if the input is undefined. + * @param value + */ + function diagLogLevelFromString(value) { + if (value == null) return; + const resolvedLogLevel = logLevelMap[value.toUpperCase()]; + if (resolvedLogLevel == null) { + api_1.diag.warn(`Unknown log level "${value}", expected one of ${Object.keys(logLevelMap)}, using default`); + return api_1.DiagLogLevel.INFO; + } + return resolvedLogLevel; + } + exports.diagLogLevelFromString = diagLogLevelFromString; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/internal/exporter.js +var require_exporter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports._export = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const suppress_tracing_1 = require_suppress_tracing(); + /** + * @internal + * Shared functionality used by Exporters while exporting data, including suppression of Traces. + */ + function _export(exporter, arg) { + return new Promise((resolve) => { + api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => { + exporter.export(arg, resolve); + }); + }); + } + exports._export = _export; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+core@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/core/build/src/index.js +var require_src$8 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.diagLogLevelFromString = exports.BindOnceFuture = exports.urlMatches = exports.isUrlIgnored = exports.callWithTimeout = exports.TimeoutError = exports.merge = exports.TraceState = exports.unsuppressTracing = exports.suppressTracing = exports.isTracingSuppressed = exports.setRPCMetadata = exports.getRPCMetadata = exports.deleteRPCMetadata = exports.RPCType = exports.parseTraceParent = exports.W3CTraceContextPropagator = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = exports.CompositePropagator = exports.otperformance = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports._globalThis = exports.SDK_INFO = exports.parseKeyPairsIntoRecord = exports.ExportResultCode = exports.unrefTimer = exports.timeInputToHrTime = exports.millisToHrTime = exports.isTimeInputHrTime = exports.isTimeInput = exports.hrTimeToTimeStamp = exports.hrTimeToSeconds = exports.hrTimeToNanoseconds = exports.hrTimeToMilliseconds = exports.hrTimeToMicroseconds = exports.hrTimeDuration = exports.hrTime = exports.getTimeOrigin = exports.addHrTimes = exports.loggingErrorHandler = exports.setGlobalErrorHandler = exports.globalErrorHandler = exports.sanitizeAttributes = exports.isAttributeValue = exports.AnchoredClock = exports.W3CBaggagePropagator = void 0; + exports.internal = void 0; + var W3CBaggagePropagator_1 = require_W3CBaggagePropagator(); + Object.defineProperty(exports, "W3CBaggagePropagator", { + enumerable: true, + get: function() { + return W3CBaggagePropagator_1.W3CBaggagePropagator; + } + }); + var anchored_clock_1 = require_anchored_clock(); + Object.defineProperty(exports, "AnchoredClock", { + enumerable: true, + get: function() { + return anchored_clock_1.AnchoredClock; + } + }); + var attributes_1 = require_attributes(); + Object.defineProperty(exports, "isAttributeValue", { + enumerable: true, + get: function() { + return attributes_1.isAttributeValue; + } + }); + Object.defineProperty(exports, "sanitizeAttributes", { + enumerable: true, + get: function() { + return attributes_1.sanitizeAttributes; + } + }); + var global_error_handler_1 = require_global_error_handler(); + Object.defineProperty(exports, "globalErrorHandler", { + enumerable: true, + get: function() { + return global_error_handler_1.globalErrorHandler; + } + }); + Object.defineProperty(exports, "setGlobalErrorHandler", { + enumerable: true, + get: function() { + return global_error_handler_1.setGlobalErrorHandler; + } + }); + var logging_error_handler_1 = require_logging_error_handler(); + Object.defineProperty(exports, "loggingErrorHandler", { + enumerable: true, + get: function() { + return logging_error_handler_1.loggingErrorHandler; + } + }); + var time_1 = require_time(); + Object.defineProperty(exports, "addHrTimes", { + enumerable: true, + get: function() { + return time_1.addHrTimes; + } + }); + Object.defineProperty(exports, "getTimeOrigin", { + enumerable: true, + get: function() { + return time_1.getTimeOrigin; + } + }); + Object.defineProperty(exports, "hrTime", { + enumerable: true, + get: function() { + return time_1.hrTime; + } + }); + Object.defineProperty(exports, "hrTimeDuration", { + enumerable: true, + get: function() { + return time_1.hrTimeDuration; + } + }); + Object.defineProperty(exports, "hrTimeToMicroseconds", { + enumerable: true, + get: function() { + return time_1.hrTimeToMicroseconds; + } + }); + Object.defineProperty(exports, "hrTimeToMilliseconds", { + enumerable: true, + get: function() { + return time_1.hrTimeToMilliseconds; + } + }); + Object.defineProperty(exports, "hrTimeToNanoseconds", { + enumerable: true, + get: function() { + return time_1.hrTimeToNanoseconds; + } + }); + Object.defineProperty(exports, "hrTimeToSeconds", { + enumerable: true, + get: function() { + return time_1.hrTimeToSeconds; + } + }); + Object.defineProperty(exports, "hrTimeToTimeStamp", { + enumerable: true, + get: function() { + return time_1.hrTimeToTimeStamp; + } + }); + Object.defineProperty(exports, "isTimeInput", { + enumerable: true, + get: function() { + return time_1.isTimeInput; + } + }); + Object.defineProperty(exports, "isTimeInputHrTime", { + enumerable: true, + get: function() { + return time_1.isTimeInputHrTime; + } + }); + Object.defineProperty(exports, "millisToHrTime", { + enumerable: true, + get: function() { + return time_1.millisToHrTime; + } + }); + Object.defineProperty(exports, "timeInputToHrTime", { + enumerable: true, + get: function() { + return time_1.timeInputToHrTime; + } + }); + var timer_util_1 = require_timer_util(); + Object.defineProperty(exports, "unrefTimer", { + enumerable: true, + get: function() { + return timer_util_1.unrefTimer; + } + }); + var ExportResult_1 = require_ExportResult(); + Object.defineProperty(exports, "ExportResultCode", { + enumerable: true, + get: function() { + return ExportResult_1.ExportResultCode; + } + }); + var utils_1 = require_utils$5(); + Object.defineProperty(exports, "parseKeyPairsIntoRecord", { + enumerable: true, + get: function() { + return utils_1.parseKeyPairsIntoRecord; + } + }); + var platform_1 = require_platform$3(); + Object.defineProperty(exports, "SDK_INFO", { + enumerable: true, + get: function() { + return platform_1.SDK_INFO; + } + }); + Object.defineProperty(exports, "_globalThis", { + enumerable: true, + get: function() { + return platform_1._globalThis; + } + }); + Object.defineProperty(exports, "getStringFromEnv", { + enumerable: true, + get: function() { + return platform_1.getStringFromEnv; + } + }); + Object.defineProperty(exports, "getBooleanFromEnv", { + enumerable: true, + get: function() { + return platform_1.getBooleanFromEnv; + } + }); + Object.defineProperty(exports, "getNumberFromEnv", { + enumerable: true, + get: function() { + return platform_1.getNumberFromEnv; + } + }); + Object.defineProperty(exports, "getStringListFromEnv", { + enumerable: true, + get: function() { + return platform_1.getStringListFromEnv; + } + }); + Object.defineProperty(exports, "otperformance", { + enumerable: true, + get: function() { + return platform_1.otperformance; + } + }); + var composite_1 = require_composite(); + Object.defineProperty(exports, "CompositePropagator", { + enumerable: true, + get: function() { + return composite_1.CompositePropagator; + } + }); + var W3CTraceContextPropagator_1 = require_W3CTraceContextPropagator(); + Object.defineProperty(exports, "TRACE_PARENT_HEADER", { + enumerable: true, + get: function() { + return W3CTraceContextPropagator_1.TRACE_PARENT_HEADER; + } + }); + Object.defineProperty(exports, "TRACE_STATE_HEADER", { + enumerable: true, + get: function() { + return W3CTraceContextPropagator_1.TRACE_STATE_HEADER; + } + }); + Object.defineProperty(exports, "W3CTraceContextPropagator", { + enumerable: true, + get: function() { + return W3CTraceContextPropagator_1.W3CTraceContextPropagator; + } + }); + Object.defineProperty(exports, "parseTraceParent", { + enumerable: true, + get: function() { + return W3CTraceContextPropagator_1.parseTraceParent; + } + }); + var rpc_metadata_1 = require_rpc_metadata(); + Object.defineProperty(exports, "RPCType", { + enumerable: true, + get: function() { + return rpc_metadata_1.RPCType; + } + }); + Object.defineProperty(exports, "deleteRPCMetadata", { + enumerable: true, + get: function() { + return rpc_metadata_1.deleteRPCMetadata; + } + }); + Object.defineProperty(exports, "getRPCMetadata", { + enumerable: true, + get: function() { + return rpc_metadata_1.getRPCMetadata; + } + }); + Object.defineProperty(exports, "setRPCMetadata", { + enumerable: true, + get: function() { + return rpc_metadata_1.setRPCMetadata; + } + }); + var suppress_tracing_1 = require_suppress_tracing(); + Object.defineProperty(exports, "isTracingSuppressed", { + enumerable: true, + get: function() { + return suppress_tracing_1.isTracingSuppressed; + } + }); + Object.defineProperty(exports, "suppressTracing", { + enumerable: true, + get: function() { + return suppress_tracing_1.suppressTracing; + } + }); + Object.defineProperty(exports, "unsuppressTracing", { + enumerable: true, + get: function() { + return suppress_tracing_1.unsuppressTracing; + } + }); + var TraceState_1 = require_TraceState(); + Object.defineProperty(exports, "TraceState", { + enumerable: true, + get: function() { + return TraceState_1.TraceState; + } + }); + var merge_1 = require_merge(); + Object.defineProperty(exports, "merge", { + enumerable: true, + get: function() { + return merge_1.merge; + } + }); + var timeout_1 = require_timeout(); + Object.defineProperty(exports, "TimeoutError", { + enumerable: true, + get: function() { + return timeout_1.TimeoutError; + } + }); + Object.defineProperty(exports, "callWithTimeout", { + enumerable: true, + get: function() { + return timeout_1.callWithTimeout; + } + }); + var url_1 = require_url(); + Object.defineProperty(exports, "isUrlIgnored", { + enumerable: true, + get: function() { + return url_1.isUrlIgnored; + } + }); + Object.defineProperty(exports, "urlMatches", { + enumerable: true, + get: function() { + return url_1.urlMatches; + } + }); + var callback_1 = require_callback(); + Object.defineProperty(exports, "BindOnceFuture", { + enumerable: true, + get: function() { + return callback_1.BindOnceFuture; + } + }); + var configuration_1 = require_configuration(); + Object.defineProperty(exports, "diagLogLevelFromString", { + enumerable: true, + get: function() { + return configuration_1.diagLogLevelFromString; + } + }); + const exporter_1 = require_exporter(); + exports.internal = { _export: exporter_1._export }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js +var OTLPExporterBase; +var init_OTLPExporterBase = __esmMin((() => { + OTLPExporterBase = class { + _delegate; + constructor(delegate) { + this._delegate = delegate; + } + /** + * Export items. + * @param items + * @param resultCallback + */ + export(items, resultCallback) { + this._delegate.export(items, resultCallback); + } + forceFlush() { + return this._delegate.forceFlush(); + } + shutdown() { + return this._delegate.shutdown(); + } + setMetrics(metrics) { + this._delegate.setMetrics(metrics); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js +var OTLPExporterError; +var init_types = __esmMin((() => { + OTLPExporterError = class extends Error { + code; + name = "OTLPExporterError"; + data; + constructor(message, code, data) { + super(message); + this.data = data; + this.code = code; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-configuration.js +function validateTimeoutMillis(timeoutMillis) { + if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) return timeoutMillis; + throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`); +} +function wrapStaticHeadersInFunction(headers) { + if (headers == null) return; + return async () => headers; +} +/** +* @param userProvidedConfiguration Configuration options provided by the user in code. +* @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. +* @param defaultConfiguration The defaults as defined by the exporter specification +*/ +function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? fallbackConfiguration.timeoutMillis ?? defaultConfiguration.timeoutMillis), + concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? fallbackConfiguration.concurrencyLimit ?? defaultConfiguration.concurrencyLimit, + compression: userProvidedConfiguration.compression ?? fallbackConfiguration.compression ?? defaultConfiguration.compression + }; +} +function getSharedConfigurationDefaults() { + return { + timeoutMillis: 1e4, + concurrencyLimit: 30, + compression: "none" + }; +} +var init_shared_configuration = __esmMin((() => {})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/legacy-node-configuration.js +var CompressionAlgorithm; +var init_legacy_node_configuration = __esmMin((() => { + ; + (function(CompressionAlgorithm) { + CompressionAlgorithm["NONE"] = "none"; + CompressionAlgorithm["GZIP"] = "gzip"; + })(CompressionAlgorithm || (CompressionAlgorithm = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js +/** +* Promise queue for keeping track of export promises. Finished promises will be auto-dequeued. +* Allows for awaiting all promises in the queue. +*/ +function createBoundedQueueExportPromiseHandler(options) { + return new BoundedQueueExportPromiseHandler(options.concurrencyLimit); +} +var BoundedQueueExportPromiseHandler; +var init_bounded_queue_export_promise_handler = __esmMin((() => { + BoundedQueueExportPromiseHandler = class { + _concurrencyLimit; + _sendingPromises = []; + /** + * @param concurrencyLimit maximum promises allowed in a queue at the same time. + */ + constructor(concurrencyLimit) { + this._concurrencyLimit = concurrencyLimit; + } + pushPromise(promise) { + if (this.hasReachedLimit()) throw new Error("Concurrency Limit reached"); + this._sendingPromises.push(promise); + const popPromise = () => { + const index = this._sendingPromises.indexOf(promise); + this._sendingPromises.splice(index, 1); + }; + promise.then(popPromise, popPromise); + } + hasReachedLimit() { + return this._sendingPromises.length >= this._concurrencyLimit; + } + async awaitAll() { + await Promise.all(this._sendingPromises); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js +function isPartialSuccessResponse(response) { + return Object.prototype.hasOwnProperty.call(response, "partialSuccess"); +} +/** +* Default response handler that logs a partial success to the console. +*/ +function createLoggingPartialSuccessResponseHandler() { + return { handleResponse(response) { + if (response == null || !isPartialSuccessResponse(response) || response.partialSuccess == null || Object.keys(response.partialSuccess).length === 0) return; + diag.warn("Received Partial Success response:", JSON.stringify(response.partialSuccess)); + } }; +} +var init_logging_response_handler = __esmMin((() => { + init_esm$2(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js +/** +* Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all +* signals. +*/ +function createOtlpExportDelegate(components, settings) { + return new OTLPExportDelegate(components.transport, components.serializer, createLoggingPartialSuccessResponseHandler(), components.promiseHandler, components.metrics, settings.timeout); +} +var import_src$8, OTLPExportDelegate; +var init_otlp_export_delegate = __esmMin((() => { + import_src$8 = require_src$8(); + init_types(); + init_logging_response_handler(); + init_esm$2(); + OTLPExportDelegate = class { + _metrics; + _diagLogger; + _transport; + _serializer; + _responseHandler; + _promiseQueue; + _timeout; + constructor(transport, serializer, responseHandler, promiseQueue, metrics, timeout) { + this._transport = transport; + this._serializer = serializer; + this._responseHandler = responseHandler; + this._promiseQueue = promiseQueue; + this._timeout = timeout; + this._diagLogger = diag.createComponentLogger({ namespace: "OTLPExportDelegate" }); + this._metrics = metrics; + } + export(internalRepresentation, resultCallback) { + this._diagLogger.debug("items to be sent", internalRepresentation); + if (this._promiseQueue.hasReachedLimit()) { + resultCallback({ + code: import_src$8.ExportResultCode.FAILED, + error: /* @__PURE__ */ new Error("Concurrent export limit reached") + }); + return; + } + const serializedRequest = this._serializer.serializeRequest(internalRepresentation); + if (serializedRequest == null) { + resultCallback({ + code: import_src$8.ExportResultCode.FAILED, + error: /* @__PURE__ */ new Error("Nothing to send") + }); + return; + } + const finishExport = this._metrics.startExport(internalRepresentation); + this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then((response) => { + if (response.status === "success") { + finishExport(void 0); + if (response.data != null) try { + this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data)); + } catch (e) { + this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?", e, response.data); + } + resultCallback({ code: import_src$8.ExportResultCode.SUCCESS }); + return; + } else if (response.status === "failure" && response.error) { + finishExport(response.error); + resultCallback({ + code: import_src$8.ExportResultCode.FAILED, + error: response.error + }); + return; + } else if (response.status === "retryable") { + finishExport("export_max_retries"); + resultCallback({ + code: import_src$8.ExportResultCode.FAILED, + error: response.error ?? new OTLPExporterError("Export failed with retryable status") + }); + } else { + finishExport("export_failed"); + resultCallback({ + code: import_src$8.ExportResultCode.FAILED, + error: new OTLPExporterError("Export failed with unknown error") + }); + } + }, (reason) => { + finishExport(reason); + resultCallback({ + code: import_src$8.ExportResultCode.FAILED, + error: reason + }); + })); + } + forceFlush() { + return this._promiseQueue.awaitAll(); + } + setMetrics(metrics) { + this._metrics = metrics; + } + async shutdown() { + this._diagLogger.debug("shutdown started"); + await this.forceFlush(); + this._transport.shutdown(); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-network-export-delegate.js +function createOtlpNetworkExportDelegate(options, serializer, metrics, transport) { + return createOtlpExportDelegate({ + transport, + serializer, + promiseHandler: createBoundedQueueExportPromiseHandler(options), + metrics + }, { timeout: options.timeoutMillis }); +} +var init_otlp_network_export_delegate = __esmMin((() => { + init_bounded_queue_export_promise_handler(); + init_otlp_export_delegate(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/semconv.js +var ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_OTEL_COMPONENT_NAME, ATTR_OTEL_COMPONENT_TYPE, ATTR_SERVER_ADDRESS, ATTR_SERVER_PORT, ATTR_ERROR_TYPE; +var init_semconv = __esmMin((() => { + ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; + ATTR_OTEL_COMPONENT_NAME = "otel.component.name"; + ATTR_OTEL_COMPONENT_TYPE = "otel.component.type"; + ATTR_SERVER_ADDRESS = "server.address"; + ATTR_SERVER_PORT = "server.port"; + ATTR_ERROR_TYPE = "error.type"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/version.js +var VERSION; +var init_version = __esmMin((() => { + VERSION = "0.222.0"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/ExporterMetrics.js +var import_src$7, componentCounter, ExporterMetrics; +var init_ExporterMetrics = __esmMin((() => { + init_esm$2(); + import_src$7 = require_src$8(); + init_semconv(); + init_version(); + componentCounter = /* @__PURE__ */ new Map(); + ExporterMetrics = class { + inflight; + exported; + duration; + standardAttrs; + responseAttributesFromError; + helper; + constructor(options) { + const { componentType, metricsHelper, meterProvider, url, responseAttributesFromError } = options; + this.responseAttributesFromError = responseAttributesFromError; + const meter = meterProvider ? meterProvider.getMeter("@opentelemetry/otlp-exporter", VERSION) : createNoopMeter(); + const counter = componentCounter.get(componentType) ?? 0; + componentCounter.set(componentType, counter + 1); + this.standardAttrs = { + [ATTR_OTEL_COMPONENT_TYPE]: componentType, + [ATTR_OTEL_COMPONENT_NAME]: `${componentType}/${counter}` + }; + if (url) { + let urlToParse = url; + if (!url.includes("://")) urlToParse = `http://${url}`; + try { + const parsedUrl = new URL(urlToParse); + this.standardAttrs[ATTR_SERVER_ADDRESS] = parsedUrl.hostname; + let port = void 0; + if (parsedUrl.port) port = Number(parsedUrl.port); + else if (parsedUrl.protocol === "http:") port = 80; + else if (parsedUrl.protocol === "https:") port = 443; + if (typeof port === "number") this.standardAttrs[ATTR_SERVER_PORT] = port; + } catch {} + } + this.helper = metricsHelper; + this.inflight = meter.createUpDownCounter(`otel.sdk.exporter.${this.helper.name}.inflight`, { + unit: `{${this.helper.name}}`, + description: `The number of ${this.helper.name}s which were passed to the exporter, but that have not been exported yet (neither successful, nor failed).` + }); + this.exported = meter.createCounter(`otel.sdk.exporter.${this.helper.name}.exported`, { + unit: `{${this.helper.name}}`, + description: `The number of ${this.helper.name}s for which the export has finished, either successful or failed.` + }); + this.duration = meter.createHistogram("otel.sdk.exporter.operation.duration", { + unit: "s", + description: "The duration of exporting a batch of telemetry records.", + advice: { explicitBucketBoundaries: [] } + }); + } + startExport(request) { + const numItems = this.helper.countItems(request); + const startTime = (0, import_src$7.hrTime)(); + this.inflight.add(numItems, this.standardAttrs); + return (error) => { + const endTime = (0, import_src$7.hrTime)(); + this.inflight.add(-numItems, this.standardAttrs); + const exportedAttrs = error ? { + ...this.standardAttrs, + [ATTR_ERROR_TYPE]: error instanceof Error ? error.name : "export_failed" + } : this.standardAttrs; + this.exported.add(numItems, exportedAttrs); + const durationAttrs = { + ...exportedAttrs, + ...this.responseAttributesFromError(error) + }; + const duration = (0, import_src$7.hrTimeToMilliseconds)((0, import_src$7.hrTimeDuration)(startTime, endTime)) / 1e3; + this.duration.record(duration, durationAttrs); + }; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/index.js +var esm_exports = /* @__PURE__ */ __exportAll({ + CompressionAlgorithm: () => CompressionAlgorithm, + ExporterMetrics: () => ExporterMetrics, + OTLPExporterBase: () => OTLPExporterBase, + OTLPExporterError: () => OTLPExporterError, + createOtlpNetworkExportDelegate: () => createOtlpNetworkExportDelegate, + getSharedConfigurationDefaults: () => getSharedConfigurationDefaults, + mergeOtlpSharedConfigurationWithDefaults: () => mergeOtlpSharedConfigurationWithDefaults +}); +var init_esm = __esmMin((() => { + init_OTLPExporterBase(); + init_types(); + init_shared_configuration(); + init_legacy_node_configuration(); + init_otlp_network_export_delegate(); + init_ExporterMetrics(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/index.js +var require_metrics$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricsExporterMetricsHelper = void 0; + exports.MetricsExporterMetricsHelper = { + name: "metric_data_point", + countItems: (request) => { + let count = 0; + for (const scopeMetrics of request.scopeMetrics) for (const metric of scopeMetrics.metrics) count += metric.dataPoints.length; + return count; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/index.js +var require_trace$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceExporterMetricsHelper = void 0; + exports.TraceExporterMetricsHelper = { + name: "span", + countItems: (request) => request.length + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/index.js +var require_logs$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LogsExporterMetricsHelper = void 0; + /** + * @experimental this helper may receive breaking changes in minor versions, pin this package's version when using this constant + */ + exports.LogsExporterMetricsHelper = { + name: "log", + countItems: (request) => request.length + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/utils.js +var require_utils$4 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.estimateVarintSize = void 0; + /** + * Estimate size of a number encoded as varint. + * @param v value to calculate size for + * @returns size in bytes of the varint encoding of the value + */ + function estimateVarintSize(v) { + if (v < 0) return 10; + if (v < 128) return 1; + if (v < 16384) return 2; + if (v < 2097152) return 3; + if (v < 268435456) return 4; + if (v < 34359738368) return 5; + if (v < 4398046511104) return 6; + if (v < 562949953421312) return 7; + if (v < 72057594037927940) return 8; + return 9; + } + exports.estimateVarintSize = estimateVarintSize; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/protobuf-writer.js +var require_protobuf_writer = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufWriter = exports.GROWING_BUFFER_DEBUG_MESSAGE = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const utils_1 = require_utils$4(); + exports.GROWING_BUFFER_DEBUG_MESSAGE = "ProtobufWriter: estimated size was too small, growing buffer."; + /** + * bytes reserved for length in length-delimited fields + * using 1 to assume most length-delimited fields are small + */ + const RESERVED_LENGTH_BYTES = 1; + /** + * Primitive protobuf writer, optimized to avoid small object allocations. + * Grows buffer dynamically if initial size is exceeded. + */ + var ProtobufWriter = class { + _buffer; + _textEncoder; + _dataView; + pos = 0; + constructor(estimatedSize = 65536) { + this._buffer = new Uint8Array(estimatedSize); + this._textEncoder = new TextEncoder(); + this._dataView = new DataView(this._buffer.buffer, this._buffer.byteOffset); + } + /** + * Ensure buffer has capacity for at least size more bytes + */ + _ensureCapacity(size) { + const needed = this.pos + size; + if (needed <= this._buffer.length) return; + api_1.diag.debug(exports.GROWING_BUFFER_DEBUG_MESSAGE); + let newSize = this._buffer.length * 2; + while (newSize < needed) newSize *= 2; + const newBuffer = new Uint8Array(newSize); + newBuffer.set(this._buffer); + this._buffer = newBuffer; + this._dataView = new DataView(this._buffer.buffer, this._buffer.byteOffset); + } + /** + * Get the written bytes as a Uint8Array + */ + finish() { + return this._buffer.subarray(0, this.pos); + } + /** + * Insert placeholder for length. Update later with {@link finishLengthDelimited} + * Returns the position where to write the length. + */ + startLengthDelimited() { + const lengthPos = this.pos; + this._ensureCapacity(RESERVED_LENGTH_BYTES); + this.pos += RESERVED_LENGTH_BYTES; + return lengthPos; + } + /** + * Write length varint at placeholder position and shift content forward if needed. + * Most messages are small (< 128 bytes), so we reserve 1 byte and only shift + * when the length needs more bytes. + */ + finishLengthDelimited(pos, length) { + const v = length >>> 0; + const varintSize = (0, utils_1.estimateVarintSize)(v); + if (varintSize > RESERVED_LENGTH_BYTES) { + const additionalBytes = varintSize - RESERVED_LENGTH_BYTES; + this._ensureCapacity(additionalBytes); + this._buffer.copyWithin(pos + varintSize, pos + RESERVED_LENGTH_BYTES, this.pos); + this.pos += additionalBytes; + } + let writePos = pos; + if (v < 128) this._buffer[writePos] = v; + else if (v < 16384) { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos] = v >>> 7; + } else if (v < 2097152) { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos++] = v >>> 7 & 127 | 128; + this._buffer[writePos] = v >>> 14; + } else if (v < 268435456) { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos++] = v >>> 7 & 127 | 128; + this._buffer[writePos++] = v >>> 14 & 127 | 128; + this._buffer[writePos] = v >>> 21; + } else { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos++] = v >>> 7 & 127 | 128; + this._buffer[writePos++] = v >>> 14 & 127 | 128; + this._buffer[writePos++] = v >>> 21 & 127 | 128; + this._buffer[writePos] = v >>> 28; + } + } + /** + * Write a sint32 value using zigzag encoding + */ + writeSint32(value) { + this.writeVarint((value << 1 ^ value >> 31) >>> 0); + } + /** + * Write a signed 64-bit fixed integer (sfixed64) from a JS number. + * Handles negative values via two's complement. + */ + writeSfixed64(value) { + let low; + let high; + if (value >= 0) { + low = value >>> 0; + high = value / 4294967296 >>> 0; + } else { + const abs = Math.abs(value); + low = abs >>> 0; + high = abs / 4294967296 >>> 0; + low = ~low >>> 0; + high = ~high >>> 0; + low = low + 1 >>> 0; + if (low === 0) high = high + 1 >>> 0; + } + this.writeFixed64(low, high); + } + /** + * Write a varint (variable-length integer) + */ + writeVarint(value) { + this._ensureCapacity((0, utils_1.estimateVarintSize)(value)); + if (value >= 0 && value <= 4294967295) { + let v = value >>> 0; + while (v > 127) { + this._buffer[this.pos++] = v & 127 | 128; + v >>>= 7; + } + this._buffer[this.pos++] = v; + } else { + let low; + let high; + if (value >= 0) { + low = value >>> 0; + high = value / 4294967296 >>> 0; + } else { + const abs = Math.abs(value); + low = abs >>> 0; + high = abs / 4294967296 >>> 0; + low = ~low >>> 0; + high = ~high >>> 0; + low = low + 1 >>> 0; + if (low === 0) high = high + 1 >>> 0; + } + while (high > 0 || low > 127) { + this._buffer[this.pos++] = low & 127 | 128; + low = (low >>> 7 | high << 25) >>> 0; + high >>>= 7; + } + this._buffer[this.pos++] = low & 127; + } + } + /** + * Write a 32-bit fixed integer (little-endian) + */ + writeFixed32(value) { + this._ensureCapacity(4); + const v = value >>> 0; + this._buffer[this.pos++] = v & 255; + this._buffer[this.pos++] = v >>> 8 & 255; + this._buffer[this.pos++] = v >>> 16 & 255; + this._buffer[this.pos++] = v >>> 24 & 255; + } + /** + * Write a 64-bit fixed integer (little-endian) + * @param low - Low 32 bits + * @param high - High 32 bits + */ + writeFixed64(low, high) { + this._ensureCapacity(8); + const l = low >>> 0; + const h = high >>> 0; + this._buffer[this.pos++] = l & 255; + this._buffer[this.pos++] = l >>> 8 & 255; + this._buffer[this.pos++] = l >>> 16 & 255; + this._buffer[this.pos++] = l >>> 24 & 255; + this._buffer[this.pos++] = h & 255; + this._buffer[this.pos++] = h >>> 8 & 255; + this._buffer[this.pos++] = h >>> 16 & 255; + this._buffer[this.pos++] = h >>> 24 & 255; + } + /** + * Write length-delimited data (varint length + bytes) + */ + writeBytes(bytes) { + this.writeVarint(bytes.length); + this._ensureCapacity(bytes.length); + this._buffer.set(bytes, this.pos); + this.pos += bytes.length; + } + /** + * Write a field key (field number + wire type) + */ + writeTag(fieldNumber, wireType) { + this.writeVarint(fieldNumber << 3 | wireType); + } + /** + * Write a double (64-bit IEEE 754) + */ + writeDouble(value) { + this._ensureCapacity(8); + this._dataView.setFloat64(this.pos, value, true); + this.pos += 8; + } + /** + * Write a string as UTF-8 bytes (length-delimited) + */ + writeString(str) { + let isAscii = true; + const len = str.length; + for (let i = 0; i < len; i++) if (str.charCodeAt(i) > 127) { + isAscii = false; + break; + } + if (isAscii) { + this.writeVarint(len); + this._ensureCapacity(len); + for (let i = 0; i < len; i++) this._buffer[this.pos++] = str.charCodeAt(i); + } else { + const bytes = this._textEncoder.encode(str); + this.writeBytes(bytes); + } + } + }; + exports.ProtobufWriter = ProtobufWriter; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js +var require_hex_to_binary = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.hexToBinary = void 0; + function intValue(charCode) { + if (charCode >= 48 && charCode <= 57) return charCode - 48; + if (charCode >= 97 && charCode <= 102) return charCode - 87; + return charCode - 55; + } + function hexToBinary(hexStr) { + const buf = new Uint8Array(hexStr.length / 2); + let offset = 0; + for (let i = 0; i < hexStr.length; i += 2) { + const hi = intValue(hexStr.charCodeAt(i)); + const lo = intValue(hexStr.charCodeAt(i + 1)); + buf[offset++] = hi << 4 | lo; + } + return buf; + } + exports.hexToBinary = hexToBinary; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js +var require_LogRecord = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SeverityNumber = void 0; + var SeverityNumber; + (function(SeverityNumber) { + SeverityNumber[SeverityNumber["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + SeverityNumber[SeverityNumber["TRACE"] = 1] = "TRACE"; + SeverityNumber[SeverityNumber["TRACE2"] = 2] = "TRACE2"; + SeverityNumber[SeverityNumber["TRACE3"] = 3] = "TRACE3"; + SeverityNumber[SeverityNumber["TRACE4"] = 4] = "TRACE4"; + SeverityNumber[SeverityNumber["DEBUG"] = 5] = "DEBUG"; + SeverityNumber[SeverityNumber["DEBUG2"] = 6] = "DEBUG2"; + SeverityNumber[SeverityNumber["DEBUG3"] = 7] = "DEBUG3"; + SeverityNumber[SeverityNumber["DEBUG4"] = 8] = "DEBUG4"; + SeverityNumber[SeverityNumber["INFO"] = 9] = "INFO"; + SeverityNumber[SeverityNumber["INFO2"] = 10] = "INFO2"; + SeverityNumber[SeverityNumber["INFO3"] = 11] = "INFO3"; + SeverityNumber[SeverityNumber["INFO4"] = 12] = "INFO4"; + SeverityNumber[SeverityNumber["WARN"] = 13] = "WARN"; + SeverityNumber[SeverityNumber["WARN2"] = 14] = "WARN2"; + SeverityNumber[SeverityNumber["WARN3"] = 15] = "WARN3"; + SeverityNumber[SeverityNumber["WARN4"] = 16] = "WARN4"; + SeverityNumber[SeverityNumber["ERROR"] = 17] = "ERROR"; + SeverityNumber[SeverityNumber["ERROR2"] = 18] = "ERROR2"; + SeverityNumber[SeverityNumber["ERROR3"] = 19] = "ERROR3"; + SeverityNumber[SeverityNumber["ERROR4"] = 20] = "ERROR4"; + SeverityNumber[SeverityNumber["FATAL"] = 21] = "FATAL"; + SeverityNumber[SeverityNumber["FATAL2"] = 22] = "FATAL2"; + SeverityNumber[SeverityNumber["FATAL3"] = 23] = "FATAL3"; + SeverityNumber[SeverityNumber["FATAL4"] = 24] = "FATAL4"; + })(SeverityNumber || (exports.SeverityNumber = SeverityNumber = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js +var require_NoopLogger = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createNoopLogger = exports.NOOP_LOGGER = exports.NoopLogger = void 0; + var NoopLogger = class { + emit(_logRecord) {} + enabled() { + return false; + } + }; + exports.NoopLogger = NoopLogger; + exports.NOOP_LOGGER = new NoopLogger(); + /** + * Create a no-op Logger + */ + function createNoopLogger() { + return exports.NOOP_LOGGER; + } + exports.createNoopLogger = createNoopLogger; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js +var require_global_utils = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.API_BACKWARDS_COMPATIBILITY_VERSION = exports.makeGetter = exports._global = exports.GLOBAL_LOGS_API_KEY = void 0; + exports.GLOBAL_LOGS_API_KEY = Symbol.for("io.opentelemetry.js.api.logs"); + exports._global = globalThis; + /** + * Make a function which accepts a version integer and returns the instance of an API if the version + * is compatible, or a fallback version (usually NOOP) if it is not. + * + * @param requiredVersion Backwards compatibility version which is required to return the instance + * @param instance Instance which should be returned if the required version is compatible + * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible + */ + function makeGetter(requiredVersion, instance, fallback) { + return (version) => version === requiredVersion ? instance : fallback; + } + exports.makeGetter = makeGetter; + /** + * A number which should be incremented each time a backwards incompatible + * change is made to the API. This number is used when an API package + * attempts to access the global API to ensure it is getting a compatible + * version. If the global API is not compatible with the API package + * attempting to get it, a NOOP API implementation will be returned. + */ + exports.API_BACKWARDS_COMPATIBILITY_VERSION = 1; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js +var require_NoopLoggerProvider = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NOOP_LOGGER_PROVIDER = exports.NoopLoggerProvider = void 0; + const NoopLogger_1 = require_NoopLogger(); + var NoopLoggerProvider = class { + getLogger(_name, _version, _options) { + return new NoopLogger_1.NoopLogger(); + } + }; + exports.NoopLoggerProvider = NoopLoggerProvider; + exports.NOOP_LOGGER_PROVIDER = new NoopLoggerProvider(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js +var require_ProxyLogger = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyLogger = void 0; + const NoopLogger_1 = require_NoopLogger(); + var ProxyLogger = class { + constructor(provider, name, version, options) { + this._provider = provider; + this.name = name; + this.version = version; + this.options = options; + } + /** + * Emit a log record. This method should only be used by log appenders. + * + * @param logRecord + */ + emit(logRecord) { + this._getLogger().emit(logRecord); + } + enabled(options) { + return this._getLogger().enabled(options); + } + /** + * Try to get a logger from the proxy logger provider. + * If the proxy logger provider has no delegate, return a noop logger. + */ + _getLogger() { + if (this._delegate) return this._delegate; + const logger = this._provider._getDelegateLogger(this.name, this.version, this.options); + if (!logger) return NoopLogger_1.NOOP_LOGGER; + this._delegate = logger; + return this._delegate; + } + }; + exports.ProxyLogger = ProxyLogger; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js +var require_ProxyLoggerProvider = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyLoggerProvider = void 0; + const NoopLoggerProvider_1 = require_NoopLoggerProvider(); + const ProxyLogger_1 = require_ProxyLogger(); + var ProxyLoggerProvider = class { + getLogger(name, version, options) { + var _a; + return (_a = this._getDelegateLogger(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyLogger_1.ProxyLogger(this, name, version, options); + } + /** + * Get the delegate logger provider. + * Used by tests only. + * @internal + */ + _getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER; + } + /** + * Set the delegate logger provider + * @internal + */ + _setDelegate(delegate) { + this._delegate = delegate; + } + /** + * @internal + */ + _getDelegateLogger(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getLogger(name, version, options); + } + }; + exports.ProxyLoggerProvider = ProxyLoggerProvider; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/api/logs.js +var require_logs$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LogsAPI = void 0; + const global_utils_1 = require_global_utils(); + const NoopLoggerProvider_1 = require_NoopLoggerProvider(); + const ProxyLoggerProvider_1 = require_ProxyLoggerProvider(); + var LogsAPI = class LogsAPI { + constructor() { + this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider(); + } + static getInstance() { + if (!this._instance) this._instance = new LogsAPI(); + return this._instance; + } + setGlobalLoggerProvider(provider) { + if (global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) return this.getLoggerProvider(); + global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY] = (0, global_utils_1.makeGetter)(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, provider, NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER); + this._proxyLoggerProvider._setDelegate(provider); + return provider; + } + /** + * Returns the global logger provider. + * + * @returns LoggerProvider + */ + getLoggerProvider() { + var _a, _b; + return (_b = (_a = global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) === null || _a === void 0 ? void 0 : _a.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== void 0 ? _b : this._proxyLoggerProvider; + } + /** + * Returns a Logger, creating one if one with the given name, version, + * schemaUrl, and attributes is not already created. + * + * Getting a Logger may be expensive, especially when `attributes` are + * provided. Reuse Logger instances where possible instead of calling + * `getLogger()` on hot paths. + * + * @param name The name of the logger or instrumentation library. + * @param version The version of the logger or instrumentation library. + * @param options The options of the logger or instrumentation library. + * @returns {@link Logger} + */ + getLogger(name, version, options) { + return this.getLoggerProvider().getLogger(name, version, options); + } + /** Remove the global logger provider */ + disable() { + delete global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]; + this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider(); + } + }; + exports.LogsAPI = LogsAPI; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+api-logs@0.222.0/node_modules/@opentelemetry/api-logs/build/src/index.js +var require_src$7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.logs = exports.createNoopLogger = exports.SeverityNumber = void 0; + var LogRecord_1 = require_LogRecord(); + Object.defineProperty(exports, "SeverityNumber", { + enumerable: true, + get: function() { + return LogRecord_1.SeverityNumber; + } + }); + var NoopLogger_1 = require_NoopLogger(); + Object.defineProperty(exports, "createNoopLogger", { + enumerable: true, + get: function() { + return NoopLogger_1.createNoopLogger; + } + }); + const logs_1 = require_logs$2(); + exports.logs = logs_1.LogsAPI.getInstance(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/common-serializer.js +var require_common_serializer = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.writeResource = exports.writeInstrumentationScope = exports.writeAnyValue = exports.writeKeyValue = exports.writeAttributes = exports.writeHrTimeAsFixed64 = void 0; + /** + * Write HrTime [seconds, nanoseconds] directly as fixed64 to the serializer. + * Converts to nanoseconds and writes as 64-bit little-endian integer without allocations. + * + * HrTime represents: total_nanos = seconds * 1_000_000_000 + nanoseconds + * We need to split this into low (bits 0-31) and high (bits 32-63). + * + * @param serializer - The protobuf writer + * @param hrTime - HrTime tuple [seconds, nanoseconds] + */ + function writeHrTimeAsFixed64(serializer, hrTime) { + const seconds = hrTime[0]; + const nanos = hrTime[1]; + const nanosPerSecond = 1e9; + const secondsLower16Bits = seconds & 65535; + const secondsUpperBits = seconds / 65536 >>> 0; + const nanosFromLower16Bits = secondsLower16Bits * nanosPerSecond; + const nanosFromUpperBits = secondsUpperBits * nanosPerSecond; + const lower16ContributionLow32 = nanosFromLower16Bits >>> 0; + const lower16ContributionHigh32 = Math.floor(nanosFromLower16Bits / 4294967296); + const upperBitsContributionLow32 = (nanosFromUpperBits & 65535) * 65536 >>> 0; + const upperBitsContributionHigh32 = nanosFromUpperBits / 65536 >>> 0; + const low32WithCarry = lower16ContributionLow32 + upperBitsContributionLow32 + nanos; + const totalLow = low32WithCarry >>> 0; + const carry = Math.floor(low32WithCarry / 4294967296); + const totalHigh = lower16ContributionHigh32 + upperBitsContributionHigh32 + carry >>> 0; + serializer.writeFixed64(totalLow, totalHigh); + } + exports.writeHrTimeAsFixed64 = writeHrTimeAsFixed64; + /** + * Write Attributes directly to protobuf as repeated KeyValue + */ + function writeAttributes(writer, attributes, fieldNumber) { + for (const key in attributes) { + if (!Object.prototype.hasOwnProperty.call(attributes, key)) continue; + const value = attributes[key]; + writer.writeTag(fieldNumber, 2); + const kvStart = writer.startLengthDelimited(); + const startPos = writer.pos; + writeKeyValue(writer, key, value); + writer.finishLengthDelimited(kvStart, writer.pos - startPos); + } + } + exports.writeAttributes = writeAttributes; + /** + * Write a KeyValue pair directly to protobuf + */ + function writeKeyValue(writer, key, value) { + writer.writeTag(1, 2); + writer.writeString(key); + writer.writeTag(2, 2); + const valueStart = writer.startLengthDelimited(); + const startPos = writer.pos; + writeAnyValue(writer, value); + writer.finishLengthDelimited(valueStart, writer.pos - startPos); + } + exports.writeKeyValue = writeKeyValue; + const MIN_64_BIT_INT = -(2 ** 63); + const MAX_64_BIT_INT = 2 ** 63; + /** + * Write an AnyValue directly from raw attribute value to protobuf + */ + function writeAnyValue(writer, value) { + const t = typeof value; + if (t === "string") { + writer.writeTag(1, 2); + writer.writeString(value); + } else if (t === "boolean") { + writer.writeTag(2, 0); + writer.writeVarint(value ? 1 : 0); + } else if (t === "number") { + const numValue = value; + if (Number.isInteger(numValue) && numValue >= MIN_64_BIT_INT && numValue < MAX_64_BIT_INT) { + writer.writeTag(3, 0); + writer.writeVarint(numValue); + } else { + writer.writeTag(4, 1); + writer.writeDouble(numValue); + } + } else if (value instanceof Uint8Array) { + writer.writeTag(7, 2); + writer.writeBytes(value); + } else if (Array.isArray(value)) { + writer.writeTag(5, 2); + const arrayStart = writer.startLengthDelimited(); + const arrayStartPos = writer.pos; + for (const item of value) { + writer.writeTag(1, 2); + const itemStart = writer.startLengthDelimited(); + const itemStartPos = writer.pos; + writeAnyValue(writer, item); + writer.finishLengthDelimited(itemStart, writer.pos - itemStartPos); + } + writer.finishLengthDelimited(arrayStart, writer.pos - arrayStartPos); + } else if (t === "object" && value != null) { + writer.writeTag(6, 2); + const kvlistStart = writer.startLengthDelimited(); + const kvlistStartPos = writer.pos; + const obj = value; + for (const k in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, k)) continue; + const v = obj[k]; + writer.writeTag(1, 2); + const kvStart = writer.startLengthDelimited(); + const kvStartPos = writer.pos; + writer.writeTag(1, 2); + writer.writeString(k); + writer.writeTag(2, 2); + const valueStart = writer.startLengthDelimited(); + const valueStartPos = writer.pos; + writeAnyValue(writer, v); + writer.finishLengthDelimited(valueStart, writer.pos - valueStartPos); + writer.finishLengthDelimited(kvStart, writer.pos - kvStartPos); + } + writer.finishLengthDelimited(kvlistStart, writer.pos - kvlistStartPos); + } + } + exports.writeAnyValue = writeAnyValue; + /** + * Write an InstrumentationScope message. + * + * Proto fields (InstrumentationScope): + * 1 name string (wire type 2) + * 2 version string (wire type 2) + */ + function writeInstrumentationScope(writer, scope, fieldNumber) { + writer.writeTag(fieldNumber, 2); + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + writer.writeTag(1, 2); + writer.writeString(scope.name); + if (scope.version) { + writer.writeTag(2, 2); + writer.writeString(scope.version); + } + if (scope.attributes) writeAttributes(writer, scope.attributes, 3); + if (scope.droppedAttributesCount) { + writer.writeTag(4, 0); + writer.writeVarint(scope.droppedAttributesCount); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + exports.writeInstrumentationScope = writeInstrumentationScope; + /** + * Write a Resource message and its enclosing tag. + * + * Proto fields (Resource): + * 1 attributes repeated KeyValue (wire type 2) + * 2 dropped_attributes_count uint32 (wire type 0) + */ + function writeResource(writer, resource, fieldNumber) { + writer.writeTag(fieldNumber, 2); + const resourceStart = writer.startLengthDelimited(); + const resourceStartPos = writer.pos; + if (resource.attributes) writeAttributes(writer, resource.attributes, 1); + writer.writeTag(2, 0); + writer.writeVarint(0); + writer.finishLengthDelimited(resourceStart, writer.pos - resourceStartPos); + } + exports.writeResource = writeResource; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/protobuf-size-estimator.js +var require_protobuf_size_estimator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufSizeEstimator = void 0; + const utils_1 = require_utils$4(); + /** + * Calculate UTF-8 byte length without encoding + * @param str valid UTF-16 string + */ + function utf8ByteLength(str) { + const len = str.length; + let byteLen = 0; + for (let i = 0; i < len; i++) { + const code = str.charCodeAt(i); + if (code < 128) byteLen += 1; + else if (code < 2048) byteLen += 2; + else if (code < 55296 || code >= 57344) byteLen += 3; + else { + i++; + byteLen += 4; + } + } + return byteLen; + } + /** + * Size estimator for protobuf messages. + * Implements the same interface as ProtobufWriter but only counts bytes without allocating a buffer. + * @internal + */ + var ProtobufSizeEstimator = class { + pos = 0; + startLengthDelimited() { + return this.pos; + } + finishLengthDelimited(_, length) { + this.pos += (0, utils_1.estimateVarintSize)(length); + } + writeVarint(value) { + this.pos += (0, utils_1.estimateVarintSize)(value); + } + writeSint32(value) { + this.pos += (0, utils_1.estimateVarintSize)((value << 1 ^ value >> 31) >>> 0); + } + writeSfixed64(_value) { + this.pos += 8; + } + writeFixed32(_value) { + this.pos += 4; + } + writeFixed64(_low, _high) { + this.pos += 8; + } + writeBytes(bytes) { + this.pos += (0, utils_1.estimateVarintSize)(bytes.length); + this.pos += bytes.length; + } + writeTag(fieldNumber, wireType) { + this.writeVarint(fieldNumber << 3 | wireType); + } + writeDouble(_value) { + this.pos += 8; + } + writeString(str) { + const byteLen = utf8ByteLength(str); + this.pos += (0, utils_1.estimateVarintSize)(byteLen); + this.pos += byteLen; + } + }; + exports.ProtobufSizeEstimator = ProtobufSizeEstimator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs-serializer.js +var require_logs_serializer = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serializeLogsExportRequest = void 0; + const protobuf_writer_1 = require_protobuf_writer(); + const hex_to_binary_1 = require_hex_to_binary(); + const api_logs_1 = require_src$7(); + const common_serializer_1 = require_common_serializer(); + const protobuf_size_estimator_1 = require_protobuf_size_estimator(); + /** + * Serialize a single LogRecord directly from ReadableLogRecord + */ + function serializeLogRecord(writer, logRecord) { + const logStart = writer.startLengthDelimited(); + const logStartPos = writer.pos; + writer.writeTag(1, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, logRecord.hrTime); + if (logRecord.severityNumber !== void 0 && logRecord.severityNumber !== api_logs_1.SeverityNumber.UNSPECIFIED) { + writer.writeTag(2, 0); + writer.writeVarint(logRecord.severityNumber); + } + if (logRecord.severityText) { + writer.writeTag(3, 2); + writer.writeString(logRecord.severityText); + } + if (logRecord.body !== void 0) { + writer.writeTag(5, 2); + const bodyStart = writer.startLengthDelimited(); + const bodyStartPos = writer.pos; + (0, common_serializer_1.writeAnyValue)(writer, logRecord.body); + writer.finishLengthDelimited(bodyStart, writer.pos - bodyStartPos); + } + if (logRecord.attributes) (0, common_serializer_1.writeAttributes)(writer, logRecord.attributes, 6); + writer.writeTag(7, 0); + writer.writeVarint(logRecord.droppedAttributesCount); + if (logRecord.spanContext?.traceFlags) { + writer.writeTag(8, 5); + writer.writeFixed32(logRecord.spanContext.traceFlags); + } + if (logRecord.spanContext?.traceId) { + writer.writeTag(9, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(logRecord.spanContext.traceId)); + } + if (logRecord.spanContext?.spanId) { + writer.writeTag(10, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(logRecord.spanContext.spanId)); + } + writer.writeTag(11, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, logRecord.hrTimeObserved); + if (logRecord.eventName) { + writer.writeTag(12, 2); + writer.writeString(logRecord.eventName); + } + writer.finishLengthDelimited(logStart, writer.pos - logStartPos); + } + /** + * Serialize ScopeLogs directly from SDK types + */ + function serializeScopeLogs(writer, scope, logRecords) { + const scopeLogsStart = writer.startLengthDelimited(); + const scopeLogsStartPos = writer.pos; + (0, common_serializer_1.writeInstrumentationScope)(writer, scope, 1); + for (const logRecord of logRecords) { + writer.writeTag(2, 2); + serializeLogRecord(writer, logRecord); + } + if (scope.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(scope.schemaUrl); + } + writer.finishLengthDelimited(scopeLogsStart, writer.pos - scopeLogsStartPos); + } + /** + * Serialize ResourceLogs directly from SDK Resource type + */ + function serializeResourceLogs(writer, resource, scopeMap) { + const resourceLogsStart = writer.startLengthDelimited(); + const resourceLogsStartPos = writer.pos; + (0, common_serializer_1.writeResource)(writer, resource, 1); + for (const scopeLogs of scopeMap.values()) { + writer.writeTag(2, 2); + const scope = scopeLogs[0].instrumentationScope; + serializeScopeLogs(writer, scope, scopeLogs); + } + if (resource.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(resource.schemaUrl); + } + writer.finishLengthDelimited(resourceLogsStart, writer.pos - resourceLogsStartPos); + } + /** + * Group log records by resource and instrumentation scope + */ + function createResourceMap(logRecords) { + const resourceMap = /* @__PURE__ */ new Map(); + for (const record of logRecords) { + const resource = record.resource; + const scope = record.instrumentationScope; + let ismMap = resourceMap.get(resource); + if (!ismMap) { + ismMap = /* @__PURE__ */ new Map(); + resourceMap.set(resource, ismMap); + } + let records = ismMap.get(scope); + if (!records) { + records = []; + ismMap.set(scope, records); + } + records.push(record); + } + return resourceMap; + } + /** + * Serialize ExportLogsServiceRequest directly from ReadableLogRecord[] + */ + function serializeLogsExportRequest(logRecords) { + const resourceMap = createResourceMap(logRecords); + const estimator = new protobuf_size_estimator_1.ProtobufSizeEstimator(); + for (const [resource, scopeMap] of resourceMap) { + estimator.writeTag(1, 2); + serializeResourceLogs(estimator, resource, scopeMap); + } + const writer = new protobuf_writer_1.ProtobufWriter(estimator.pos); + for (const [resource, scopeMap] of resourceMap) { + writer.writeTag(1, 2); + serializeResourceLogs(writer, resource, scopeMap); + } + return writer.finish(); + } + exports.serializeLogsExportRequest = serializeLogsExportRequest; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/protobuf-reader.js +var require_protobuf_reader = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufReader = void 0; + /** + * Minimal binary protobuf reader. + * Only implements the wire-types that we currently need; this is not intended + * to be a general-purpose protobuf reader. + * + * Since the values we parse are generally small and not very nested, it's public + * interface does not enforce the same low-allocation philosophy that ProtobufWriter does. + * If this is needed in the future, we should refactor this to fit the use-case. + */ + var ProtobufReader = class { + pos = 0; + _buf; + _textDecoder; + constructor(buf) { + this._buf = buf; + this._textDecoder = new TextDecoder(); + } + isAtEnd() { + return this.pos >= this._buf.length; + } + /** Read a varint and decode it as a tag, returning field number and wire type. */ + readTag() { + const raw = this.readVarint(); + return { + fieldNumber: raw >>> 3, + wireType: raw & 7 + }; + } + /** + * Read a base-128 varint. + * Returns a JS `number`; precision above 2^53 is silently lost. + * Throws if the buffer is truncated mid-varint. + */ + readVarint() { + let result = 0; + let shift = 0; + let terminated = false; + while (this.pos < this._buf.length) { + const b = this._buf[this.pos++]; + result += (b & 127) * Math.pow(2, shift); + shift += 7; + if ((b & 128) === 0) { + terminated = true; + break; + } + } + if (!terminated) throw new Error("Truncated buffer: unexpected end of data while reading varint"); + return result; + } + /** Read a length-delimited byte sequence (bytes field or embedded message). */ + readBytes() { + const len = this.readVarint(); + if (this.pos + len > this._buf.length) throw new Error(`Truncated buffer: expected ${len} bytes at position ${this.pos}, but only ${this._buf.length - this.pos} available`); + const slice = this._buf.subarray(this.pos, this.pos + len); + this.pos += len; + return slice; + } + /** Read a length-delimited UTF-8 string. */ + readString() { + return this._textDecoder.decode(this.readBytes()); + } + /** + * Skip an unknown field. + * Handles wire types 0 (varint), 1 (64-bit), 2 (length-delimited), + * and 5 (32-bit). + * + * Wire types 3 and 4 (start-group / end-group) are deprecated in proto3 + * and are not used by any OpenTelemetry proto definition. Encountering + * them is treated as an error. + */ + skip(wireType) { + switch (wireType) { + case 0: + this.readVarint(); + break; + case 1: + this.pos += 8; + break; + case 2: + this.readBytes(); + break; + case 5: + this.pos += 4; + break; + default: throw new Error(`Unknown wire type ${wireType}, cannot safely skip`); + } + } + }; + exports.ProtobufReader = ProtobufReader; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/response-deserializer.js +var require_response_deserializer$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deserializeExportLogsServiceResponse = void 0; + const protobuf_reader_1 = require_protobuf_reader(); + /** + * Parse an ExportLogsPartialSuccess embedded message from raw bytes. + * + * Field map (opentelemetry/proto/collector/logs/v1/logs_service.proto): + * 1 rejected_log_records int64 (varint) + * 2 error_message string (length-delimited) + */ + function deserializePartialSuccess(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 0) result.rejectedLogRecords = reader.readVarint(); + else reader.skip(wireType); + break; + case 2: + if (wireType === 2) result.errorMessage = reader.readString(); + else reader.skip(wireType); + break; + default: reader.skip(wireType); + } + } + return result; + } + /** + * Parse an ExportLogsServiceResponse protobuf message from raw bytes. + * + * Field map (opentelemetry/proto/collector/logs/v1/logs_service.proto): + * 1 partial_success ExportLogsPartialSuccess (length-delimited) + */ + function deserializeExportLogsServiceResponse(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 2) result.partialSuccess = deserializePartialSuccess(reader.readBytes()); + else reader.skip(wireType); + break; + default: reader.skip(wireType); + } + } + return result; + } + exports.deserializeExportLogsServiceResponse = deserializeExportLogsServiceResponse; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js +var require_logs$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufLogsSerializer = void 0; + const logs_serializer_1 = require_logs_serializer(); + const response_deserializer_1 = require_response_deserializer$2(); + /** + * @experimental this serializer may receive breaking changes in minor versions, pin this package's version when using this constant + */ + exports.ProtobufLogsSerializer = { + serializeRequest: (arg) => { + return (0, logs_serializer_1.serializeLogsExportRequest)(arg); + }, + deserializeResponse: (arg) => { + return (0, response_deserializer_1.deserializeExportLogsServiceResponse)(arg); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js +var require_protobuf$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufLogsSerializer = void 0; + var logs_1 = require_logs$1(); + Object.defineProperty(exports, "ProtobufLogsSerializer", { + enumerable: true, + get: function() { + return logs_1.ProtobufLogsSerializer; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js +var require_AggregationTemporality = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AggregationTemporality = void 0; + /** + * AggregationTemporality indicates the way additive quantities are expressed. + */ + var AggregationTemporality; + (function(AggregationTemporality) { + AggregationTemporality[AggregationTemporality["DELTA"] = 0] = "DELTA"; + AggregationTemporality[AggregationTemporality["CUMULATIVE"] = 1] = "CUMULATIVE"; + })(AggregationTemporality || (exports.AggregationTemporality = AggregationTemporality = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js +var require_MetricData = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DataPointType = exports.InstrumentType = void 0; + /** + * Supported types of metric instruments. + */ + var InstrumentType; + (function(InstrumentType) { + InstrumentType["COUNTER"] = "COUNTER"; + InstrumentType["GAUGE"] = "GAUGE"; + InstrumentType["HISTOGRAM"] = "HISTOGRAM"; + InstrumentType["UP_DOWN_COUNTER"] = "UP_DOWN_COUNTER"; + InstrumentType["OBSERVABLE_COUNTER"] = "OBSERVABLE_COUNTER"; + InstrumentType["OBSERVABLE_GAUGE"] = "OBSERVABLE_GAUGE"; + InstrumentType["OBSERVABLE_UP_DOWN_COUNTER"] = "OBSERVABLE_UP_DOWN_COUNTER"; + })(InstrumentType || (exports.InstrumentType = InstrumentType = {})); + /** + * The aggregated point data type. + */ + var DataPointType; + (function(DataPointType) { + /** + * A histogram data point contains a histogram statistics of collected + * values with a list of explicit bucket boundaries and statistics such + * as min, max, count, and sum of all collected values. + */ + DataPointType[DataPointType["HISTOGRAM"] = 0] = "HISTOGRAM"; + /** + * An exponential histogram data point contains a histogram statistics of + * collected values where bucket boundaries are automatically calculated + * using an exponential function, and statistics such as min, max, count, + * and sum of all collected values. + */ + DataPointType[DataPointType["EXPONENTIAL_HISTOGRAM"] = 1] = "EXPONENTIAL_HISTOGRAM"; + /** + * A gauge metric data point has only a single numeric value. + */ + DataPointType[DataPointType["GAUGE"] = 2] = "GAUGE"; + /** + * A sum metric data point has a single numeric value and a + * monotonicity-indicator. + */ + DataPointType[DataPointType["SUM"] = 3] = "SUM"; + })(DataPointType || (exports.DataPointType = DataPointType = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js +var require_utils$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.equalsCaseInsensitive = exports.binarySearchUB = exports.setEquals = exports.callWithTimeout = exports.TimeoutError = exports.instrumentationScopeId = exports.hashAttributes = void 0; + /** + * Converting the unordered attributes into unique identifier string. + * @param attributes user provided unordered Attributes. + */ + function hashAttributes(attributes) { + let keys = Object.keys(attributes); + if (keys.length === 0) return ""; + keys = keys.sort(); + return JSON.stringify(keys.map((key) => [key, attributes[key]])); + } + exports.hashAttributes = hashAttributes; + /** + * Converting the instrumentation scope object to a unique identifier string. + * @param instrumentationScope + */ + function instrumentationScopeId(instrumentationScope) { + return `${instrumentationScope.name}:${instrumentationScope.version ?? ""}:${instrumentationScope.schemaUrl ?? ""}`; + } + exports.instrumentationScopeId = instrumentationScopeId; + /** + * Error that is thrown on timeouts. + */ + var TimeoutError = class TimeoutError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, TimeoutError.prototype); + } + }; + exports.TimeoutError = TimeoutError; + /** + * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise + * rejects, and resolves if the specified promise resolves. + * + *

NOTE: this operation will continue even after it throws a {@link TimeoutError}. + * + * @param promise promise to use with timeout. + * @param timeout the timeout in milliseconds until the returned promise is rejected. + */ + function callWithTimeout(promise, timeout) { + let timeoutHandle; + const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { + timeoutHandle = setTimeout(function timeoutHandler() { + reject(new TimeoutError("Operation timed out.")); + }, timeout); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }, (reason) => { + clearTimeout(timeoutHandle); + throw reason; + }); + } + exports.callWithTimeout = callWithTimeout; + function setEquals(lhs, rhs) { + if (lhs.size !== rhs.size) return false; + for (const item of lhs) if (!rhs.has(item)) return false; + return true; + } + exports.setEquals = setEquals; + /** + * Binary search the sorted array to the find upper bound for the value. + * @param arr + * @param value + * @returns + */ + function binarySearchUB(arr, value) { + let lo = 0; + let hi = arr.length - 1; + let ret = arr.length; + while (hi >= lo) { + const mid = lo + Math.trunc((hi - lo) / 2); + if (arr[mid] < value) lo = mid + 1; + else { + ret = mid; + hi = mid - 1; + } + } + return ret; + } + exports.binarySearchUB = binarySearchUB; + function equalsCaseInsensitive(lhs, rhs) { + return lhs.toLowerCase() === rhs.toLowerCase(); + } + exports.equalsCaseInsensitive = equalsCaseInsensitive; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js +var require_types$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AggregatorKind = void 0; + /** The kind of aggregator. */ + var AggregatorKind; + (function(AggregatorKind) { + AggregatorKind[AggregatorKind["DROP"] = 0] = "DROP"; + AggregatorKind[AggregatorKind["SUM"] = 1] = "SUM"; + AggregatorKind[AggregatorKind["LAST_VALUE"] = 2] = "LAST_VALUE"; + AggregatorKind[AggregatorKind["HISTOGRAM"] = 3] = "HISTOGRAM"; + AggregatorKind[AggregatorKind["EXPONENTIAL_HISTOGRAM"] = 4] = "EXPONENTIAL_HISTOGRAM"; + })(AggregatorKind || (exports.AggregatorKind = AggregatorKind = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js +var require_Drop = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DropAggregator = void 0; + const types_1 = require_types$1(); + /** Basic aggregator for None which keeps no recorded value. */ + var DropAggregator = class { + kind = types_1.AggregatorKind.DROP; + createAccumulation() {} + merge(_previous, _delta) {} + diff(_previous, _current) {} + toMetricData(_descriptor, _aggregationTemporality, _accumulationByAttributes, _endTime) {} + }; + exports.DropAggregator = DropAggregator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js +var require_Histogram = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HistogramAggregator = exports.HistogramAccumulation = void 0; + const types_1 = require_types$1(); + const MetricData_1 = require_MetricData(); + const utils_1 = require_utils$3(); + function createNewEmptyCheckpoint(boundaries) { + const counts = boundaries.map(() => 0); + counts.push(0); + return { + buckets: { + boundaries, + counts + }, + sum: 0, + count: 0, + hasMinMax: false, + min: Infinity, + max: -Infinity + }; + } + var HistogramAccumulation = class { + startTime; + _boundaries; + _recordMinMax; + _current; + constructor(startTime, boundaries, recordMinMax = true, current = createNewEmptyCheckpoint(boundaries)) { + this.startTime = startTime; + this._boundaries = boundaries; + this._recordMinMax = recordMinMax; + this._current = current; + } + record(value) { + if (Number.isNaN(value)) return; + this._current.count += 1; + this._current.sum += value; + if (this._recordMinMax) { + this._current.min = Math.min(value, this._current.min); + this._current.max = Math.max(value, this._current.max); + this._current.hasMinMax = true; + } + const idx = (0, utils_1.binarySearchUB)(this._boundaries, value); + this._current.buckets.counts[idx] += 1; + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } + }; + exports.HistogramAccumulation = HistogramAccumulation; + /** + * Basic aggregator which observes events and counts them in pre-defined buckets + * and provides the total sum and count of all observations. + */ + var HistogramAggregator = class { + kind = types_1.AggregatorKind.HISTOGRAM; + _boundaries; + _recordMinMax; + /** + * @param _boundaries sorted upper bounds of recorded values. + * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded. + */ + constructor(boundaries, recordMinMax) { + this._boundaries = boundaries; + this._recordMinMax = recordMinMax; + } + createAccumulation(startTime) { + return new HistogramAccumulation(startTime, this._boundaries, this._recordMinMax); + } + /** + * Return the result of the merge of two histogram accumulations. As long as one Aggregator + * instance produces all Accumulations with constant boundaries we don't need to worry about + * merging accumulations with different boundaries. + */ + merge(previous, delta) { + const previousValue = previous.toPointValue(); + const deltaValue = delta.toPointValue(); + const previousCounts = previousValue.buckets.counts; + const deltaCounts = deltaValue.buckets.counts; + const mergedCounts = new Array(previousCounts.length); + for (let idx = 0; idx < previousCounts.length; idx++) mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx]; + let min = Infinity; + let max = -Infinity; + if (this._recordMinMax) { + if (previousValue.hasMinMax && deltaValue.hasMinMax) { + min = Math.min(previousValue.min, deltaValue.min); + max = Math.max(previousValue.max, deltaValue.max); + } else if (previousValue.hasMinMax) { + min = previousValue.min; + max = previousValue.max; + } else if (deltaValue.hasMinMax) { + min = deltaValue.min; + max = deltaValue.max; + } + } + return new HistogramAccumulation(previous.startTime, previousValue.buckets.boundaries, this._recordMinMax, { + buckets: { + boundaries: previousValue.buckets.boundaries, + counts: mergedCounts + }, + count: previousValue.count + deltaValue.count, + sum: previousValue.sum + deltaValue.sum, + hasMinMax: this._recordMinMax && (previousValue.hasMinMax || deltaValue.hasMinMax), + min, + max + }); + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + */ + diff(previous, current) { + const previousValue = previous.toPointValue(); + const currentValue = current.toPointValue(); + const previousCounts = previousValue.buckets.counts; + const currentCounts = currentValue.buckets.counts; + const diffedCounts = new Array(previousCounts.length); + for (let idx = 0; idx < previousCounts.length; idx++) diffedCounts[idx] = currentCounts[idx] - previousCounts[idx]; + return new HistogramAccumulation(current.startTime, previousValue.buckets.boundaries, this._recordMinMax, { + buckets: { + boundaries: previousValue.buckets.boundaries, + counts: diffedCounts + }, + count: currentValue.count - previousValue.count, + sum: currentValue.sum - previousValue.sum, + hasMinMax: false, + min: Infinity, + max: -Infinity + }); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.HISTOGRAM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + const pointValue = accumulation.toPointValue(); + const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: { + min: pointValue.hasMinMax ? pointValue.min : void 0, + max: pointValue.hasMinMax ? pointValue.max : void 0, + sum: !allowsNegativeValues ? pointValue.sum : void 0, + buckets: pointValue.buckets, + count: pointValue.count + } + }; + }) + }; + } + }; + exports.HistogramAggregator = HistogramAggregator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js +var require_Buckets = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Buckets = void 0; + var Buckets = class Buckets { + backing; + indexBase; + indexStart; + indexEnd; + /** + * The term index refers to the number of the exponential histogram bucket + * used to determine its boundaries. The lower boundary of a bucket is + * determined by base ** index and the upper boundary of a bucket is + * determined by base ** (index + 1). index values are signed to account + * for values less than or equal to 1. + * + * indexBase is the index of the 0th position in the + * backing array, i.e., backing[0] is the count + * in the bucket with index `indexBase`. + * + * indexStart is the smallest index value represented + * in the backing array. + * + * indexEnd is the largest index value represented in + * the backing array. + */ + constructor(backing = new BucketsBacking(), indexBase = 0, indexStart = 0, indexEnd = 0) { + this.backing = backing; + this.indexBase = indexBase; + this.indexStart = indexStart; + this.indexEnd = indexEnd; + } + /** + * Offset is the bucket index of the smallest entry in the counts array + * @returns {number} + */ + get offset() { + return this.indexStart; + } + /** + * Buckets is a view into the backing array. + * @returns {number} + */ + get length() { + if (this.backing.length === 0) return 0; + if (this.indexEnd === this.indexStart && this.at(0) === 0) return 0; + return this.indexEnd - this.indexStart + 1; + } + /** + * An array of counts, where count[i] carries the count + * of the bucket at index (offset+i). count[i] is the count of + * values greater than base^(offset+i) and less than or equal to + * base^(offset+i+1). + * @returns {number} The logical counts based on the backing array + */ + counts() { + return Array.from({ length: this.length }, (_, i) => this.at(i)); + } + /** + * At returns the count of the bucket at a position in the logical + * array of counts. + * @param position + * @returns {number} + */ + at(position) { + const bias = this.indexBase - this.indexStart; + if (position < bias) position += this.backing.length; + position -= bias; + return this.backing.countAt(position); + } + /** + * incrementBucket increments the backing array index by `increment` + * @param bucketIndex + * @param increment + */ + incrementBucket(bucketIndex, increment) { + this.backing.increment(bucketIndex, increment); + } + /** + * decrementBucket decrements the backing array index by `decrement` + * if decrement is greater than the current value, it's set to 0. + * @param bucketIndex + * @param decrement + */ + decrementBucket(bucketIndex, decrement) { + this.backing.decrement(bucketIndex, decrement); + } + /** + * trim removes leading and / or trailing zero buckets (which can occur + * after diffing two histos) and rotates the backing array so that the + * smallest non-zero index is in the 0th position of the backing array + */ + trim() { + for (let i = 0; i < this.length; i++) if (this.at(i) !== 0) { + this.indexStart += i; + break; + } else if (i === this.length - 1) { + this.indexStart = this.indexEnd = this.indexBase = 0; + return; + } + for (let i = this.length - 1; i >= 0; i--) if (this.at(i) !== 0) { + this.indexEnd -= this.length - i - 1; + break; + } + this._rotate(); + } + /** + * downscale first rotates, then collapses 2**`by`-to-1 buckets. + * @param by + */ + downscale(by) { + this._rotate(); + const size = 1 + this.indexEnd - this.indexStart; + const each = 1 << by; + let inpos = 0; + let outpos = 0; + for (let pos = this.indexStart; pos <= this.indexEnd;) { + let mod = pos % each; + if (mod < 0) mod += each; + for (let i = mod; i < each && inpos < size; i++) { + this._relocateBucket(outpos, inpos); + inpos++; + pos++; + } + outpos++; + } + this.indexStart >>= by; + this.indexEnd >>= by; + this.indexBase = this.indexStart; + } + /** + * Clone returns a deep copy of Buckets + * @returns {Buckets} + */ + clone() { + return new Buckets(this.backing.clone(), this.indexBase, this.indexStart, this.indexEnd); + } + /** + * _rotate shifts the backing array contents so that indexStart == + * indexBase to simplify the downscale logic. + */ + _rotate() { + const bias = this.indexBase - this.indexStart; + if (bias === 0) return; + else if (bias > 0) { + this.backing.reverse(0, this.backing.length); + this.backing.reverse(0, bias); + this.backing.reverse(bias, this.backing.length); + } else { + this.backing.reverse(0, this.backing.length); + this.backing.reverse(0, this.backing.length + bias); + } + this.indexBase = this.indexStart; + } + /** + * _relocateBucket adds the count in counts[src] to counts[dest] and + * resets count[src] to zero. + */ + _relocateBucket(dest, src) { + if (dest === src) return; + this.incrementBucket(dest, this.backing.emptyBucket(src)); + } + }; + exports.Buckets = Buckets; + /** + * BucketsBacking holds the raw buckets and some utility methods to + * manage them. + */ + var BucketsBacking = class BucketsBacking { + _counts; + constructor(counts = [0]) { + this._counts = counts; + } + /** + * length returns the physical size of the backing array, which + * is >= buckets.length() + */ + get length() { + return this._counts.length; + } + /** + * countAt returns the count in a specific bucket + */ + countAt(pos) { + return this._counts[pos]; + } + /** + * growTo grows a backing array and copies old entries + * into their correct new positions. + */ + growTo(newSize, oldPositiveLimit, newPositiveLimit) { + const tmp = new Array(newSize).fill(0); + tmp.splice(newPositiveLimit, this._counts.length - oldPositiveLimit, ...this._counts.slice(oldPositiveLimit)); + tmp.splice(0, oldPositiveLimit, ...this._counts.slice(0, oldPositiveLimit)); + this._counts = tmp; + } + /** + * reverse the items in the backing array in the range [from, limit). + */ + reverse(from, limit) { + const num = Math.floor((from + limit) / 2) - from; + for (let i = 0; i < num; i++) { + const tmp = this._counts[from + i]; + this._counts[from + i] = this._counts[limit - i - 1]; + this._counts[limit - i - 1] = tmp; + } + } + /** + * emptyBucket empties the count from a bucket, for + * moving into another. + */ + emptyBucket(src) { + const tmp = this._counts[src]; + this._counts[src] = 0; + return tmp; + } + /** + * increments a bucket by `increment` + */ + increment(bucketIndex, increment) { + this._counts[bucketIndex] += increment; + } + /** + * decrements a bucket by `decrement` + */ + decrement(bucketIndex, decrement) { + if (this._counts[bucketIndex] >= decrement) this._counts[bucketIndex] -= decrement; + else this._counts[bucketIndex] = 0; + } + /** + * clone returns a deep copy of BucketsBacking + */ + clone() { + return new BucketsBacking([...this._counts]); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js +var require_ieee754 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPowerOfTwo = exports.getNormalBase2 = exports.MIN_VALUE = exports.MAX_NORMAL_EXPONENT = exports.MIN_NORMAL_EXPONENT = void 0; + /** + * The functions and constants in this file allow us to interact + * with the internal representation of an IEEE 64-bit floating point + * number. We need to work with all 64-bits, thus, care needs to be + * taken when working with Javascript's bitwise operators (<<, >>, &, + * |, etc) as they truncate operands to 32-bits. In order to work around + * this we work with the 64-bits as two 32-bit halves and perform bitwise + * operations on each half independently. + */ + /** + * EXPONENT_MASK is set to 1 for the hi 32-bits of an IEEE 754 + * floating point exponent: 0x7ff00000. + */ + const EXPONENT_MASK = 2146435072; + /** + * SIGNIFICAND_MASK is the mask for the significand portion of the hi 32-bits + * of an IEEE 754 double-precision floating-point value: 0xfffff + */ + const SIGNIFICAND_MASK = 1048575; + /** + * EXPONENT_BIAS is the exponent bias specified for encoding + * the IEEE 754 double-precision floating point exponent: 1023 + */ + const EXPONENT_BIAS = 1023; + /** + * MIN_NORMAL_EXPONENT is the minimum exponent of a normalized + * floating point: -1022. + */ + exports.MIN_NORMAL_EXPONENT = -1022; + /** + * MAX_NORMAL_EXPONENT is the maximum exponent of a normalized + * floating point: 1023. + */ + exports.MAX_NORMAL_EXPONENT = EXPONENT_BIAS; + /** + * MIN_VALUE is the smallest normal number + */ + exports.MIN_VALUE = Math.pow(2, -1022); + const dv = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); + /** + * floatBits writes value into the shared buffer and returns its two 32-bit + * halves. + * @param {number} value - the floating point number to read + * @returns {{hi: number, lo: number}} the high and low 32-bit halves + */ + function floatBits(value) { + dv.setFloat64(0, value); + return { + hi: dv.getUint32(0), + lo: dv.getUint32(4) + }; + } + /** + * getNormalBase2 extracts the normalized base-2 fractional exponent. + * This returns k for the equation f x 2**k where f is + * in the range [1, 2). Note that this function is not called for + * subnormal numbers. + * @param {number} value - the value to determine normalized base-2 fractional + * exponent for + * @returns {number} the normalized base-2 exponent + */ + function getNormalBase2(value) { + const { hi } = floatBits(value); + return ((hi & EXPONENT_MASK) >> 20) - EXPONENT_BIAS; + } + exports.getNormalBase2 = getNormalBase2; + /** + * isPowerOfTwo reports whether value is an exact power of two, e.g. its 52-bit + * significand is all zeros. Only valid for positive, finite values. + * @param {number} value - the floating point number to test + * @returns {boolean} true if value is an exact power of two + */ + function isPowerOfTwo(value) { + const { hi, lo } = floatBits(value); + return (hi & SIGNIFICAND_MASK) === 0 && lo === 0; + } + exports.isPowerOfTwo = isPowerOfTwo; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.nextGreaterSquare = exports.ldexp = void 0; + /** + * Note: other languages provide this as a built in function. This is + * a naive, but functionally correct implementation. This is used sparingly, + * when creating a new mapping in a running application. + * + * ldexp returns frac × 2**exp. With the following special cases: + * ldexp(±0, exp) = ±0 + * ldexp(±Inf, exp) = ±Inf + * ldexp(NaN, exp) = NaN + * @param frac + * @param exp + * @returns {number} + */ + function ldexp(frac, exp) { + if (frac === 0 || frac === Number.POSITIVE_INFINITY || frac === Number.NEGATIVE_INFINITY || Number.isNaN(frac)) return frac; + return frac * Math.pow(2, exp); + } + exports.ldexp = ldexp; + /** + * Computes the next power of two that is greater than or equal to v. + * This implementation more efficient than, but functionally equivalent + * to Math.pow(2, Math.ceil(Math.log(x)/Math.log(2))). + * @param v + * @returns {number} + */ + function nextGreaterSquare(v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + exports.nextGreaterSquare = nextGreaterSquare; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MappingError = void 0; + var MappingError = class extends Error {}; + exports.MappingError = MappingError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js +var require_ExponentMapping = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExponentMapping = void 0; + const ieee754 = require_ieee754(); + const util = require_util(); + const types_1 = require_types(); + /** + * ExponentMapping implements exponential mapping functions for + * scales <=0. For scales > 0 LogarithmMapping should be used. + */ + var ExponentMapping = class { + _shift; + constructor(scale) { + this._shift = -scale; + } + /** + * Maps positive floating point values to indexes corresponding to scale + * @param value + * @returns {number} index for provided value at the current scale + */ + mapToIndex(value) { + if (value < ieee754.MIN_VALUE) return this._minNormalLowerBoundaryIndex(); + return ieee754.getNormalBase2(value) + (ieee754.isPowerOfTwo(value) ? -1 : 0) >> this._shift; + } + /** + * Returns the lower bucket boundary for the given index for scale + * + * @param index + * @returns {number} + */ + lowerBoundary(index) { + const minIndex = this._minNormalLowerBoundaryIndex(); + if (index < minIndex) throw new types_1.MappingError(`underflow: ${index} is < minimum lower boundary: ${minIndex}`); + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index > maxIndex) throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); + return util.ldexp(1, index << this._shift); + } + /** + * The scale used by this mapping + * @returns {number} + */ + get scale() { + if (this._shift === 0) return 0; + return -this._shift; + } + _minNormalLowerBoundaryIndex() { + let index = ieee754.MIN_NORMAL_EXPONENT >> this._shift; + if (this._shift < 2) index--; + return index; + } + _maxNormalLowerBoundaryIndex() { + return ieee754.MAX_NORMAL_EXPONENT >> this._shift; + } + }; + exports.ExponentMapping = ExponentMapping; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js +var require_LogarithmMapping = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LogarithmMapping = void 0; + const ieee754 = require_ieee754(); + const util = require_util(); + const types_1 = require_types(); + /** + * LogarithmMapping implements exponential mapping functions for scale > 0. + * For scales <= 0 the exponent mapping should be used. + */ + var LogarithmMapping = class { + _scale; + _scaleFactor; + _inverseFactor; + constructor(scale) { + this._scale = scale; + this._scaleFactor = util.ldexp(Math.LOG2E, scale); + this._inverseFactor = util.ldexp(Math.LN2, -scale); + } + /** + * Maps positive floating point values to indexes corresponding to scale + * @param value + * @returns {number} index for provided value at the current scale + */ + mapToIndex(value) { + if (value <= ieee754.MIN_VALUE) return this._minNormalLowerBoundaryIndex() - 1; + if (ieee754.isPowerOfTwo(value)) return (ieee754.getNormalBase2(value) << this._scale) - 1; + const index = Math.floor(Math.log(value) * this._scaleFactor); + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index >= maxIndex) return maxIndex; + return index; + } + /** + * Returns the lower bucket boundary for the given index for scale + * + * @param index + * @returns {number} + */ + lowerBoundary(index) { + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index >= maxIndex) { + if (index === maxIndex) return 2 * Math.exp((index - (1 << this._scale)) / this._scaleFactor); + throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); + } + const minIndex = this._minNormalLowerBoundaryIndex(); + if (index <= minIndex) { + if (index === minIndex) return ieee754.MIN_VALUE; + else if (index === minIndex - 1) return Math.exp((index + (1 << this._scale)) / this._scaleFactor) / 2; + throw new types_1.MappingError(`overflow: ${index} is < minimum lower boundary: ${minIndex}`); + } + return Math.exp(index * this._inverseFactor); + } + /** + * The scale used by this mapping + * @returns {number} + */ + get scale() { + return this._scale; + } + _minNormalLowerBoundaryIndex() { + return ieee754.MIN_NORMAL_EXPONENT << this._scale; + } + _maxNormalLowerBoundaryIndex() { + return (ieee754.MAX_NORMAL_EXPONENT + 1 << this._scale) - 1; + } + }; + exports.LogarithmMapping = LogarithmMapping; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js +var require_getMapping = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMapping = void 0; + const ExponentMapping_1 = require_ExponentMapping(); + const LogarithmMapping_1 = require_LogarithmMapping(); + const types_1 = require_types(); + const MIN_SCALE = -10; + const MAX_SCALE = 20; + const PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => { + if (i > 10) return new LogarithmMapping_1.LogarithmMapping(i - 10); + return new ExponentMapping_1.ExponentMapping(i - 10); + }); + /** + * getMapping returns an appropriate mapping for the given scale. For scales -10 + * to 0 the underlying type will be ExponentMapping. For scales 1 to 20 the + * underlying type will be LogarithmMapping. + * @param scale a number in the range [-10, 20] + * @returns {Mapping} + */ + function getMapping(scale) { + if (scale > MAX_SCALE || scale < MIN_SCALE) throw new types_1.MappingError(`expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE}, got: ${scale}`); + return PREBUILT_MAPPINGS[scale + 10]; + } + exports.getMapping = getMapping; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js +var require_ExponentialHistogram = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = void 0; + const types_1 = require_types$1(); + const MetricData_1 = require_MetricData(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const Buckets_1 = require_Buckets(); + const getMapping_1 = require_getMapping(); + const util_1 = require_util(); + var HighLow = class HighLow { + static combine(h1, h2) { + return new HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high)); + } + low; + high; + constructor(low, high) { + this.low = low; + this.high = high; + } + }; + const MAX_SCALE = 20; + const DEFAULT_MAX_SIZE = 160; + const MIN_MAX_SIZE = 2; + var ExponentialHistogramAccumulation = class ExponentialHistogramAccumulation { + startTime; + _maxSize; + _recordMinMax; + _sum; + _count; + _zeroCount; + _min; + _max; + _positive; + _negative; + _mapping; + constructor(startTime, maxSize = DEFAULT_MAX_SIZE, recordMinMax = true, sum = 0, count = 0, zeroCount = 0, min = Number.POSITIVE_INFINITY, max = Number.NEGATIVE_INFINITY, positive = new Buckets_1.Buckets(), negative = new Buckets_1.Buckets(), mapping = (0, getMapping_1.getMapping)(MAX_SCALE)) { + this.startTime = startTime; + this._maxSize = maxSize; + this._recordMinMax = recordMinMax; + this._sum = sum; + this._count = count; + this._zeroCount = zeroCount; + this._min = min; + this._max = max; + this._positive = positive; + this._negative = negative; + this._mapping = mapping; + if (this._maxSize < MIN_MAX_SIZE) { + api_1.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \ + changing to the minimum size of: ${MIN_MAX_SIZE}`); + this._maxSize = MIN_MAX_SIZE; + } + } + /** + * record updates a histogram with a single count + * @param {Number} value + */ + record(value) { + this.updateByIncrement(value, 1); + } + /** + * Sets the start time for this accumulation + * @param {HrTime} startTime + */ + setStartTime(startTime) { + this.startTime = startTime; + } + /** + * Returns the datapoint representation of this accumulation + * @param {HrTime} startTime + */ + toPointValue() { + return { + hasMinMax: this._recordMinMax, + min: this.min, + max: this.max, + sum: this.sum, + positive: { + offset: this.positive.offset, + bucketCounts: this.positive.counts() + }, + negative: { + offset: this.negative.offset, + bucketCounts: this.negative.counts() + }, + count: this.count, + scale: this.scale, + zeroCount: this.zeroCount + }; + } + /** + * @returns {Number} The sum of values recorded by this accumulation + */ + get sum() { + return this._sum; + } + /** + * @returns {Number} The minimum value recorded by this accumulation + */ + get min() { + return this._min; + } + /** + * @returns {Number} The maximum value recorded by this accumulation + */ + get max() { + return this._max; + } + /** + * @returns {Number} The count of values recorded by this accumulation + */ + get count() { + return this._count; + } + /** + * @returns {Number} The number of 0 values recorded by this accumulation + */ + get zeroCount() { + return this._zeroCount; + } + /** + * @returns {Number} The scale used by this accumulation + */ + get scale() { + if (this._count === this._zeroCount) return 0; + return this._mapping.scale; + } + /** + * positive holds the positive values + * @returns {Buckets} + */ + get positive() { + return this._positive; + } + /** + * negative holds the negative values by their absolute value + * @returns {Buckets} + */ + get negative() { + return this._negative; + } + /** + * updateByIncr supports updating a histogram with a non-negative + * increment. + * @param value + * @param increment + */ + updateByIncrement(value, increment) { + if (!Number.isFinite(value)) return; + if (value > this._max) this._max = value; + if (value < this._min) this._min = value; + this._count += increment; + if (value === 0) { + this._zeroCount += increment; + return; + } + this._sum += value * increment; + if (value > 0) this._updateBuckets(this._positive, value, increment); + else this._updateBuckets(this._negative, -value, increment); + } + /** + * merge combines data from previous value into self + * @param {ExponentialHistogramAccumulation} previous + */ + merge(previous) { + if (this._count === 0) { + this._min = previous.min; + this._max = previous.max; + } else if (previous.count !== 0) { + if (previous.min < this.min) this._min = previous.min; + if (previous.max > this.max) this._max = previous.max; + } + this.startTime = previous.startTime; + this._sum += previous.sum; + this._count += previous.count; + this._zeroCount += previous.zeroCount; + const minScale = this._minScale(previous); + this._downscale(this.scale - minScale); + this._mergeBuckets(this.positive, previous, previous.positive, minScale); + this._mergeBuckets(this.negative, previous, previous.negative, minScale); + } + /** + * diff subtracts other from self + * @param {ExponentialHistogramAccumulation} other + */ + diff(other) { + this._min = Infinity; + this._max = -Infinity; + this._sum -= other.sum; + this._count -= other.count; + this._zeroCount -= other.zeroCount; + const minScale = this._minScale(other); + this._downscale(this.scale - minScale); + this._diffBuckets(this.positive, other, other.positive, minScale); + this._diffBuckets(this.negative, other, other.negative, minScale); + } + /** + * clone returns a deep copy of self + * @returns {ExponentialHistogramAccumulation} + */ + clone() { + return new ExponentialHistogramAccumulation(this.startTime, this._maxSize, this._recordMinMax, this._sum, this._count, this._zeroCount, this._min, this._max, this.positive.clone(), this.negative.clone(), this._mapping); + } + /** + * _updateBuckets maps the incoming value to a bucket index for the current + * scale. If the bucket index is outside of the range of the backing array, + * it will rescale the backing array and update the mapping for the new scale. + */ + _updateBuckets(buckets, value, increment) { + let index = this._mapping.mapToIndex(value); + let rescalingNeeded = false; + let high = 0; + let low = 0; + if (buckets.length === 0) { + buckets.indexStart = index; + buckets.indexEnd = buckets.indexStart; + buckets.indexBase = buckets.indexStart; + } else if (index < buckets.indexStart && buckets.indexEnd - index >= this._maxSize) { + rescalingNeeded = true; + low = index; + high = buckets.indexEnd; + } else if (index > buckets.indexEnd && index - buckets.indexStart >= this._maxSize) { + rescalingNeeded = true; + low = buckets.indexStart; + high = index; + } + if (rescalingNeeded) { + const change = this._changeScale(high, low); + this._downscale(change); + index = this._mapping.mapToIndex(value); + } + this._incrementIndexBy(buckets, index, increment); + } + /** + * _incrementIndexBy increments the count of the bucket specified by `index`. + * If the index is outside of the range [buckets.indexStart, buckets.indexEnd] + * the boundaries of the backing array will be adjusted and more buckets will + * be added if needed. + */ + _incrementIndexBy(buckets, index, increment) { + if (increment === 0) return; + if (buckets.length === 0) buckets.indexStart = buckets.indexEnd = buckets.indexBase = index; + if (index < buckets.indexStart) { + const span = buckets.indexEnd - index; + if (span >= buckets.backing.length) this._grow(buckets, span + 1); + buckets.indexStart = index; + } else if (index > buckets.indexEnd) { + const span = index - buckets.indexStart; + if (span >= buckets.backing.length) this._grow(buckets, span + 1); + buckets.indexEnd = index; + } + let bucketIndex = index - buckets.indexBase; + if (bucketIndex < 0) bucketIndex += buckets.backing.length; + buckets.incrementBucket(bucketIndex, increment); + } + /** + * grow resizes the backing array by doubling in size up to maxSize. + * This extends the array with a bunch of zeros and copies the + * existing counts to the same position. + */ + _grow(buckets, needed) { + const size = buckets.backing.length; + const bias = buckets.indexBase - buckets.indexStart; + const oldPositiveLimit = size - bias; + let newSize = (0, util_1.nextGreaterSquare)(needed); + if (newSize > this._maxSize) newSize = this._maxSize; + const newPositiveLimit = newSize - bias; + buckets.backing.growTo(newSize, oldPositiveLimit, newPositiveLimit); + } + /** + * _changeScale computes how much downscaling is needed by shifting the + * high and low values until they are separated by no more than size. + */ + _changeScale(high, low) { + let change = 0; + while (high - low >= this._maxSize) { + high >>= 1; + low >>= 1; + change++; + } + return change; + } + /** + * _downscale subtracts `change` from the current mapping scale. + */ + _downscale(change) { + if (change === 0) return; + if (change < 0) throw new Error(`impossible change of scale: ${this.scale}`); + const newScale = this._mapping.scale - change; + this._positive.downscale(change); + this._negative.downscale(change); + this._mapping = (0, getMapping_1.getMapping)(newScale); + } + /** + * _minScale is used by diff and merge to compute an ideal combined scale + */ + _minScale(other) { + const minScale = Math.min(this.scale, other.scale); + const highLowPos = HighLow.combine(this._highLowAtScale(this.positive, this.scale, minScale), this._highLowAtScale(other.positive, other.scale, minScale)); + const highLowNeg = HighLow.combine(this._highLowAtScale(this.negative, this.scale, minScale), this._highLowAtScale(other.negative, other.scale, minScale)); + return Math.min(minScale - this._changeScale(highLowPos.high, highLowPos.low), minScale - this._changeScale(highLowNeg.high, highLowNeg.low)); + } + /** + * _highLowAtScale is used by diff and merge to compute an ideal combined scale. + */ + _highLowAtScale(buckets, currentScale, newScale) { + if (buckets.length === 0) return new HighLow(0, -1); + const shift = currentScale - newScale; + return new HighLow(buckets.indexStart >> shift, buckets.indexEnd >> shift); + } + /** + * _mergeBuckets translates index values from another histogram and + * adds the values into the corresponding buckets of this histogram. + */ + _mergeBuckets(ours, other, theirs, scale) { + const theirOffset = theirs.offset; + const theirChange = other.scale - scale; + for (let i = 0; i < theirs.length; i++) this._incrementIndexBy(ours, theirOffset + i >> theirChange, theirs.at(i)); + } + /** + * _diffBuckets translates index values from another histogram and + * subtracts the values in the corresponding buckets of this histogram. + */ + _diffBuckets(ours, other, theirs, scale) { + const theirOffset = theirs.offset; + const theirChange = other.scale - scale; + for (let i = 0; i < theirs.length; i++) { + let bucketIndex = (theirOffset + i >> theirChange) - ours.indexBase; + if (bucketIndex < 0) bucketIndex += ours.backing.length; + ours.decrementBucket(bucketIndex, theirs.at(i)); + } + ours.trim(); + } + }; + exports.ExponentialHistogramAccumulation = ExponentialHistogramAccumulation; + /** + * Aggregator for ExponentialHistogramAccumulations + */ + var ExponentialHistogramAggregator = class { + kind = types_1.AggregatorKind.EXPONENTIAL_HISTOGRAM; + _maxSize; + _recordMinMax; + /** + * @param _maxSize Maximum number of buckets for each of the positive + * and negative ranges, exclusive of the zero-bucket. + * @param _recordMinMax If set to true, min and max will be recorded. + * Otherwise, min and max will not be recorded. + */ + constructor(maxSize, recordMinMax) { + this._maxSize = maxSize; + this._recordMinMax = recordMinMax; + } + createAccumulation(startTime) { + return new ExponentialHistogramAccumulation(startTime, this._maxSize, this._recordMinMax); + } + /** + * Return the result of the merge of two exponential histogram accumulations. + */ + merge(previous, delta) { + const result = delta.clone(); + result.merge(previous); + return result; + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + */ + diff(previous, current) { + const result = current.clone(); + result.diff(previous); + return result; + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.EXPONENTIAL_HISTOGRAM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + const pointValue = accumulation.toPointValue(); + const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: { + min: pointValue.hasMinMax ? pointValue.min : void 0, + max: pointValue.hasMinMax ? pointValue.max : void 0, + sum: !allowsNegativeValues ? pointValue.sum : void 0, + positive: { + offset: pointValue.positive.offset, + bucketCounts: pointValue.positive.bucketCounts + }, + negative: { + offset: pointValue.negative.offset, + bucketCounts: pointValue.negative.bucketCounts + }, + count: pointValue.count, + scale: pointValue.scale, + zeroCount: pointValue.zeroCount + } + }; + }) + }; + } + }; + exports.ExponentialHistogramAggregator = ExponentialHistogramAggregator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js +var require_LastValue = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LastValueAggregator = exports.LastValueAccumulation = void 0; + const types_1 = require_types$1(); + const core_1 = require_src$8(); + const MetricData_1 = require_MetricData(); + var LastValueAccumulation = class { + startTime; + _current; + sampleTime; + constructor(startTime, current = 0, sampleTime = [0, 0]) { + this.startTime = startTime; + this._current = current; + this.sampleTime = sampleTime; + } + record(value) { + this._current = value; + this.sampleTime = (0, core_1.millisToHrTime)(Date.now()); + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } + }; + exports.LastValueAccumulation = LastValueAccumulation; + /** Basic aggregator which calculates a LastValue from individual measurements. */ + var LastValueAggregator = class { + kind = types_1.AggregatorKind.LAST_VALUE; + createAccumulation(startTime) { + return new LastValueAccumulation(startTime); + } + /** + * Returns the result of the merge of the given accumulations. + * + * Return the newly captured (delta) accumulation for LastValueAggregator. + */ + merge(previous, delta) { + const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(delta.sampleTime) >= (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) ? delta : previous; + return new LastValueAccumulation(previous.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + * + * A delta aggregation is not meaningful to LastValueAggregator, just return + * the newly captured (delta) accumulation for LastValueAggregator. + */ + diff(previous, current) { + const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(current.sampleTime) >= (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) ? current : previous; + return new LastValueAccumulation(current.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.GAUGE, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: accumulation.toPointValue() + }; + }) + }; + } + }; + exports.LastValueAggregator = LastValueAggregator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js +var require_Sum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SumAggregator = exports.SumAccumulation = void 0; + const types_1 = require_types$1(); + const MetricData_1 = require_MetricData(); + var SumAccumulation = class { + startTime; + monotonic; + _current; + reset; + constructor(startTime, monotonic, current = 0, reset = false) { + this.startTime = startTime; + this.monotonic = monotonic; + this._current = current; + this.reset = reset; + } + record(value) { + if (this.monotonic && value < 0) return; + this._current += value; + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } + }; + exports.SumAccumulation = SumAccumulation; + /** Basic aggregator which calculates a Sum from individual measurements. */ + var SumAggregator = class { + kind = types_1.AggregatorKind.SUM; + monotonic; + constructor(monotonic) { + this.monotonic = monotonic; + } + createAccumulation(startTime) { + return new SumAccumulation(startTime, this.monotonic); + } + /** + * Returns the result of the merge of the given accumulations. + */ + merge(previous, delta) { + const prevPv = previous.toPointValue(); + const deltaPv = delta.toPointValue(); + if (delta.reset) return new SumAccumulation(delta.startTime, this.monotonic, deltaPv, delta.reset); + return new SumAccumulation(previous.startTime, this.monotonic, prevPv + deltaPv); + } + /** + * Returns a new DELTA aggregation by comparing two cumulative measurements. + */ + diff(previous, current) { + const prevPv = previous.toPointValue(); + const currPv = current.toPointValue(); + /** + * If the SumAggregator is a monotonic one and the previous point value is + * greater than the current one, a reset is deemed to be happened. + * Return the current point value to prevent the value from been reset. + */ + if (this.monotonic && prevPv > currPv) return new SumAccumulation(current.startTime, this.monotonic, currPv, true); + return new SumAccumulation(current.startTime, this.monotonic, currPv - prevPv); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.SUM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: accumulation.toPointValue() + }; + }), + isMonotonic: this.monotonic + }; + } + }; + exports.SumAggregator = SumAggregator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js +var require_aggregator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SumAggregator = exports.SumAccumulation = exports.LastValueAggregator = exports.LastValueAccumulation = exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = exports.HistogramAggregator = exports.HistogramAccumulation = exports.DropAggregator = void 0; + var Drop_1 = require_Drop(); + Object.defineProperty(exports, "DropAggregator", { + enumerable: true, + get: function() { + return Drop_1.DropAggregator; + } + }); + var Histogram_1 = require_Histogram(); + Object.defineProperty(exports, "HistogramAccumulation", { + enumerable: true, + get: function() { + return Histogram_1.HistogramAccumulation; + } + }); + Object.defineProperty(exports, "HistogramAggregator", { + enumerable: true, + get: function() { + return Histogram_1.HistogramAggregator; + } + }); + var ExponentialHistogram_1 = require_ExponentialHistogram(); + Object.defineProperty(exports, "ExponentialHistogramAccumulation", { + enumerable: true, + get: function() { + return ExponentialHistogram_1.ExponentialHistogramAccumulation; + } + }); + Object.defineProperty(exports, "ExponentialHistogramAggregator", { + enumerable: true, + get: function() { + return ExponentialHistogram_1.ExponentialHistogramAggregator; + } + }); + var LastValue_1 = require_LastValue(); + Object.defineProperty(exports, "LastValueAccumulation", { + enumerable: true, + get: function() { + return LastValue_1.LastValueAccumulation; + } + }); + Object.defineProperty(exports, "LastValueAggregator", { + enumerable: true, + get: function() { + return LastValue_1.LastValueAggregator; + } + }); + var Sum_1 = require_Sum(); + Object.defineProperty(exports, "SumAccumulation", { + enumerable: true, + get: function() { + return Sum_1.SumAccumulation; + } + }); + Object.defineProperty(exports, "SumAggregator", { + enumerable: true, + get: function() { + return Sum_1.SumAggregator; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js +var require_Aggregation = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_AGGREGATION = exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = exports.HISTOGRAM_AGGREGATION = exports.LAST_VALUE_AGGREGATION = exports.SUM_AGGREGATION = exports.DROP_AGGREGATION = exports.DefaultAggregation = exports.ExponentialHistogramAggregation = exports.ExplicitBucketHistogramAggregation = exports.HistogramAggregation = exports.LastValueAggregation = exports.SumAggregation = exports.DropAggregation = void 0; + const api = (init_esm$2(), __toCommonJS(esm_exports$2)); + const aggregator_1 = require_aggregator(); + const MetricData_1 = require_MetricData(); + /** + * The default drop aggregation. + */ + var DropAggregation = class DropAggregation { + static DEFAULT_INSTANCE = new aggregator_1.DropAggregator(); + createAggregator(_instrument) { + return DropAggregation.DEFAULT_INSTANCE; + } + }; + exports.DropAggregation = DropAggregation; + /** + * The default sum aggregation. + */ + var SumAggregation = class SumAggregation { + static MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(true); + static NON_MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(false); + createAggregator(instrument) { + switch (instrument.type) { + case MetricData_1.InstrumentType.COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: + case MetricData_1.InstrumentType.HISTOGRAM: return SumAggregation.MONOTONIC_INSTANCE; + default: return SumAggregation.NON_MONOTONIC_INSTANCE; + } + } + }; + exports.SumAggregation = SumAggregation; + /** + * The default last value aggregation. + */ + var LastValueAggregation = class LastValueAggregation { + static DEFAULT_INSTANCE = new aggregator_1.LastValueAggregator(); + createAggregator(_instrument) { + return LastValueAggregation.DEFAULT_INSTANCE; + } + }; + exports.LastValueAggregation = LastValueAggregation; + /** + * The default histogram aggregation. + + */ + var HistogramAggregation = class HistogramAggregation { + static DEFAULT_INSTANCE = new aggregator_1.HistogramAggregator([ + 0, + 5, + 10, + 25, + 50, + 75, + 100, + 250, + 500, + 750, + 1e3, + 2500, + 5e3, + 7500, + 1e4 + ], true); + createAggregator(_instrument) { + return HistogramAggregation.DEFAULT_INSTANCE; + } + }; + exports.HistogramAggregation = HistogramAggregation; + /** + * The explicit bucket histogram aggregation. + */ + var ExplicitBucketHistogramAggregation = class { + _boundaries; + _recordMinMax; + /** + * @param boundaries the bucket boundaries of the histogram aggregation + * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded. + */ + constructor(boundaries, recordMinMax = true) { + if (boundaries == null) throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array"); + boundaries = boundaries.concat(); + boundaries = boundaries.sort((a, b) => a - b); + const minusInfinityIndex = boundaries.lastIndexOf(-Infinity); + let infinityIndex = boundaries.indexOf(Infinity); + if (infinityIndex === -1) infinityIndex = void 0; + this._boundaries = boundaries.slice(minusInfinityIndex + 1, infinityIndex); + this._recordMinMax = recordMinMax; + } + createAggregator(_instrument) { + return new aggregator_1.HistogramAggregator(this._boundaries, this._recordMinMax); + } + }; + exports.ExplicitBucketHistogramAggregation = ExplicitBucketHistogramAggregation; + var ExponentialHistogramAggregation = class { + _maxSize; + _recordMinMax; + constructor(maxSize = 160, recordMinMax = true) { + this._maxSize = maxSize; + this._recordMinMax = recordMinMax; + } + createAggregator(_instrument) { + return new aggregator_1.ExponentialHistogramAggregator(this._maxSize, this._recordMinMax); + } + }; + exports.ExponentialHistogramAggregation = ExponentialHistogramAggregation; + /** + * The default aggregation. + */ + var DefaultAggregation = class { + _resolve(instrument) { + switch (instrument.type) { + case MetricData_1.InstrumentType.COUNTER: + case MetricData_1.InstrumentType.UP_DOWN_COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: return exports.SUM_AGGREGATION; + case MetricData_1.InstrumentType.GAUGE: + case MetricData_1.InstrumentType.OBSERVABLE_GAUGE: return exports.LAST_VALUE_AGGREGATION; + case MetricData_1.InstrumentType.HISTOGRAM: + if (instrument.advice.explicitBucketBoundaries) return new ExplicitBucketHistogramAggregation(instrument.advice.explicitBucketBoundaries); + return exports.HISTOGRAM_AGGREGATION; + } + api.diag.warn(`Unable to recognize instrument type: ${instrument.type}`); + return exports.DROP_AGGREGATION; + } + createAggregator(instrument) { + return this._resolve(instrument).createAggregator(instrument); + } + }; + exports.DefaultAggregation = DefaultAggregation; + exports.DROP_AGGREGATION = new DropAggregation(); + exports.SUM_AGGREGATION = new SumAggregation(); + exports.LAST_VALUE_AGGREGATION = new LastValueAggregation(); + exports.HISTOGRAM_AGGREGATION = new HistogramAggregation(); + exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = new ExponentialHistogramAggregation(); + exports.DEFAULT_AGGREGATION = new DefaultAggregation(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js +var require_AggregationOption = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toAggregation = exports.AggregationType = void 0; + const Aggregation_1 = require_Aggregation(); + var AggregationType; + (function(AggregationType) { + AggregationType[AggregationType["DEFAULT"] = 0] = "DEFAULT"; + AggregationType[AggregationType["DROP"] = 1] = "DROP"; + AggregationType[AggregationType["SUM"] = 2] = "SUM"; + AggregationType[AggregationType["LAST_VALUE"] = 3] = "LAST_VALUE"; + AggregationType[AggregationType["EXPLICIT_BUCKET_HISTOGRAM"] = 4] = "EXPLICIT_BUCKET_HISTOGRAM"; + AggregationType[AggregationType["EXPONENTIAL_HISTOGRAM"] = 5] = "EXPONENTIAL_HISTOGRAM"; + })(AggregationType || (exports.AggregationType = AggregationType = {})); + function toAggregation(option) { + switch (option.type) { + case AggregationType.DEFAULT: return Aggregation_1.DEFAULT_AGGREGATION; + case AggregationType.DROP: return Aggregation_1.DROP_AGGREGATION; + case AggregationType.SUM: return Aggregation_1.SUM_AGGREGATION; + case AggregationType.LAST_VALUE: return Aggregation_1.LAST_VALUE_AGGREGATION; + case AggregationType.EXPONENTIAL_HISTOGRAM: { + const expOption = option; + return new Aggregation_1.ExponentialHistogramAggregation(expOption.options?.maxSize, expOption.options?.recordMinMax); + } + case AggregationType.EXPLICIT_BUCKET_HISTOGRAM: { + const expOption = option; + if (expOption.options == null) return Aggregation_1.HISTOGRAM_AGGREGATION; + else return new Aggregation_1.ExplicitBucketHistogramAggregation(expOption.options?.boundaries, expOption.options?.recordMinMax); + } + default: throw new Error("Unsupported Aggregation"); + } + } + exports.toAggregation = toAggregation; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js +var require_AggregationSelector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = exports.DEFAULT_AGGREGATION_SELECTOR = void 0; + const AggregationTemporality_1 = require_AggregationTemporality(); + const AggregationOption_1 = require_AggregationOption(); + const DEFAULT_AGGREGATION_SELECTOR = (_instrumentType) => { + return { type: AggregationOption_1.AggregationType.DEFAULT }; + }; + exports.DEFAULT_AGGREGATION_SELECTOR = DEFAULT_AGGREGATION_SELECTOR; + const DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = (_instrumentType) => AggregationTemporality_1.AggregationTemporality.CUMULATIVE; + exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/semconv.js +var require_semconv$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_ERROR_TYPE = exports.METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION = exports.OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER = exports.ATTR_OTEL_COMPONENT_TYPE = exports.ATTR_OTEL_COMPONENT_NAME = void 0; + /** + * A name uniquely identifying the instance of the OpenTelemetry component within its containing SDK instance. + * + * @example otlp_grpc_span_exporter/0 + * @example custom-name + * + * @note Implementations **SHOULD** ensure a low cardinality for this attribute, even across application or SDK restarts. + * E.g. implementations **MUST NOT** use UUIDs as values for this attribute. + * + * Implementations **MAY** achieve these goals by following a `/` pattern, e.g. `batching_span_processor/0`. + * Hereby `otel.component.type` refers to the corresponding attribute value of the component. + * + * The value of `instance-counter` **MAY** be automatically assigned by the component and uniqueness within the enclosing SDK instance **MUST** be guaranteed. + * For example, `` **MAY** be implemented by using a monotonically increasing counter (starting with `0`), which is incremented every time an + * instance of the given component type is started. + * + * With this implementation, for example the first Batching Span Processor would have `batching_span_processor/0` + * as `otel.component.name`, the second one `batching_span_processor/1` and so on. + * These values will therefore be reused in the case of an application restart. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OTEL_COMPONENT_NAME = "otel.component.name"; + /** + * A name identifying the type of the OpenTelemetry component. + * + * @example batching_span_processor + * @example com.example.MySpanExporter + * + * @note If none of the standardized values apply, implementations **SHOULD** use the language-defined name of the type. + * E.g. for Java the fully qualified classname **SHOULD** be used in this case. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OTEL_COMPONENT_TYPE = "otel.component.type"; + /** + * Enum value "periodic_metric_reader" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}. + * + * The builtin SDK periodically exporting metric reader + * + * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER = "periodic_metric_reader"; + /** + * The duration of the collect operation of the metric reader. + * + * @note For successful collections, `error.type` **MUST NOT** be set. For failed collections, `error.type` **SHOULD** contain the failure cause. + * It can happen that metrics collection is successful for some MetricProducers, while others fail. In that case `error.type` **SHOULD** be set to any of the failure causes. + * + * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION = "otel.sdk.metric_reader.collection.duration"; + /** + * Describes a class of error the operation ended with. + * + * @example timeout + * @example java.net.UnknownHostException + * @example server_certificate_invalid + * @example 500 + * + * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality. + * + * When `error.type` is set to a type (e.g., an exception type), its + * canonical class name identifying the type within the artifact **SHOULD** be used. + * + * Instrumentations **SHOULD** document the list of errors they report. + * + * The cardinality of `error.type` within one instrumentation library **SHOULD** be low. + * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications + * should be prepared for `error.type` to have high cardinality at query time when no + * additional filters are applied. + * + * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`. + * + * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes), + * it's **RECOMMENDED** to: + * + * - Use a domain-specific attribute + * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not. + */ + exports.ATTR_ERROR_TYPE = "error.type"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReaderMetrics.js +var require_MetricReaderMetrics = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricReaderMetrics = void 0; + const semconv_1 = require_semconv$3(); + const componentCounter = /* @__PURE__ */ new Map(); + /** + * Generates `otel.sdk.metric_reader.*` self-observability metrics. + * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#metric-otelsdkmetric_readercollectionduration + */ + var MetricReaderMetrics = class { + collectionDuration; + standardAttrs; + constructor(componentType, meter) { + const counter = componentCounter.get(componentType) ?? 0; + componentCounter.set(componentType, counter + 1); + this.standardAttrs = { + [semconv_1.ATTR_OTEL_COMPONENT_TYPE]: componentType, + [semconv_1.ATTR_OTEL_COMPONENT_NAME]: `${componentType}/${counter}` + }; + this.collectionDuration = meter.createHistogram(semconv_1.METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION, { + unit: "s", + description: "The duration of the collect operation of the metric reader.", + advice: { explicitBucketBoundaries: [] } + }); + } + recordCollection(durationSecs, error) { + const attrs = error ? { + ...this.standardAttrs, + [semconv_1.ATTR_ERROR_TYPE]: error + } : this.standardAttrs; + this.collectionDuration.record(durationSecs, attrs); + } + }; + exports.MetricReaderMetrics = MetricReaderMetrics; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/version.js +var require_version$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = void 0; + exports.VERSION = "2.11.0"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js +var require_MetricReader = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricReader = void 0; + const api = (init_esm$2(), __toCommonJS(esm_exports$2)); + const utils_1 = require_utils$3(); + const AggregationSelector_1 = require_AggregationSelector(); + const MetricReaderMetrics_1 = require_MetricReaderMetrics(); + const version_1 = require_version$1(); + const core_1 = require_src$8(); + /** + * A registered reader of metrics that, when linked to a {@link MetricProducer}, offers global + * control over metrics. + */ + var MetricReader = class { + _shutdown = false; + _metricProducers; + _sdkMetricProducer; + _selfObsMetrics; + _aggregationTemporalitySelector; + _aggregationSelector; + _cardinalitySelector; + _otelComponentType; + constructor(options) { + this._aggregationSelector = options?.aggregationSelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_SELECTOR; + this._aggregationTemporalitySelector = options?.aggregationTemporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; + this._metricProducers = options?.metricProducers ?? []; + this._cardinalitySelector = options?.cardinalitySelector; + this._otelComponentType = options?.otelComponentType ?? this.constructor.name; + this._selfObsMetrics = new MetricReaderMetrics_1.MetricReaderMetrics(this._otelComponentType, api.createNoopMeter()); + } + setMetricProducer(metricProducer) { + if (this._sdkMetricProducer) throw new Error("MetricReader can not be bound to a MeterProvider again."); + this._sdkMetricProducer = metricProducer; + this.onInitialized(); + } + _setSelfObsMeterProvider(meterProvider) { + const meter = meterProvider.getMeter("@opentelemetry/sdk-metrics", version_1.VERSION); + this._selfObsMetrics = new MetricReaderMetrics_1.MetricReaderMetrics(this._otelComponentType, meter); + } + selectAggregation(instrumentType) { + return this._aggregationSelector(instrumentType); + } + selectAggregationTemporality(instrumentType) { + return this._aggregationTemporalitySelector(instrumentType); + } + selectCardinalityLimit(instrumentType) { + return this._cardinalitySelector ? this._cardinalitySelector(instrumentType) : 2e3; + } + /** + * Handle once the SDK has initialized this {@link MetricReader} + * Overriding this method is optional. + */ + onInitialized() {} + async collect(options) { + if (this._sdkMetricProducer === void 0) throw new Error("MetricReader is not bound to a MetricProducer"); + if (this._shutdown) throw new Error("MetricReader is shutdown"); + const startTime = (0, core_1.hrTime)(); + const [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([this._sdkMetricProducer.collect({ timeoutMillis: options?.timeoutMillis }), ...this._metricProducers.map((producer) => producer.collect({ timeoutMillis: options?.timeoutMillis }))]); + const endTime = (0, core_1.hrTime)(); + const errors = sdkCollectionResults.errors.concat(additionalCollectionResults.flatMap((result) => result.errors)); + const collectDuration = (0, core_1.hrTimeToSeconds)((0, core_1.hrTimeDuration)(startTime, endTime)); + this._selfObsMetrics.recordCollection(collectDuration, errors.length > 0 ? errors[0].name ?? "collect_error" : void 0); + return { + resourceMetrics: { + resource: sdkCollectionResults.resourceMetrics.resource, + scopeMetrics: sdkCollectionResults.resourceMetrics.scopeMetrics.concat(additionalCollectionResults.flatMap((result) => result.resourceMetrics.scopeMetrics)) + }, + errors + }; + } + async shutdown(options) { + if (this._shutdown) { + api.diag.error("Cannot call shutdown twice."); + return; + } + if (options?.timeoutMillis == null) await this.onShutdown(); + else await (0, utils_1.callWithTimeout)(this.onShutdown(), options.timeoutMillis); + this._shutdown = true; + } + async forceFlush(options) { + if (this._shutdown) { + api.diag.warn("Cannot forceFlush on already shutdown MetricReader."); + return; + } + if (options?.timeoutMillis == null) { + await this.onForceFlush(); + return; + } + await (0, utils_1.callWithTimeout)(this.onForceFlush(), options.timeoutMillis); + } + }; + exports.MetricReader = MetricReader; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricDataSplitter.js +var require_MetricDataSplitter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.splitMetricData = void 0; + /** + * Splits a ResourceMetrics object into smaller ResourceMetrics objects + * such that no batch exceeds maxExportBatchSize data points. + * @param resourceMetrics The metrics to split. + * @param maxExportBatchSize The maximum number of data points per batch. + * @internal + */ + function splitMetricData(resourceMetrics, maxExportBatchSize) { + if (!Number.isInteger(maxExportBatchSize) || maxExportBatchSize <= 0) throw new Error("maxExportBatchSize must be a positive integer"); + const batches = []; + let currentBatchPoints = 0; + let currentScopeMetrics = []; + function flush() { + if (currentScopeMetrics.length > 0) { + batches.push({ + resource: resourceMetrics.resource, + scopeMetrics: currentScopeMetrics + }); + currentScopeMetrics = []; + currentBatchPoints = 0; + } + } + for (const scopeMetric of resourceMetrics.scopeMetrics) { + let scopeMetricCopy = null; + for (const metric of scopeMetric.metrics) { + const dataPoints = metric.dataPoints; + if (dataPoints.length === 0) { + if (!scopeMetricCopy) { + scopeMetricCopy = { + scope: scopeMetric.scope, + metrics: [] + }; + currentScopeMetrics.push(scopeMetricCopy); + } + scopeMetricCopy.metrics.push(metric); + continue; + } + let offset = 0; + while (offset < dataPoints.length) { + const spaceLeft = maxExportBatchSize - currentBatchPoints; + const take = Math.min(spaceLeft, dataPoints.length - offset); + if (!scopeMetricCopy) { + scopeMetricCopy = { + scope: scopeMetric.scope, + metrics: [] + }; + currentScopeMetrics.push(scopeMetricCopy); + } + const metricCopy = { + ...metric, + dataPoints: dataPoints.slice(offset, offset + take) + }; + scopeMetricCopy.metrics.push(metricCopy); + offset += take; + currentBatchPoints += take; + if (currentBatchPoints === maxExportBatchSize) { + flush(); + scopeMetricCopy = null; + } + } + } + } + flush(); + return batches; + } + exports.splitMetricData = splitMetricData; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js +var require_PeriodicExportingMetricReader = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PeriodicExportingMetricReader = void 0; + const api = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const MetricReader_1 = require_MetricReader(); + const utils_1 = require_utils$3(); + const MetricData_1 = require_MetricData(); + const MetricDataSplitter_1 = require_MetricDataSplitter(); + const semconv_1 = require_semconv$3(); + /** + * {@link MetricReader} which collects metrics based on a user-configurable time interval, and passes the metrics to + * the configured {@link PushMetricExporter} + */ + var PeriodicExportingMetricReader = class extends MetricReader_1.MetricReader { + _interval; + _exporter; + _exportInterval; + _exportTimeout; + _maxExportBatchSize; + _ongoingExportPromise = null; + constructor(options) { + const { exporter, exportIntervalMillis = 6e4, metricProducers, cardinalityLimits, maxExportBatchSize } = options; + let { exportTimeoutMillis = 3e4 } = options; + super({ + aggregationSelector: exporter.selectAggregation?.bind(exporter), + aggregationTemporalitySelector: exporter.selectAggregationTemporality?.bind(exporter), + otelComponentType: semconv_1.OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER, + metricProducers, + cardinalitySelector: (instrumentType) => { + const limits = { + default: 2e3, + ...cardinalityLimits + }; + switch (instrumentType) { + case MetricData_1.InstrumentType.COUNTER: return limits.counter ?? limits.default; + case MetricData_1.InstrumentType.GAUGE: return limits.gauge ?? limits.default; + case MetricData_1.InstrumentType.HISTOGRAM: return limits.histogram ?? limits.default; + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: return limits.observableCounter ?? limits.default; + case MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: return limits.observableUpDownCounter ?? limits.default; + case MetricData_1.InstrumentType.OBSERVABLE_GAUGE: return limits.observableGauge ?? limits.default; + case MetricData_1.InstrumentType.UP_DOWN_COUNTER: return limits.upDownCounter ?? limits.default; + default: return limits.default; + } + } + }); + if (exportIntervalMillis <= 0) throw Error("exportIntervalMillis must be greater than 0"); + if (exportTimeoutMillis <= 0) throw Error("exportTimeoutMillis must be greater than 0"); + if (maxExportBatchSize !== void 0 && (!Number.isInteger(maxExportBatchSize) || maxExportBatchSize <= 0)) throw Error("maxExportBatchSize must be a positive integer"); + if (exportIntervalMillis < exportTimeoutMillis) { + if ("exportIntervalMillis" in options && "exportTimeoutMillis" in options) throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis"); + else { + api.diag.info(`Timeout of ${exportTimeoutMillis} exceeds the interval of ${exportIntervalMillis}. Clamping timeout to interval duration.`); + exportTimeoutMillis = exportIntervalMillis; + } + } + this._exportInterval = exportIntervalMillis; + this._exportTimeout = exportTimeoutMillis; + this._exporter = exporter; + this._maxExportBatchSize = maxExportBatchSize; + } + async _runOnce() { + try { + await this._doRun(); + } catch (err) { + (0, core_1.globalErrorHandler)(err); + } + } + async _doRun() { + if (this._ongoingExportPromise) { + api.diag.debug("PeriodicExportingMetricReader: export already in progress, skipping"); + return; + } + const currentRun = async () => { + const { resourceMetrics, errors } = await this.collect({ timeoutMillis: this._exportTimeout }); + if (errors.length > 0) api.diag.error("PeriodicExportingMetricReader: metrics collection errors", ...errors); + if (resourceMetrics.resource.asyncAttributesPending) try { + await resourceMetrics.resource.waitForAsyncAttributes?.(); + } catch (e) { + api.diag.debug("Error while resolving async portion of resource: ", e); + (0, core_1.globalErrorHandler)(e); + } + if (resourceMetrics.scopeMetrics.length === 0) return; + const batches = this._maxExportBatchSize ? (0, MetricDataSplitter_1.splitMetricData)(resourceMetrics, this._maxExportBatchSize) : [resourceMetrics]; + let anyErr = null; + for (const batch of batches) try { + const result = await (0, utils_1.callWithTimeout)(core_1.internal._export(this._exporter, batch), this._exportTimeout); + if (result.code !== core_1.ExportResultCode.SUCCESS) anyErr = /* @__PURE__ */ new Error(`PeriodicExportingMetricReader: metrics export failed (error ${result.error})`); + } catch (e) { + if (e instanceof utils_1.TimeoutError) { + api.diag.error(`PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`); + break; + } else { + api.diag.error("PeriodicExportingMetricReader: metrics export threw error", e); + anyErr = e instanceof Error ? e : new Error(String(e)); + } + } + if (anyErr) throw anyErr; + }; + this._ongoingExportPromise = currentRun(); + try { + await this._ongoingExportPromise; + } finally { + this._ongoingExportPromise = null; + } + } + onInitialized() { + this._interval = setInterval(() => { + this._runOnce(); + }, this._exportInterval); + if (typeof this._interval !== "number") this._interval.unref(); + } + async onForceFlush() { + await this._awaitOngoingExport(); + if (this._ongoingExportPromise) await this._awaitOngoingExport(); + else await this._runOnce(); + await this._exporter.forceFlush(); + } + /** + * Helper function to wait for an ongoing export to complete. + * Errors are swallowed and handled by the original _runOnce(). + */ + async _awaitOngoingExport() { + if (this._ongoingExportPromise) { + api.diag.debug("PeriodicExportingMetricReader: export already in progress, awaiting ongoing export"); + try { + await this._ongoingExportPromise; + } catch {} + } + } + async onShutdown() { + if (this._interval) clearInterval(this._interval); + await this.onForceFlush(); + await this._exporter.shutdown(); + } + }; + exports.PeriodicExportingMetricReader = PeriodicExportingMetricReader; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js +var require_InMemoryMetricExporter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InMemoryMetricExporter = void 0; + const core_1 = require_src$8(); + /** + * In-memory Metrics Exporter is a Push Metric Exporter + * which accumulates metrics data in the local memory and + * allows to inspect it (useful for e.g. unit tests). + */ + var InMemoryMetricExporter = class { + _shutdown = false; + _aggregationTemporality; + _metrics = []; + constructor(aggregationTemporality) { + this._aggregationTemporality = aggregationTemporality; + } + /** + * @inheritedDoc + */ + export(metrics, resultCallback) { + if (this._shutdown) { + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.FAILED }), 0); + return; + } + this._metrics.push(metrics); + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); + } + /** + * Returns all the collected resource metrics + * @returns ResourceMetrics[] + */ + getMetrics() { + return this._metrics; + } + forceFlush() { + return Promise.resolve(); + } + reset() { + this._metrics = []; + } + selectAggregationTemporality(_instrumentType) { + return this._aggregationTemporality; + } + shutdown() { + this._shutdown = true; + return Promise.resolve(); + } + }; + exports.InMemoryMetricExporter = InMemoryMetricExporter; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js +var require_ConsoleMetricExporter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConsoleMetricExporter = void 0; + const core_1 = require_src$8(); + const AggregationSelector_1 = require_AggregationSelector(); + /** + * This is an implementation of {@link PushMetricExporter} that prints metrics to the + * console. This class can be used for diagnostic purposes. + * + * NOTE: This {@link PushMetricExporter} is intended for diagnostics use only, output rendered to the console may change at any time. + */ + var ConsoleMetricExporter = class ConsoleMetricExporter { + _shutdown = false; + _temporalitySelector; + constructor(options) { + this._temporalitySelector = options?.temporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; + } + export(metrics, resultCallback) { + if (this._shutdown) { + resultCallback({ code: core_1.ExportResultCode.FAILED }); + return; + } + return ConsoleMetricExporter._sendMetrics(metrics, resultCallback); + } + forceFlush() { + return Promise.resolve(); + } + selectAggregationTemporality(_instrumentType) { + return this._temporalitySelector(_instrumentType); + } + shutdown() { + this._shutdown = true; + return Promise.resolve(); + } + static _sendMetrics(metrics, done) { + for (const scopeMetrics of metrics.scopeMetrics) for (const metric of scopeMetrics.metrics) console.dir({ + descriptor: metric.descriptor, + dataPointType: metric.dataPointType, + dataPoints: metric.dataPoints + }, { depth: null }); + done({ code: core_1.ExportResultCode.SUCCESS }); + } + }; + exports.ConsoleMetricExporter = ConsoleMetricExporter; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/default-service-name.js +var require_default_service_name = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports._clearDefaultServiceNameCache = exports.defaultServiceName = void 0; + let serviceName; + /** + * Returns the default service name for OpenTelemetry resources. + * In Node.js environments, returns "unknown_service:". + * In browser/edge environments, returns "unknown_service". + */ + function defaultServiceName() { + if (serviceName === void 0) try { + const argv0 = globalThis.process.argv0; + serviceName = argv0 ? `unknown_service:${argv0}` : "unknown_service"; + } catch { + serviceName = "unknown_service"; + } + return serviceName; + } + exports.defaultServiceName = defaultServiceName; + /** @internal For testing purposes only */ + function _clearDefaultServiceNameCache() { + serviceName = void 0; + } + exports._clearDefaultServiceNameCache = _clearDefaultServiceNameCache; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/utils.js +var require_utils$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPromiseLike = void 0; + const isPromiseLike = (val) => { + return val !== null && typeof val === "object" && typeof val.then === "function"; + }; + exports.isPromiseLike = isPromiseLike; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js +var require_ResourceImpl = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultResource = exports.emptyResource = exports.resourceFromDetectedResource = exports.resourceFromAttributes = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const semantic_conventions_1 = (init_esm$1(), __toCommonJS(esm_exports$1)); + const default_service_name_1 = require_default_service_name(); + const utils_1 = require_utils$2(); + var ResourceImpl = class ResourceImpl { + _rawAttributes; + _asyncAttributesPending = false; + _schemaUrl; + _memoizedAttributes; + static FromAttributeList(attributes, options) { + const res = new ResourceImpl({}, options); + res._rawAttributes = guardedRawAttributes(attributes); + res._asyncAttributesPending = attributes.filter(([_, val]) => (0, utils_1.isPromiseLike)(val)).length > 0; + return res; + } + constructor(resource, options) { + const attributes = resource.attributes ?? {}; + this._rawAttributes = Object.entries(attributes).map(([k, v]) => { + if ((0, utils_1.isPromiseLike)(v)) this._asyncAttributesPending = true; + return [k, v]; + }); + this._rawAttributes = guardedRawAttributes(this._rawAttributes); + this._schemaUrl = validateSchemaUrl(options?.schemaUrl); + } + get asyncAttributesPending() { + return this._asyncAttributesPending; + } + async waitForAsyncAttributes() { + if (!this.asyncAttributesPending) return; + for (let i = 0; i < this._rawAttributes.length; i++) { + const [k, v] = this._rawAttributes[i]; + this._rawAttributes[i] = [k, (0, utils_1.isPromiseLike)(v) ? await v : v]; + } + this._asyncAttributesPending = false; + } + get attributes() { + if (this.asyncAttributesPending) api_1.diag.error("Accessing resource attributes before async attributes settled"); + if (this._memoizedAttributes) return this._memoizedAttributes; + const attrs = {}; + for (const [k, v] of this._rawAttributes) { + if ((0, utils_1.isPromiseLike)(v)) { + api_1.diag.debug(`Unsettled resource attribute ${k} skipped`); + continue; + } + if (v != null) attrs[k] ??= v; + } + if (!this._asyncAttributesPending) this._memoizedAttributes = attrs; + return attrs; + } + getRawAttributes() { + return this._rawAttributes; + } + get schemaUrl() { + return this._schemaUrl; + } + merge(resource) { + if (resource == null) return this; + const mergedSchemaUrl = mergeSchemaUrl(this, resource); + const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : void 0; + return ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions); + } + }; + function resourceFromAttributes(attributes, options) { + return ResourceImpl.FromAttributeList(Object.entries(attributes), options); + } + exports.resourceFromAttributes = resourceFromAttributes; + function resourceFromDetectedResource(detectedResource, options) { + return new ResourceImpl(detectedResource, options); + } + exports.resourceFromDetectedResource = resourceFromDetectedResource; + function emptyResource() { + return resourceFromAttributes({}); + } + exports.emptyResource = emptyResource; + function defaultResource() { + return resourceFromAttributes({ + [semantic_conventions_1.ATTR_SERVICE_NAME]: (0, default_service_name_1.defaultServiceName)(), + [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE], + [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME], + [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION] + }); + } + exports.defaultResource = defaultResource; + function guardedRawAttributes(attributes) { + return attributes.map(([k, v]) => { + if ((0, utils_1.isPromiseLike)(v)) return [k, v.catch((err) => { + api_1.diag.debug("promise rejection for resource attribute: %s - %s", k, err); + })]; + return [k, v]; + }); + } + function validateSchemaUrl(schemaUrl) { + if (typeof schemaUrl === "string" || schemaUrl === void 0) return schemaUrl; + api_1.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl); + } + function mergeSchemaUrl(old, updating) { + const oldSchemaUrl = old?.schemaUrl; + const updatingSchemaUrl = updating?.schemaUrl; + const isOldEmpty = oldSchemaUrl === void 0 || oldSchemaUrl === ""; + const isUpdatingEmpty = updatingSchemaUrl === void 0 || updatingSchemaUrl === ""; + if (isOldEmpty) return updatingSchemaUrl; + if (isUpdatingEmpty) return oldSchemaUrl; + if (oldSchemaUrl === updatingSchemaUrl) return oldSchemaUrl; + api_1.diag.warn("Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.", oldSchemaUrl, updatingSchemaUrl); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detect-resources.js +var require_detect_resources = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.detectResources = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const ResourceImpl_1 = require_ResourceImpl(); + /** + * Runs all resource detectors and returns the results merged into a single Resource. + * + * @param config Configuration for resource detection + */ + const detectResources = (config = {}) => { + return (config.detectors || []).map((d) => { + try { + const resource = (0, ResourceImpl_1.resourceFromDetectedResource)(d.detect(config)); + api_1.diag.debug(`${d.constructor.name} found resource.`, resource); + return resource; + } catch (e) { + api_1.diag.debug(`${d.constructor.name} failed: ${e.message}`); + return (0, ResourceImpl_1.emptyResource)(); + } + }).reduce((acc, resource) => acc.merge(resource), (0, ResourceImpl_1.emptyResource)()); + }; + exports.detectResources = detectResources; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js +var require_EnvDetector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.envDetector = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const semantic_conventions_1 = (init_esm$1(), __toCommonJS(esm_exports$1)); + const core_1 = require_src$8(); + /** + * EnvDetector can be used to detect the presence of and create a Resource + * from the OTEL_RESOURCE_ATTRIBUTES environment variable. + */ + var EnvDetector = class { + _MAX_LENGTH = 255; + _COMMA_SEPARATOR = ","; + _LABEL_KEY_VALUE_SPLITTER = "="; + /** + * Returns a {@link Resource} populated with attributes from the + * OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async + * function to conform to the Detector interface. + * + * @param config The resource detection config + */ + detect(_config) { + const attributes = {}; + const rawAttributes = (0, core_1.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES"); + const serviceName = (0, core_1.getStringFromEnv)("OTEL_SERVICE_NAME"); + if (rawAttributes) try { + const parsedAttributes = this._parseResourceAttributes(rawAttributes); + Object.assign(attributes, parsedAttributes); + } catch (e) { + api_1.diag.debug(`EnvDetector failed: ${e instanceof Error ? e.message : e}`); + } + if (serviceName) attributes[semantic_conventions_1.ATTR_SERVICE_NAME] = serviceName; + return { attributes }; + } + /** + * Creates an attribute map from the OTEL_RESOURCE_ATTRIBUTES environment + * variable. + * + * OTEL_RESOURCE_ATTRIBUTES: A comma-separated list of attributes in the + * format "key1=value1,key2=value2". The ',' and '=' characters in keys + * and values MUST be percent-encoded. Other characters MAY be percent-encoded. + * + * Per the spec, on any error (e.g., decoding failure), the entire environment + * variable value is discarded. + * + * @param rawEnvAttributes The resource attributes as a comma-separated list + * of key/value pairs. + * @returns The parsed resource attributes. + * @throws Error if parsing fails (caller handles by discarding all attributes) + */ + _parseResourceAttributes(rawEnvAttributes) { + if (!rawEnvAttributes) return {}; + const attributes = {}; + const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR).filter((attr) => attr.trim() !== ""); + for (const rawAttribute of rawAttributes) { + const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER); + if (keyValuePair.length !== 2) throw new Error(`Invalid format for OTEL_RESOURCE_ATTRIBUTES: "${rawAttribute}". Expected format: key=value. The ',' and '=' characters must be percent-encoded in keys and values.`); + const [rawKey, rawValue] = keyValuePair; + const key = rawKey.trim(); + const value = rawValue.trim(); + if (key.length === 0) throw new Error(`Invalid OTEL_RESOURCE_ATTRIBUTES: empty attribute key in "${rawAttribute}".`); + let decodedKey; + let decodedValue; + try { + decodedKey = decodeURIComponent(key); + decodedValue = decodeURIComponent(value); + } catch (e) { + throw new Error(`Failed to percent-decode OTEL_RESOURCE_ATTRIBUTES entry "${rawAttribute}": ${e instanceof Error ? e.message : e}`, { cause: e }); + } + if (decodedKey.length > this._MAX_LENGTH) throw new Error(`Attribute key exceeds the maximum length of ${this._MAX_LENGTH} characters: "${decodedKey}".`); + if (decodedValue.length > this._MAX_LENGTH) throw new Error(`Attribute value exceeds the maximum length of ${this._MAX_LENGTH} characters for key "${decodedKey}".`); + attributes[decodedKey] = decodedValue; + } + return attributes; + } + }; + exports.envDetector = new EnvDetector(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/semconv.js +var require_semconv$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_WEBENGINE_VERSION = exports.ATTR_WEBENGINE_NAME = exports.ATTR_WEBENGINE_DESCRIPTION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_PROCESS_RUNTIME_VERSION = exports.ATTR_PROCESS_RUNTIME_NAME = exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = exports.ATTR_PROCESS_PID = exports.ATTR_PROCESS_OWNER = exports.ATTR_PROCESS_EXECUTABLE_PATH = exports.ATTR_PROCESS_EXECUTABLE_NAME = exports.ATTR_PROCESS_COMMAND_ARGS = exports.ATTR_PROCESS_COMMAND = exports.ATTR_OS_VERSION = exports.ATTR_OS_TYPE = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_CLUSTER_NAME = exports.ATTR_HOST_TYPE = exports.ATTR_HOST_NAME = exports.ATTR_HOST_IMAGE_VERSION = exports.ATTR_HOST_IMAGE_NAME = exports.ATTR_HOST_IMAGE_ID = exports.ATTR_HOST_ID = exports.ATTR_HOST_ARCH = exports.ATTR_CONTAINER_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CLOUD_REGION = exports.ATTR_CLOUD_PROVIDER = exports.ATTR_CLOUD_AVAILABILITY_ZONE = exports.ATTR_CLOUD_ACCOUNT_ID = void 0; + /** + * The cloud account ID the resource is assigned to. + * + * @example 111111111111 + * @example opentelemetry + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CLOUD_ACCOUNT_ID = "cloud.account.id"; + /** + * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. + * + * @example us-east-1c + * + * @note Availability zones are called "zones" on Alibaba Cloud and Google Cloud. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; + /** + * Name of the cloud provider. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CLOUD_PROVIDER = "cloud.provider"; + /** + * The geographical region the resource is running. + * + * @example us-central1 + * @example us-east-1 + * + * @note Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/global-infrastructure/geographies/), [Google Cloud regions](https://cloud.google.com/about/locations), or [Tencent Cloud regions](https://www.tencentcloud.com/document/product/213/6091). + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CLOUD_REGION = "cloud.region"; + /** + * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated. + * + * @example a3bf90e006b2 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CONTAINER_ID = "container.id"; + /** + * Name of the image the container was built on. + * + * @example gcr.io/opentelemetry/operator + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CONTAINER_IMAGE_NAME = "container.image.name"; + /** + * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). Should be only the `` section of the full name for example from `registry.example.com/my-org/my-image:`. + * + * @example ["v1.27.1", "3.5.7-0"] + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags"; + /** + * Container name used by container runtime. + * + * @example opentelemetry-autoconf + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_CONTAINER_NAME = "container.name"; + /** + * The CPU architecture the host system is running on. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_HOST_ARCH = "host.arch"; + /** + * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. For non-containerized systems, this should be the `machine-id`. See the table below for the sources to use to determine the `machine-id` based on operating system. + * + * @example fdbf79e8af94cb7f9e8df36789187052 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_HOST_ID = "host.id"; + /** + * VM image ID or host OS image ID. For Cloud, this value is from the provider. + * + * @example ami-07b06b442921831e5 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_HOST_IMAGE_ID = "host.image.id"; + /** + * Name of the VM image or OS install the host was instantiated from. + * + * @example infra-ami-eks-worker-node-7d4ec78312 + * @example CentOS-8-x86_64-1905 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_HOST_IMAGE_NAME = "host.image.name"; + /** + * The version string of the VM image or host OS as defined in [Version Attributes](/docs/resource/README.md#version-attributes). + * + * @example 0.1 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_HOST_IMAGE_VERSION = "host.image.version"; + /** + * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. + * + * @example opentelemetry-test + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_HOST_NAME = "host.name"; + /** + * Type of host. For Cloud, this must be the machine type. + * + * @example n1-standard-1 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_HOST_TYPE = "host.type"; + /** + * The name of the cluster. + * + * @example opentelemetry-cluster + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name"; + /** + * The name of the Deployment. + * + * @example opentelemetry + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + /** + * The name of the namespace that the pod is running in. + * + * @example default + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + /** + * The name of the Pod. + * + * @example opentelemetry-pod-autoconf + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_K8S_POD_NAME = "k8s.pod.name"; + /** + * The operating system type. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OS_TYPE = "os.type"; + /** + * The version string of the operating system as defined in [Version Attributes](/docs/resource/README.md#version-attributes). + * + * @example 14.2.1 + * @example 18.04.1 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OS_VERSION = "os.version"; + /** + * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. + * + * @example cmd/otelcol + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_COMMAND = "process.command"; + /** + * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. + * + * @example ["cmd/otecol", "--config=config.yaml"] + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_COMMAND_ARGS = "process.command_args"; + /** + * The name of the process executable. On Linux based systems, this **SHOULD** be set to the base name of the target of `/proc/[pid]/exe`. On Windows, this **SHOULD** be set to the base name of `GetProcessImageFileNameW`. + * + * @example otelcol + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_EXECUTABLE_NAME = "process.executable.name"; + /** + * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. + * + * @example /usr/bin/cmd/otelcol + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_EXECUTABLE_PATH = "process.executable.path"; + /** + * The username of the user that owns the process. + * + * @example root + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_OWNER = "process.owner"; + /** + * Process identifier (PID). + * + * @example 1234 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_PID = "process.pid"; + /** + * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. + * + * @example "Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0" + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; + /** + * The name of the runtime of this process. + * + * @example OpenJDK Runtime Environment + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name"; + /** + * The version of the runtime of this process, as returned by the runtime without modification. + * + * @example "14.0.2" + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_PROCESS_RUNTIME_VERSION = "process.runtime.version"; + /** + * The string ID of the service instance. + * + * @example 627cc493-f310-47de-96bd-71410b7dec09 + * + * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words + * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to + * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled + * service). + * + * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC + * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of + * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and + * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`. + * + * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is + * needed. Similar to what can be seen in the man page for the + * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying + * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it + * or not via another resource attribute. + * + * For applications running behind an application server (like unicorn), we do not recommend using one identifier + * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker + * thread in unicorn) to have its own instance.id. + * + * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the + * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will + * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated. + * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance + * for that telemetry. This is typically the case for scraping receivers, as they know the target address and + * port. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; + /** + * A namespace for `service.name`. + * + * @example Shop + * + * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_SERVICE_NAMESPACE = "service.namespace"; + /** + * Additional description of the web engine (e.g. detailed version and edition information). + * + * @example WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - 2.2.2.Final + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_WEBENGINE_DESCRIPTION = "webengine.description"; + /** + * The name of the web engine. + * + * @example WildFly + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_WEBENGINE_NAME = "webengine.name"; + /** + * The version of the web engine. + * + * @example 21.0.0 + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_WEBENGINE_VERSION = "webengine.version"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js +var require_execAsync = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.execAsync = void 0; + const child_process = __require("child_process"); + const util = __require("util"); + exports.execAsync = util.promisify(child_process.exec); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js +var require_getMachineId_darwin = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = void 0; + const execAsync_1 = require_execAsync(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + async function getMachineId() { + try { + const idLine = (await (0, execAsync_1.execAsync)("ioreg -rd1 -c \"IOPlatformExpertDevice\"")).stdout.split("\n").find((line) => line.includes("IOPlatformUUID")); + if (!idLine) return; + const parts = idLine.split("\" = \""); + if (parts.length === 2) return parts[1].slice(0, -1); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + } + exports.getMachineId = getMachineId; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js +var require_getMachineId_linux = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = void 0; + const fs_1$1 = __require("fs"); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + async function getMachineId() { + for (const path of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) try { + return (await fs_1$1.promises.readFile(path, { encoding: "utf8" })).trim(); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + } + exports.getMachineId = getMachineId; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js +var require_getMachineId_bsd = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = void 0; + const fs_1 = __require("fs"); + const execAsync_1 = require_execAsync(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + async function getMachineId() { + try { + return (await fs_1.promises.readFile("/etc/hostid", { encoding: "utf8" })).trim(); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + try { + return (await (0, execAsync_1.execAsync)("kenv -q smbios.system.uuid")).stdout.trim(); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + } + exports.getMachineId = getMachineId; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js +var require_getMachineId_win = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = void 0; + const process$2 = __require("process"); + const execAsync_1 = require_execAsync(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + async function getMachineId() { + const args = "QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid"; + let command = "%windir%\\System32\\REG.exe"; + if (process$2.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process$2.env) command = "%windir%\\sysnative\\cmd.exe /c " + command; + try { + const parts = (await (0, execAsync_1.execAsync)(`${command} ${args}`)).stdout.split("REG_SZ"); + if (parts.length === 2) return parts[1].trim(); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + } + exports.getMachineId = getMachineId; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js +var require_getMachineId_unsupported = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + async function getMachineId() { + api_1.diag.debug("could not read machine-id: unsupported platform"); + } + exports.getMachineId = getMachineId; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js +var require_getMachineId = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = void 0; + const process$1 = __require("process"); + let getMachineIdImpl; + async function getMachineId() { + if (!getMachineIdImpl) switch (process$1.platform) { + case "darwin": + getMachineIdImpl = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_getMachineId_darwin()))).getMachineId; + break; + case "linux": + getMachineIdImpl = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_getMachineId_linux()))).getMachineId; + break; + case "freebsd": + getMachineIdImpl = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_getMachineId_bsd()))).getMachineId; + break; + case "win32": + getMachineIdImpl = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_getMachineId_win()))).getMachineId; + break; + default: getMachineIdImpl = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_getMachineId_unsupported()))).getMachineId; + } + return getMachineIdImpl(); + } + exports.getMachineId = getMachineId; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js +var require_utils$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.normalizeType = exports.normalizeArch = void 0; + const normalizeArch = (nodeArchString) => { + switch (nodeArchString) { + case "arm": return "arm32"; + case "ppc": return "ppc32"; + case "x64": return "amd64"; + default: return nodeArchString; + } + }; + exports.normalizeArch = normalizeArch; + const normalizeType = (nodePlatform) => { + switch (nodePlatform) { + case "sunos": return "solaris"; + case "win32": return "windows"; + default: return nodePlatform; + } + }; + exports.normalizeType = normalizeType; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js +var require_HostDetector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.hostDetector = void 0; + const semconv_1 = require_semconv$2(); + const os_1$1 = __require("os"); + const getMachineId_1 = require_getMachineId(); + const utils_1 = require_utils$1(); + /** + * HostDetector detects the resources related to the host current process is + * running on. Currently only non-cloud-based attributes are included. + */ + var HostDetector = class { + detect(_config) { + return { attributes: { + [semconv_1.ATTR_HOST_NAME]: (0, os_1$1.hostname)(), + [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1$1.arch)()), + [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)() + } }; + } + }; + exports.hostDetector = new HostDetector(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js +var require_OSDetector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.osDetector = void 0; + const semconv_1 = require_semconv$2(); + const os_1 = __require("os"); + const utils_1 = require_utils$1(); + /** + * OSDetector detects the resources related to the operating system (OS) on + * which the process represented by this resource is running. + */ + var OSDetector = class { + detect(_config) { + return { attributes: { + [semconv_1.ATTR_OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()), + [semconv_1.ATTR_OS_VERSION]: (0, os_1.release)() + } }; + } + }; + exports.osDetector = new OSDetector(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js +var require_ProcessDetector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.processDetector = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const semconv_1 = require_semconv$2(); + const os = __require("os"); + /** + * ProcessDetector will be used to detect the resources related current process running + * and being instrumented from the NodeJS Process module. + */ + var ProcessDetector = class { + detect(_config) { + const attributes = { + [semconv_1.ATTR_PROCESS_PID]: process.pid, + [semconv_1.ATTR_PROCESS_EXECUTABLE_NAME]: process.title, + [semconv_1.ATTR_PROCESS_EXECUTABLE_PATH]: process.execPath, + [semconv_1.ATTR_PROCESS_COMMAND_ARGS]: [ + process.argv[0], + ...process.execArgv, + ...process.argv.slice(1) + ], + [semconv_1.ATTR_PROCESS_RUNTIME_VERSION]: process.versions.node, + [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "nodejs", + [semconv_1.ATTR_PROCESS_RUNTIME_DESCRIPTION]: "Node.js" + }; + if (process.argv.length > 1) attributes[semconv_1.ATTR_PROCESS_COMMAND] = process.argv[1]; + try { + const userInfo = os.userInfo(); + attributes[semconv_1.ATTR_PROCESS_OWNER] = userInfo.username; + } catch (e) { + api_1.diag.debug(`error obtaining process owner: ${e}`); + } + return { attributes }; + } + }; + exports.processDetector = new ProcessDetector(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js +var require_ServiceInstanceIdDetector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serviceInstanceIdDetector = void 0; + const semconv_1 = require_semconv$2(); + const crypto_1 = __require("crypto"); + /** + * ServiceInstanceIdDetector detects the resources related to the service instance ID. + */ + var ServiceInstanceIdDetector = class { + _serviceInstanceId; + detect(_config) { + if (!this._serviceInstanceId) this._serviceInstanceId = (0, crypto_1.randomUUID)(); + return { attributes: { [semconv_1.ATTR_SERVICE_INSTANCE_ID]: this._serviceInstanceId } }; + } + }; + /** + * @experimental + */ + exports.serviceInstanceIdDetector = new ServiceInstanceIdDetector(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js +var require_node$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0; + var HostDetector_1 = require_HostDetector(); + Object.defineProperty(exports, "hostDetector", { + enumerable: true, + get: function() { + return HostDetector_1.hostDetector; + } + }); + var OSDetector_1 = require_OSDetector(); + Object.defineProperty(exports, "osDetector", { + enumerable: true, + get: function() { + return OSDetector_1.osDetector; + } + }); + var ProcessDetector_1 = require_ProcessDetector(); + Object.defineProperty(exports, "processDetector", { + enumerable: true, + get: function() { + return ProcessDetector_1.processDetector; + } + }); + var ServiceInstanceIdDetector_1 = require_ServiceInstanceIdDetector(); + Object.defineProperty(exports, "serviceInstanceIdDetector", { + enumerable: true, + get: function() { + return ServiceInstanceIdDetector_1.serviceInstanceIdDetector; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js +var require_platform$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0; + var node_1 = require_node$2(); + Object.defineProperty(exports, "hostDetector", { + enumerable: true, + get: function() { + return node_1.hostDetector; + } + }); + Object.defineProperty(exports, "osDetector", { + enumerable: true, + get: function() { + return node_1.osDetector; + } + }); + Object.defineProperty(exports, "processDetector", { + enumerable: true, + get: function() { + return node_1.processDetector; + } + }); + Object.defineProperty(exports, "serviceInstanceIdDetector", { + enumerable: true, + get: function() { + return node_1.serviceInstanceIdDetector; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js +var require_NoopDetector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.noopDetector = exports.NoopDetector = void 0; + var NoopDetector = class { + detect() { + return { attributes: {} }; + } + }; + exports.NoopDetector = NoopDetector; + exports.noopDetector = new NoopDetector(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/detectors/index.js +var require_detectors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.noopDetector = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = void 0; + var EnvDetector_1 = require_EnvDetector(); + Object.defineProperty(exports, "envDetector", { + enumerable: true, + get: function() { + return EnvDetector_1.envDetector; + } + }); + var platform_1 = require_platform$2(); + Object.defineProperty(exports, "hostDetector", { + enumerable: true, + get: function() { + return platform_1.hostDetector; + } + }); + Object.defineProperty(exports, "osDetector", { + enumerable: true, + get: function() { + return platform_1.osDetector; + } + }); + Object.defineProperty(exports, "processDetector", { + enumerable: true, + get: function() { + return platform_1.processDetector; + } + }); + Object.defineProperty(exports, "serviceInstanceIdDetector", { + enumerable: true, + get: function() { + return platform_1.serviceInstanceIdDetector; + } + }); + var NoopDetector_1 = require_NoopDetector(); + Object.defineProperty(exports, "noopDetector", { + enumerable: true, + get: function() { + return NoopDetector_1.noopDetector; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+resources@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/resources/build/src/index.js +var require_src$6 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultServiceName = exports.emptyResource = exports.defaultResource = exports.resourceFromAttributes = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = exports.detectResources = void 0; + var detect_resources_1 = require_detect_resources(); + Object.defineProperty(exports, "detectResources", { + enumerable: true, + get: function() { + return detect_resources_1.detectResources; + } + }); + var detectors_1 = require_detectors(); + Object.defineProperty(exports, "envDetector", { + enumerable: true, + get: function() { + return detectors_1.envDetector; + } + }); + Object.defineProperty(exports, "hostDetector", { + enumerable: true, + get: function() { + return detectors_1.hostDetector; + } + }); + Object.defineProperty(exports, "osDetector", { + enumerable: true, + get: function() { + return detectors_1.osDetector; + } + }); + Object.defineProperty(exports, "processDetector", { + enumerable: true, + get: function() { + return detectors_1.processDetector; + } + }); + Object.defineProperty(exports, "serviceInstanceIdDetector", { + enumerable: true, + get: function() { + return detectors_1.serviceInstanceIdDetector; + } + }); + var ResourceImpl_1 = require_ResourceImpl(); + Object.defineProperty(exports, "resourceFromAttributes", { + enumerable: true, + get: function() { + return ResourceImpl_1.resourceFromAttributes; + } + }); + Object.defineProperty(exports, "defaultResource", { + enumerable: true, + get: function() { + return ResourceImpl_1.defaultResource; + } + }); + Object.defineProperty(exports, "emptyResource", { + enumerable: true, + get: function() { + return ResourceImpl_1.emptyResource; + } + }); + var default_service_name_1 = require_default_service_name(); + Object.defineProperty(exports, "defaultServiceName", { + enumerable: true, + get: function() { + return default_service_name_1.defaultServiceName; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js +var require_ViewRegistry = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ViewRegistry = void 0; + var ViewRegistry = class { + _registeredViews = []; + addView(view) { + this._registeredViews.push(view); + } + findViews(instrument, meter) { + return this._registeredViews.filter((registeredView) => { + return this._matchInstrument(registeredView.instrumentSelector, instrument) && this._matchMeter(registeredView.meterSelector, meter); + }); + } + _matchInstrument(selector, instrument) { + return (selector.getType() === void 0 || instrument.type === selector.getType()) && selector.getNameFilter().match(instrument.name) && selector.getUnitFilter().match(instrument.unit); + } + _matchMeter(selector, meter) { + return selector.getNameFilter().match(meter.name) && (meter.version === void 0 || selector.getVersionFilter().match(meter.version)) && (meter.schemaUrl === void 0 || selector.getSchemaUrlFilter().match(meter.schemaUrl)); + } + }; + exports.ViewRegistry = ViewRegistry; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js +var require_InstrumentDescriptor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isValidName = exports.isDescriptorCompatibleWith = exports.createInstrumentDescriptorWithView = exports.createInstrumentDescriptor = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const utils_1 = require_utils$3(); + function createInstrumentDescriptor(name, type, options) { + if (!isValidName(name)) api_1.diag.warn(`Invalid metric name: "${name}". The metric name should be a ASCII string with a length no greater than 255 characters.`); + return { + name, + type, + description: options?.description ?? "", + unit: options?.unit ?? "", + valueType: options?.valueType ?? api_1.ValueType.DOUBLE, + advice: options?.advice ?? {} + }; + } + exports.createInstrumentDescriptor = createInstrumentDescriptor; + function createInstrumentDescriptorWithView(view, instrument) { + return { + name: view.name ?? instrument.name, + description: view.description ?? instrument.description, + type: instrument.type, + unit: instrument.unit, + valueType: instrument.valueType, + advice: instrument.advice + }; + } + exports.createInstrumentDescriptorWithView = createInstrumentDescriptorWithView; + function isDescriptorCompatibleWith(descriptor, otherDescriptor) { + return (0, utils_1.equalsCaseInsensitive)(descriptor.name, otherDescriptor.name) && descriptor.unit === otherDescriptor.unit && descriptor.type === otherDescriptor.type && descriptor.valueType === otherDescriptor.valueType; + } + exports.isDescriptorCompatibleWith = isDescriptorCompatibleWith; + const NAME_REGEXP = /^[a-z][a-z0-9_.\-/]{0,254}$/i; + function isValidName(name) { + return NAME_REGEXP.test(name); + } + exports.isValidName = isValidName; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js +var require_Instruments = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isObservableInstrument = exports.ObservableUpDownCounterInstrument = exports.ObservableGaugeInstrument = exports.ObservableCounterInstrument = exports.ObservableInstrument = exports.HistogramInstrument = exports.GaugeInstrument = exports.CounterInstrument = exports.UpDownCounterInstrument = exports.SyncInstrument = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + var SyncInstrument = class { + _writableMetricStorage; + _descriptor; + constructor(writableMetricStorage, descriptor) { + this._writableMetricStorage = writableMetricStorage; + this._descriptor = descriptor; + } + _record(value, attributes = {}, context) { + if (typeof value !== "number") { + api_1.diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${value}`); + return; + } + if (this._descriptor.valueType === api_1.ValueType.INT && !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`); + value = Math.trunc(value); + if (!Number.isInteger(value)) return; + } + this._writableMetricStorage.record(value, attributes, context, Date.now()); + } + }; + exports.SyncInstrument = SyncInstrument; + /** + * The class implements {@link UpDownCounter} interface. + */ + var UpDownCounterInstrument = class extends SyncInstrument { + /** + * Increment value of counter by the input. Inputs may be negative. + */ + add(value, attributes, ctx) { + this._record(value, attributes, ctx); + } + }; + exports.UpDownCounterInstrument = UpDownCounterInstrument; + /** + * The class implements {@link Counter} interface. + */ + var CounterInstrument = class extends SyncInstrument { + /** + * Increment value of counter by the input. Inputs may not be negative. + */ + add(value, attributes, ctx) { + if (value < 0) { + api_1.diag.warn(`negative value provided to counter ${this._descriptor.name}: ${value}`); + return; + } + this._record(value, attributes, ctx); + } + }; + exports.CounterInstrument = CounterInstrument; + /** + * The class implements {@link Gauge} interface. + */ + var GaugeInstrument = class extends SyncInstrument { + /** + * Records a measurement. + */ + record(value, attributes, ctx) { + this._record(value, attributes, ctx); + } + }; + exports.GaugeInstrument = GaugeInstrument; + /** + * The class implements {@link Histogram} interface. + */ + var HistogramInstrument = class extends SyncInstrument { + /** + * Records a measurement. Value of the measurement must not be negative. + */ + record(value, attributes, ctx) { + if (value < 0) { + api_1.diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${value}`); + return; + } + this._record(value, attributes, ctx); + } + }; + exports.HistogramInstrument = HistogramInstrument; + var ObservableInstrument = class { + /** @internal */ + _metricStorages; + /** @internal */ + _descriptor; + _observableRegistry; + constructor(descriptor, metricStorages, observableRegistry) { + this._descriptor = descriptor; + this._metricStorages = metricStorages; + this._observableRegistry = observableRegistry; + } + /** + * @see {Observable.addCallback} + */ + addCallback(callback) { + this._observableRegistry.addCallback(callback, this); + } + /** + * @see {Observable.removeCallback} + */ + removeCallback(callback) { + this._observableRegistry.removeCallback(callback, this); + } + }; + exports.ObservableInstrument = ObservableInstrument; + var ObservableCounterInstrument = class extends ObservableInstrument {}; + exports.ObservableCounterInstrument = ObservableCounterInstrument; + var ObservableGaugeInstrument = class extends ObservableInstrument {}; + exports.ObservableGaugeInstrument = ObservableGaugeInstrument; + var ObservableUpDownCounterInstrument = class extends ObservableInstrument {}; + exports.ObservableUpDownCounterInstrument = ObservableUpDownCounterInstrument; + function isObservableInstrument(it) { + return it instanceof ObservableInstrument; + } + exports.isObservableInstrument = isObservableInstrument; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js +var require_Meter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Meter = void 0; + const InstrumentDescriptor_1 = require_InstrumentDescriptor(); + const Instruments_1 = require_Instruments(); + const MetricData_1 = require_MetricData(); + /** + * This class implements the {@link IMeter} interface. + */ + var Meter = class { + _meterSharedState; + constructor(meterSharedState) { + this._meterSharedState = meterSharedState; + } + /** + * Create a {@link Gauge} instrument. + */ + createGauge(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.GAUGE, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.GaugeInstrument(storage, descriptor); + } + /** + * Create a {@link Histogram} instrument. + */ + createHistogram(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.HISTOGRAM, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.HistogramInstrument(storage, descriptor); + } + /** + * Create a {@link Counter} instrument. + */ + createCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.COUNTER, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.CounterInstrument(storage, descriptor); + } + /** + * Create a {@link UpDownCounter} instrument. + */ + createUpDownCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.UP_DOWN_COUNTER, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.UpDownCounterInstrument(storage, descriptor); + } + /** + * Create a {@link ObservableGauge} instrument. + */ + createObservableGauge(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_GAUGE, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableGaugeInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + /** + * Create a {@link ObservableCounter} instrument. + */ + createObservableCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_COUNTER, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + /** + * Create a {@link ObservableUpDownCounter} instrument. + */ + createObservableUpDownCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableUpDownCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(callback, observables) { + this._meterSharedState.observableRegistry.addBatchCallback(callback, observables); + } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(callback, observables) { + this._meterSharedState.observableRegistry.removeBatchCallback(callback, observables); + } + }; + exports.Meter = Meter; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js +var require_MetricStorage = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricStorage = void 0; + const InstrumentDescriptor_1 = require_InstrumentDescriptor(); + /** + * Internal interface. + * + * Represents a storage from which we can collect metrics. + */ + var MetricStorage = class { + _instrumentDescriptor; + constructor(instrumentDescriptor) { + this._instrumentDescriptor = instrumentDescriptor; + } + getInstrumentDescriptor() { + return this._instrumentDescriptor; + } + updateDescription(description) { + this._instrumentDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(this._instrumentDescriptor.name, this._instrumentDescriptor.type, { + description, + valueType: this._instrumentDescriptor.valueType, + unit: this._instrumentDescriptor.unit, + advice: this._instrumentDescriptor.advice + }); + } + }; + exports.MetricStorage = MetricStorage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js +var require_HashMap = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AttributeHashMap = exports.HashMap = void 0; + const utils_1 = require_utils$3(); + var HashMap = class { + _valueMap = /* @__PURE__ */ new Map(); + _keyMap = /* @__PURE__ */ new Map(); + _hash; + constructor(hash) { + this._hash = hash; + } + get(key, hashCode) { + hashCode ??= this._hash(key); + return this._valueMap.get(hashCode); + } + getOrDefault(key, defaultFactory) { + const hash = this._hash(key); + if (this._valueMap.has(hash)) return this._valueMap.get(hash); + const val = defaultFactory(); + if (!this._keyMap.has(hash)) this._keyMap.set(hash, key); + this._valueMap.set(hash, val); + return val; + } + set(key, value, hashCode) { + hashCode ??= this._hash(key); + if (!this._keyMap.has(hashCode)) this._keyMap.set(hashCode, key); + this._valueMap.set(hashCode, value); + } + has(key, hashCode) { + hashCode ??= this._hash(key); + return this._valueMap.has(hashCode); + } + *keys() { + const keyIterator = this._keyMap.entries(); + let next = keyIterator.next(); + while (next.done !== true) { + yield [next.value[1], next.value[0]]; + next = keyIterator.next(); + } + } + *entries() { + const valueIterator = this._valueMap.entries(); + let next = valueIterator.next(); + while (next.done !== true) { + yield [ + this._keyMap.get(next.value[0]), + next.value[1], + next.value[0] + ]; + next = valueIterator.next(); + } + } + get size() { + return this._valueMap.size; + } + }; + exports.HashMap = HashMap; + var AttributeHashMap = class extends HashMap { + constructor() { + super(utils_1.hashAttributes); + } + }; + exports.AttributeHashMap = AttributeHashMap; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js +var require_DeltaMetricProcessor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeltaMetricProcessor = void 0; + const core_1 = require_src$8(); + const utils_1 = require_utils$3(); + const HashMap_1 = require_HashMap(); + /** + * Internal interface. + * + * Allows synchronous collection of metrics. This processor should allow + * allocation of new aggregation cells for metrics and convert cumulative + * recording to delta data points. + */ + var DeltaMetricProcessor = class { + _activeCollectionStorage = new HashMap_1.AttributeHashMap(); + _cumulativeMemoStorage = new HashMap_1.AttributeHashMap(); + _cardinalityLimit; + _overflowAttributes = { "otel.metric.overflow": true }; + _overflowHashCode; + _aggregator; + constructor(aggregator, aggregationCardinalityLimit) { + this._aggregator = aggregator; + this._cardinalityLimit = (aggregationCardinalityLimit ?? 2e3) - 1; + this._overflowHashCode = (0, utils_1.hashAttributes)(this._overflowAttributes); + } + record(value, attributes, collectionTime) { + let accumulation = this._activeCollectionStorage.get(attributes); + if (!accumulation) { + const hrTime = (0, core_1.millisToHrTime)(collectionTime); + if (this._activeCollectionStorage.size >= this._cardinalityLimit) { + this._activeCollectionStorage.getOrDefault(this._overflowAttributes, () => this._aggregator.createAccumulation(hrTime))?.record(value); + return; + } + accumulation = this._aggregator.createAccumulation(hrTime); + this._activeCollectionStorage.set(attributes, accumulation); + } + accumulation?.record(value); + } + batchCumulate(measurements, collectionTime) { + for (const [originalAttributes, value, originalHashCode] of measurements.entries()) { + let attributes = originalAttributes; + let hashCode = originalHashCode; + const accumulation = this._aggregator.createAccumulation(collectionTime); + accumulation?.record(value); + let delta = accumulation; + if (this._cumulativeMemoStorage.has(attributes, hashCode)) { + const previous = this._cumulativeMemoStorage.get(attributes, hashCode); + delta = this._aggregator.diff(previous, accumulation); + } else if (this._cumulativeMemoStorage.size >= this._cardinalityLimit) { + attributes = this._overflowAttributes; + hashCode = this._overflowHashCode; + if (this._cumulativeMemoStorage.has(attributes, hashCode)) { + const previous = this._cumulativeMemoStorage.get(attributes, hashCode); + delta = this._aggregator.diff(previous, accumulation); + } + } + if (this._activeCollectionStorage.has(attributes, hashCode)) { + const active = this._activeCollectionStorage.get(attributes, hashCode); + delta = this._aggregator.merge(active, delta); + } + this._cumulativeMemoStorage.set(attributes, accumulation, hashCode); + this._activeCollectionStorage.set(attributes, delta, hashCode); + } + } + /** + * Returns a collection of delta metrics. Start time is the when first + * time event collected. + */ + collect() { + const unreportedDelta = this._activeCollectionStorage; + this._activeCollectionStorage = new HashMap_1.AttributeHashMap(); + return unreportedDelta; + } + }; + exports.DeltaMetricProcessor = DeltaMetricProcessor; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js +var require_TemporalMetricProcessor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TemporalMetricProcessor = void 0; + const AggregationTemporality_1 = require_AggregationTemporality(); + const HashMap_1 = require_HashMap(); + /** + * Internal interface. + * + * Provides unique reporting for each collector. Allows synchronous collection + * of metrics and reports given temporality values. + */ + var TemporalMetricProcessor = class TemporalMetricProcessor { + _aggregator; + _unreportedAccumulations = /* @__PURE__ */ new Map(); + _reportHistory = /* @__PURE__ */ new Map(); + constructor(aggregator, collectorHandles) { + this._aggregator = aggregator; + collectorHandles.forEach((handle) => { + this._unreportedAccumulations.set(handle, []); + }); + } + /** + * Builds the {@link MetricData} streams to report against a specific MetricCollector. + * @param collector The information of the MetricCollector. + * @param collectors The registered collectors. + * @param instrumentDescriptor The instrumentation descriptor that these metrics generated with. + * @param currentAccumulations The current accumulation of metric data from instruments. + * @param collectionTime The current collection timestamp. + * @returns The {@link MetricData} points or `null`. + */ + buildMetrics(collector, instrumentDescriptor, currentAccumulations, collectionTime) { + this._stashAccumulations(currentAccumulations); + const unreportedAccumulations = this._getMergedUnreportedAccumulations(collector); + let result = unreportedAccumulations; + let aggregationTemporality; + if (this._reportHistory.has(collector)) { + const last = this._reportHistory.get(collector); + const lastCollectionTime = last.collectionTime; + aggregationTemporality = last.aggregationTemporality; + if (aggregationTemporality === AggregationTemporality_1.AggregationTemporality.CUMULATIVE) result = TemporalMetricProcessor.merge(last.accumulations, unreportedAccumulations, this._aggregator); + else result = TemporalMetricProcessor.calibrateStartTime(last.accumulations, unreportedAccumulations, lastCollectionTime); + } else aggregationTemporality = collector.selectAggregationTemporality(instrumentDescriptor.type); + this._reportHistory.set(collector, { + accumulations: result, + collectionTime, + aggregationTemporality + }); + const accumulationRecords = AttributesMapToAccumulationRecords(result); + if (accumulationRecords.length === 0) return; + return this._aggregator.toMetricData(instrumentDescriptor, aggregationTemporality, accumulationRecords, collectionTime); + } + _stashAccumulations(currentAccumulation) { + const registeredCollectors = this._unreportedAccumulations.keys(); + for (const collector of registeredCollectors) { + let stash = this._unreportedAccumulations.get(collector); + if (stash === void 0) { + stash = []; + this._unreportedAccumulations.set(collector, stash); + } + stash.push(currentAccumulation); + } + } + _getMergedUnreportedAccumulations(collector) { + let result = new HashMap_1.AttributeHashMap(); + const unreportedList = this._unreportedAccumulations.get(collector); + this._unreportedAccumulations.set(collector, []); + if (unreportedList === void 0) return result; + for (const it of unreportedList) result = TemporalMetricProcessor.merge(result, it, this._aggregator); + return result; + } + static merge(last, current, aggregator) { + const result = last; + const iterator = current.entries(); + let next = iterator.next(); + while (next.done !== true) { + const [key, record, hash] = next.value; + if (last.has(key, hash)) { + const lastAccumulation = last.get(key, hash); + const accumulation = aggregator.merge(lastAccumulation, record); + result.set(key, accumulation, hash); + } else result.set(key, record, hash); + next = iterator.next(); + } + return result; + } + /** + * Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves + * the new stream to be the initial observation time unchanged. + */ + static calibrateStartTime(last, current, lastCollectionTime) { + for (const [key, hash] of last.keys()) current.get(key, hash)?.setStartTime(lastCollectionTime); + return current; + } + }; + exports.TemporalMetricProcessor = TemporalMetricProcessor; + function AttributesMapToAccumulationRecords(map) { + return Array.from(map.entries()); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js +var require_AsyncMetricStorage = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncMetricStorage = void 0; + const MetricStorage_1 = require_MetricStorage(); + const DeltaMetricProcessor_1 = require_DeltaMetricProcessor(); + const TemporalMetricProcessor_1 = require_TemporalMetricProcessor(); + const HashMap_1 = require_HashMap(); + /** + * Internal interface. + * + * Stores and aggregates {@link MetricData} for asynchronous instruments. + */ + var AsyncMetricStorage = class extends MetricStorage_1.MetricStorage { + _aggregationCardinalityLimit; + _deltaMetricStorage; + _temporalMetricStorage; + _attributesProcessor; + constructor(_instrumentDescriptor, aggregator, attributesProcessor, collectorHandles, aggregationCardinalityLimit) { + super(_instrumentDescriptor); + this._aggregationCardinalityLimit = aggregationCardinalityLimit; + this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); + this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); + this._attributesProcessor = attributesProcessor; + } + record(measurements, observationTime) { + if (this._attributesProcessor === void 0) { + this._deltaMetricStorage.batchCumulate(measurements, observationTime); + return; + } + const processed = new HashMap_1.AttributeHashMap(); + for (const [attributes, value] of measurements.entries()) processed.set(this._attributesProcessor.process(attributes), value); + this._deltaMetricStorage.batchCumulate(processed, observationTime); + } + /** + * Collects the metrics from this storage. The ObservableCallback is invoked + * during the collection. + * + * Note: This is a stateful operation and may reset any interval-related + * state for the MetricCollector. + */ + collect(collector, collectionTime) { + const accumulations = this._deltaMetricStorage.collect(); + return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); + } + }; + exports.AsyncMetricStorage = AsyncMetricStorage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js +var require_RegistrationConflicts = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getConflictResolutionRecipe = exports.getDescriptionResolutionRecipe = exports.getTypeConflictResolutionRecipe = exports.getUnitConflictResolutionRecipe = exports.getValueTypeConflictResolutionRecipe = exports.getIncompatibilityDetails = void 0; + function getIncompatibilityDetails(existing, otherDescriptor) { + let incompatibility = ""; + if (existing.unit !== otherDescriptor.unit) incompatibility += `\t- Unit '${existing.unit}' does not match '${otherDescriptor.unit}'\n`; + if (existing.type !== otherDescriptor.type) incompatibility += `\t- Type '${existing.type}' does not match '${otherDescriptor.type}'\n`; + if (existing.valueType !== otherDescriptor.valueType) incompatibility += `\t- Value Type '${existing.valueType}' does not match '${otherDescriptor.valueType}'\n`; + if (existing.description !== otherDescriptor.description) incompatibility += `\t- Description '${existing.description}' does not match '${otherDescriptor.description}'\n`; + return incompatibility; + } + exports.getIncompatibilityDetails = getIncompatibilityDetails; + function getValueTypeConflictResolutionRecipe(existing, otherDescriptor) { + return `\t- use valueType '${existing.valueType}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; + } + exports.getValueTypeConflictResolutionRecipe = getValueTypeConflictResolutionRecipe; + function getUnitConflictResolutionRecipe(existing, otherDescriptor) { + return `\t- use unit '${existing.unit}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; + } + exports.getUnitConflictResolutionRecipe = getUnitConflictResolutionRecipe; + function getTypeConflictResolutionRecipe(existing, otherDescriptor) { + const selector = { + name: otherDescriptor.name, + type: otherDescriptor.type, + unit: otherDescriptor.unit + }; + const selectorString = JSON.stringify(selector); + return `\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'`; + } + exports.getTypeConflictResolutionRecipe = getTypeConflictResolutionRecipe; + function getDescriptionResolutionRecipe(existing, otherDescriptor) { + const selector = { + name: otherDescriptor.name, + type: otherDescriptor.type, + unit: otherDescriptor.unit + }; + const selectorString = JSON.stringify(selector); + return `\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}' + \t- OR - create a new view with the name ${existing.name} and description '${existing.description}' and InstrumentSelector ${selectorString} + \t- OR - create a new view with the name ${otherDescriptor.name} and description '${existing.description}' and InstrumentSelector ${selectorString}`; + } + exports.getDescriptionResolutionRecipe = getDescriptionResolutionRecipe; + function getConflictResolutionRecipe(existing, otherDescriptor) { + if (existing.valueType !== otherDescriptor.valueType) return getValueTypeConflictResolutionRecipe(existing, otherDescriptor); + if (existing.unit !== otherDescriptor.unit) return getUnitConflictResolutionRecipe(existing, otherDescriptor); + if (existing.type !== otherDescriptor.type) return getTypeConflictResolutionRecipe(existing, otherDescriptor); + if (existing.description !== otherDescriptor.description) return getDescriptionResolutionRecipe(existing, otherDescriptor); + return ""; + } + exports.getConflictResolutionRecipe = getConflictResolutionRecipe; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js +var require_MetricStorageRegistry = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricStorageRegistry = void 0; + const InstrumentDescriptor_1 = require_InstrumentDescriptor(); + const api = (init_esm$2(), __toCommonJS(esm_exports$2)); + const RegistrationConflicts_1 = require_RegistrationConflicts(); + /** + * Internal class for storing {@link MetricStorage} + */ + var MetricStorageRegistry = class MetricStorageRegistry { + _sharedRegistry = /* @__PURE__ */ new Map(); + _perCollectorRegistry = /* @__PURE__ */ new Map(); + static create() { + return new MetricStorageRegistry(); + } + getStorages(collector) { + let storages = []; + for (const metricStorages of this._sharedRegistry.values()) storages = storages.concat(metricStorages); + const perCollectorStorages = this._perCollectorRegistry.get(collector); + if (perCollectorStorages != null) for (const metricStorages of perCollectorStorages.values()) storages = storages.concat(metricStorages); + return storages; + } + register(storage) { + this._registerStorage(storage, this._sharedRegistry); + } + registerForCollector(collector, storage) { + let storageMap = this._perCollectorRegistry.get(collector); + if (storageMap == null) { + storageMap = /* @__PURE__ */ new Map(); + this._perCollectorRegistry.set(collector, storageMap); + } + this._registerStorage(storage, storageMap); + } + findOrUpdateCompatibleStorage(expectedDescriptor) { + const storages = this._sharedRegistry.get(expectedDescriptor.name); + if (storages === void 0) return null; + return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); + } + findOrUpdateCompatibleCollectorStorage(collector, expectedDescriptor) { + const storageMap = this._perCollectorRegistry.get(collector); + if (storageMap === void 0) return null; + const storages = storageMap.get(expectedDescriptor.name); + if (storages === void 0) return null; + return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); + } + _registerStorage(storage, storageMap) { + const descriptor = storage.getInstrumentDescriptor(); + const storages = storageMap.get(descriptor.name); + if (storages === void 0) { + storageMap.set(descriptor.name, [storage]); + return; + } + storages.push(storage); + } + _findOrUpdateCompatibleStorage(expectedDescriptor, existingStorages) { + let compatibleStorage = null; + for (const existingStorage of existingStorages) { + const existingDescriptor = existingStorage.getInstrumentDescriptor(); + if ((0, InstrumentDescriptor_1.isDescriptorCompatibleWith)(existingDescriptor, expectedDescriptor)) { + if (existingDescriptor.description !== expectedDescriptor.description) { + if (expectedDescriptor.description.length > existingDescriptor.description.length) existingStorage.updateDescription(expectedDescriptor.description); + api.diag.warn("A view or instrument with the name ", expectedDescriptor.name, " has already been registered, but has a different description and is incompatible with another registered view.\n", "Details:\n", (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), "The longer description will be used.\nTo resolve the conflict:", (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); + } + compatibleStorage = existingStorage; + } else api.diag.warn("A view or instrument with the name ", expectedDescriptor.name, " has already been registered and is incompatible with another registered view.\n", "Details:\n", (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), "To resolve the conflict:\n", (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); + } + return compatibleStorage; + } + }; + exports.MetricStorageRegistry = MetricStorageRegistry; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js +var require_MultiWritableMetricStorage = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MultiMetricStorage = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + /** + * Internal interface. + */ + var MultiMetricStorage = class { + _backingStorages; + hasAttributeProcessor; + constructor(backingStorages) { + this._backingStorages = backingStorages; + this.hasAttributeProcessor = backingStorages.some((s) => s.hasAttributeProcessor); + } + record(value, attributes, context, recordTime) { + if (this.hasAttributeProcessor && context === void 0) context = api_1.context.active(); + const storages = this._backingStorages; + for (let i = 0; i < storages.length; i++) storages[i].record(value, attributes, context, recordTime); + } + }; + exports.MultiMetricStorage = MultiMetricStorage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js +var require_ObservableResult = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchObservableResultImpl = exports.ObservableResultImpl = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const HashMap_1 = require_HashMap(); + const Instruments_1 = require_Instruments(); + /** + * The class implements {@link ObservableResult} interface. + */ + var ObservableResultImpl = class { + /** + * @internal + */ + _buffer = new HashMap_1.AttributeHashMap(); + _instrumentName; + _valueType; + constructor(instrumentName, valueType) { + this._instrumentName = instrumentName; + this._valueType = valueType; + } + /** + * Observe a measurement of the value associated with the given attributes. + */ + observe(value, attributes = {}) { + if (typeof value !== "number") { + api_1.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${value}`); + return; + } + if (this._valueType === api_1.ValueType.INT && !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`); + value = Math.trunc(value); + if (!Number.isInteger(value)) return; + } + this._buffer.set(attributes, value); + } + }; + exports.ObservableResultImpl = ObservableResultImpl; + /** + * The class implements {@link BatchObservableCallback} interface. + */ + var BatchObservableResultImpl = class { + /** + * @internal + */ + _buffer = /* @__PURE__ */ new Map(); + /** + * Observe a measurement of the value associated with the given attributes. + */ + observe(metric, value, attributes = {}) { + if (!(0, Instruments_1.isObservableInstrument)(metric)) return; + let map = this._buffer.get(metric); + if (map == null) { + map = new HashMap_1.AttributeHashMap(); + this._buffer.set(metric, map); + } + if (typeof value !== "number") { + api_1.diag.warn(`non-number value provided to metric ${metric._descriptor.name}: ${value}`); + return; + } + if (metric._descriptor.valueType === api_1.ValueType.INT && !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${metric._descriptor.name}, ignoring the fractional digits.`); + value = Math.trunc(value); + if (!Number.isInteger(value)) return; + } + map.set(attributes, value); + } + }; + exports.BatchObservableResultImpl = BatchObservableResultImpl; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js +var require_ObservableRegistry = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ObservableRegistry = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const Instruments_1 = require_Instruments(); + const ObservableResult_1 = require_ObservableResult(); + const utils_1 = require_utils$3(); + /** + * An internal interface for managing ObservableCallbacks. + * + * Every registered callback associated with a set of instruments are be evaluated + * exactly once during collection prior to reading data for that instrument. + */ + var ObservableRegistry = class { + _callbacks = []; + _batchCallbacks = []; + addCallback(callback, instrument) { + if (this._findCallback(callback, instrument) >= 0) return; + this._callbacks.push({ + callback, + instrument + }); + } + removeCallback(callback, instrument) { + const idx = this._findCallback(callback, instrument); + if (idx < 0) return; + this._callbacks.splice(idx, 1); + } + addBatchCallback(callback, instruments) { + const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); + if (observableInstruments.size === 0) { + api_1.diag.error("BatchObservableCallback is not associated with valid instruments", instruments); + return; + } + if (this._findBatchCallback(callback, observableInstruments) >= 0) return; + this._batchCallbacks.push({ + callback, + instruments: observableInstruments + }); + } + removeBatchCallback(callback, instruments) { + const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); + const idx = this._findBatchCallback(callback, observableInstruments); + if (idx < 0) return; + this._batchCallbacks.splice(idx, 1); + } + /** + * @returns a promise of rejected reasons for invoking callbacks. + */ + async observe(collectionTime, timeoutMillis) { + const callbackFutures = this._observeCallbacks(collectionTime, timeoutMillis); + const batchCallbackFutures = this._observeBatchCallbacks(collectionTime, timeoutMillis); + return (await Promise.allSettled([...callbackFutures, ...batchCallbackFutures])).filter((result) => result.status === "rejected").map((result) => result.reason); + } + _observeCallbacks(observationTime, timeoutMillis) { + return this._callbacks.map(async ({ callback, instrument }) => { + const observableResult = new ObservableResult_1.ObservableResultImpl(instrument._descriptor.name, instrument._descriptor.valueType); + let callPromise = Promise.resolve(callback(observableResult)); + if (timeoutMillis != null) callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); + await callPromise; + instrument._metricStorages.forEach((metricStorage) => { + metricStorage.record(observableResult._buffer, observationTime); + }); + }); + } + _observeBatchCallbacks(observationTime, timeoutMillis) { + return this._batchCallbacks.map(async ({ callback, instruments }) => { + const observableResult = new ObservableResult_1.BatchObservableResultImpl(); + let callPromise = Promise.resolve(callback(observableResult)); + if (timeoutMillis != null) callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); + await callPromise; + instruments.forEach((instrument) => { + const buffer = observableResult._buffer.get(instrument); + if (buffer == null) return; + instrument._metricStorages.forEach((metricStorage) => { + metricStorage.record(buffer, observationTime); + }); + }); + }); + } + _findCallback(callback, instrument) { + return this._callbacks.findIndex((record) => { + return record.callback === callback && record.instrument === instrument; + }); + } + _findBatchCallback(callback, instruments) { + return this._batchCallbacks.findIndex((record) => { + return record.callback === callback && (0, utils_1.setEquals)(record.instruments, instruments); + }); + } + }; + exports.ObservableRegistry = ObservableRegistry; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js +var require_SyncMetricStorage = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SyncMetricStorage = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const MetricStorage_1 = require_MetricStorage(); + const DeltaMetricProcessor_1 = require_DeltaMetricProcessor(); + const TemporalMetricProcessor_1 = require_TemporalMetricProcessor(); + /** + * Internal interface. + * + * Stores and aggregates {@link MetricData} for synchronous instruments. + */ + var SyncMetricStorage = class extends MetricStorage_1.MetricStorage { + _aggregationCardinalityLimit; + _deltaMetricStorage; + _temporalMetricStorage; + _attributesProcessor; + constructor(instrumentDescriptor, aggregator, attributesProcessor, collectorHandles, aggregationCardinalityLimit) { + super(instrumentDescriptor); + this._aggregationCardinalityLimit = aggregationCardinalityLimit; + this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); + this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); + this._attributesProcessor = attributesProcessor; + this.hasAttributeProcessor = attributesProcessor !== void 0; + } + hasAttributeProcessor; + record(value, attributes, context, recordTime) { + if (this._attributesProcessor !== void 0) attributes = this._attributesProcessor.process(attributes, context ?? api_1.context.active()); + this._deltaMetricStorage.record(value, attributes, recordTime); + } + /** + * Collects the metrics from this storage. + * + * Note: This is a stateful operation and may reset any interval-related + * state for the MetricCollector. + */ + collect(collector, collectionTime) { + const accumulations = this._deltaMetricStorage.collect(); + return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); + } + }; + exports.SyncMetricStorage = SyncMetricStorage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js +var require_MeterSharedState = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterSharedState = void 0; + const InstrumentDescriptor_1 = require_InstrumentDescriptor(); + const Meter_1 = require_Meter(); + const AsyncMetricStorage_1 = require_AsyncMetricStorage(); + const MetricStorageRegistry_1 = require_MetricStorageRegistry(); + const MultiWritableMetricStorage_1 = require_MultiWritableMetricStorage(); + const ObservableRegistry_1 = require_ObservableRegistry(); + const SyncMetricStorage_1 = require_SyncMetricStorage(); + /** + * An internal record for shared meter provider states. + */ + var MeterSharedState = class { + metricStorageRegistry = new MetricStorageRegistry_1.MetricStorageRegistry(); + observableRegistry = new ObservableRegistry_1.ObservableRegistry(); + meter; + _meterProviderSharedState; + _instrumentationScope; + constructor(meterProviderSharedState, instrumentationScope) { + this.meter = new Meter_1.Meter(this); + this._meterProviderSharedState = meterProviderSharedState; + this._instrumentationScope = instrumentationScope; + } + registerMetricStorage(descriptor) { + const storages = this._registerMetricStorage(descriptor, SyncMetricStorage_1.SyncMetricStorage); + if (storages.length === 1) return storages[0]; + return new MultiWritableMetricStorage_1.MultiMetricStorage(storages); + } + registerAsyncMetricStorage(descriptor) { + return this._registerMetricStorage(descriptor, AsyncMetricStorage_1.AsyncMetricStorage); + } + /** + * @param collector opaque handle of {@link MetricCollector} which initiated the collection. + * @param collectionTime the HrTime at which the collection was initiated. + * @param options options for collection. + * @returns the list of metric data collected. + */ + async collect(collector, collectionTime, options) { + /** + * 1. Call all observable callbacks first. + * 2. Collect metric result for the collector. + */ + const errors = await this.observableRegistry.observe(collectionTime, options?.timeoutMillis); + const storages = this.metricStorageRegistry.getStorages(collector); + if (storages.length === 0) return null; + const metricDataList = []; + storages.forEach((metricStorage) => { + const metricData = metricStorage.collect(collector, collectionTime); + if (metricData != null) metricDataList.push(metricData); + }); + if (metricDataList.length === 0) return { errors }; + return { + scopeMetrics: { + scope: this._instrumentationScope, + metrics: metricDataList + }, + errors + }; + } + _registerMetricStorage(descriptor, MetricStorageType) { + let storages = this._meterProviderSharedState.viewRegistry.findViews(descriptor, this._instrumentationScope).map((view) => { + const viewDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptorWithView)(view, descriptor); + const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor); + if (compatibleStorage != null) return compatibleStorage; + const viewStorage = new MetricStorageType(viewDescriptor, view.aggregation.createAggregator(viewDescriptor), view.attributesProcessor, this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit); + this.metricStorageRegistry.register(viewStorage); + return viewStorage; + }); + if (storages.length === 0) { + const collectorStorages = this._meterProviderSharedState.selectAggregations(descriptor.type).map(([collector, aggregation]) => { + const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(collector, descriptor); + if (compatibleStorage != null) return compatibleStorage; + const aggregator = aggregation.createAggregator(descriptor); + const cardinalityLimit = collector.selectCardinalityLimit(descriptor.type); + const storage = new MetricStorageType(descriptor, aggregator, void 0, [collector], cardinalityLimit); + this.metricStorageRegistry.registerForCollector(collector, storage); + return storage; + }); + storages = storages.concat(collectorStorages); + } + return storages; + } + }; + exports.MeterSharedState = MeterSharedState; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js +var require_MeterProviderSharedState = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterProviderSharedState = void 0; + const utils_1 = require_utils$3(); + const ViewRegistry_1 = require_ViewRegistry(); + const MeterSharedState_1 = require_MeterSharedState(); + const AggregationOption_1 = require_AggregationOption(); + /** + * An internal record for shared meter provider states. + */ + var MeterProviderSharedState = class { + viewRegistry = new ViewRegistry_1.ViewRegistry(); + metricCollectors = []; + meterSharedStates = /* @__PURE__ */ new Map(); + resource; + constructor(resource) { + this.resource = resource; + } + getMeterSharedState(instrumentationScope) { + const id = (0, utils_1.instrumentationScopeId)(instrumentationScope); + let meterSharedState = this.meterSharedStates.get(id); + if (meterSharedState == null) { + meterSharedState = new MeterSharedState_1.MeterSharedState(this, instrumentationScope); + this.meterSharedStates.set(id, meterSharedState); + } + return meterSharedState; + } + selectAggregations(instrumentType) { + const result = []; + for (const collector of this.metricCollectors) result.push([collector, (0, AggregationOption_1.toAggregation)(collector.selectAggregation(instrumentType))]); + return result; + } + }; + exports.MeterProviderSharedState = MeterProviderSharedState; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js +var require_MetricCollector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricCollector = void 0; + const core_1 = require_src$8(); + /** + * An internal opaque interface that the MetricReader receives as + * MetricProducer. It acts as the storage key to the internal metric stream + * state for each MetricReader. + */ + var MetricCollector = class { + _sharedState; + _metricReader; + constructor(sharedState, metricReader) { + this._sharedState = sharedState; + this._metricReader = metricReader; + } + async collect(options) { + const collectionTime = (0, core_1.millisToHrTime)(Date.now()); + const scopeMetrics = []; + const errors = []; + const meterCollectionPromises = Array.from(this._sharedState.meterSharedStates.values()).map(async (meterSharedState) => { + const current = await meterSharedState.collect(this, collectionTime, options); + if (current?.scopeMetrics != null) scopeMetrics.push(current.scopeMetrics); + if (current?.errors != null) errors.push(...current.errors); + }); + await Promise.all(meterCollectionPromises); + return { + resourceMetrics: { + resource: this._sharedState.resource, + scopeMetrics + }, + errors + }; + } + /** + * Delegates for MetricReader.forceFlush. + */ + async forceFlush(options) { + await this._metricReader.forceFlush(options); + } + /** + * Delegates for MetricReader.shutdown. + */ + async shutdown(options) { + await this._metricReader.shutdown(options); + } + selectAggregationTemporality(instrumentType) { + return this._metricReader.selectAggregationTemporality(instrumentType); + } + selectAggregation(instrumentType) { + return this._metricReader.selectAggregation(instrumentType); + } + /** + * Select the cardinality limit for the given {@link InstrumentType} for this + * collector. + */ + selectCardinalityLimit(instrumentType) { + return this._metricReader.selectCardinalityLimit?.(instrumentType) ?? 2e3; + } + }; + exports.MetricCollector = MetricCollector; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js +var require_Predicate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExactPredicate = exports.PatternPredicate = void 0; + const ESCAPE = /[\^$\\.+?()[\]{}|]/g; + /** + * Wildcard pattern predicate, supports patterns like `*`, `foo*`, `*bar`. + */ + var PatternPredicate = class PatternPredicate { + _matchAll; + _regexp; + constructor(pattern) { + if (pattern === "*") { + this._matchAll = true; + this._regexp = /.*/; + } else { + this._matchAll = false; + this._regexp = new RegExp(PatternPredicate.escapePattern(pattern)); + } + } + match(str) { + if (this._matchAll) return true; + return this._regexp.test(str); + } + static escapePattern(pattern) { + return `^${pattern.replace(ESCAPE, "\\$&").replace("*", ".*")}$`; + } + static hasWildcard(pattern) { + return pattern.includes("*"); + } + }; + exports.PatternPredicate = PatternPredicate; + var ExactPredicate = class { + _matchAll; + _pattern; + constructor(pattern) { + this._matchAll = pattern === void 0; + this._pattern = pattern; + } + match(str) { + if (this._matchAll) return true; + if (str === this._pattern) return true; + return false; + } + }; + exports.ExactPredicate = ExactPredicate; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js +var require_AttributesProcessor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.createMultiAttributesProcessor = exports.createNoopAttributesProcessor = void 0; + var NoopAttributesProcessor = class { + process(incoming, _context) { + return incoming; + } + }; + var MultiAttributesProcessor = class { + _processors; + constructor(processors) { + this._processors = processors; + } + process(incoming, context) { + let filteredAttributes = incoming; + for (const processor of this._processors) filteredAttributes = processor.process(filteredAttributes, context); + return filteredAttributes; + } + }; + var AllowListProcessor = class { + _allowedAttributeNames; + constructor(allowedAttributeNames) { + this._allowedAttributeNames = new Set(allowedAttributeNames); + } + process(incoming, _context) { + const filteredAttributes = {}; + for (const attributeName in incoming) if (Object.prototype.hasOwnProperty.call(incoming, attributeName) && this._allowedAttributeNames.has(attributeName)) filteredAttributes[attributeName] = incoming[attributeName]; + return filteredAttributes; + } + }; + var DenyListProcessor = class { + _deniedAttributeNames; + constructor(deniedAttributeNames) { + this._deniedAttributeNames = new Set(deniedAttributeNames); + } + process(incoming, _context) { + const filteredAttributes = {}; + for (const attributeName in incoming) if (Object.prototype.hasOwnProperty.call(incoming, attributeName) && !this._deniedAttributeNames.has(attributeName)) filteredAttributes[attributeName] = incoming[attributeName]; + return filteredAttributes; + } + }; + /** + * @internal + * + * Create an {@link IAttributesProcessor} that acts as a simple pass-through for attributes. + */ + function createNoopAttributesProcessor() { + return NOOP; + } + exports.createNoopAttributesProcessor = createNoopAttributesProcessor; + /** + * @internal + * + * Create an {@link IAttributesProcessor} that applies all processors from the provided list in order. + * + * @param processors Processors to apply in order. + */ + function createMultiAttributesProcessor(processors) { + return new MultiAttributesProcessor(processors); + } + exports.createMultiAttributesProcessor = createMultiAttributesProcessor; + /** + * Create an {@link IAttributesProcessor} that filters by allowed attribute names and drops any names that are not in the + * allow list. + */ + function createAllowListAttributesProcessor(attributeAllowList) { + return new AllowListProcessor(attributeAllowList); + } + exports.createAllowListAttributesProcessor = createAllowListAttributesProcessor; + /** + * Create an {@link IAttributesProcessor} that drops attributes based on the names provided in the deny list + */ + function createDenyListAttributesProcessor(attributeDenyList) { + return new DenyListProcessor(attributeDenyList); + } + exports.createDenyListAttributesProcessor = createDenyListAttributesProcessor; + const NOOP = new NoopAttributesProcessor(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js +var require_InstrumentSelector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstrumentSelector = void 0; + const Predicate_1 = require_Predicate(); + var InstrumentSelector = class { + _nameFilter; + _type; + _unitFilter; + constructor(criteria) { + this._nameFilter = new Predicate_1.PatternPredicate(criteria?.name ?? "*"); + this._type = criteria?.type; + this._unitFilter = new Predicate_1.ExactPredicate(criteria?.unit); + } + getType() { + return this._type; + } + getNameFilter() { + return this._nameFilter; + } + getUnitFilter() { + return this._unitFilter; + } + }; + exports.InstrumentSelector = InstrumentSelector; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js +var require_MeterSelector = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterSelector = void 0; + const Predicate_1 = require_Predicate(); + var MeterSelector = class { + _nameFilter; + _versionFilter; + _schemaUrlFilter; + constructor(criteria) { + this._nameFilter = new Predicate_1.ExactPredicate(criteria?.name); + this._versionFilter = new Predicate_1.ExactPredicate(criteria?.version); + this._schemaUrlFilter = new Predicate_1.ExactPredicate(criteria?.schemaUrl); + } + getNameFilter() { + return this._nameFilter; + } + /** + * TODO: semver filter? no spec yet. + */ + getVersionFilter() { + return this._versionFilter; + } + getSchemaUrlFilter() { + return this._schemaUrlFilter; + } + }; + exports.MeterSelector = MeterSelector; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js +var require_View = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.View = void 0; + const Predicate_1 = require_Predicate(); + const AttributesProcessor_1 = require_AttributesProcessor(); + const InstrumentSelector_1 = require_InstrumentSelector(); + const MeterSelector_1 = require_MeterSelector(); + const AggregationOption_1 = require_AggregationOption(); + function isSelectorNotProvided(options) { + return options.instrumentName == null && options.instrumentType == null && options.instrumentUnit == null && options.meterName == null && options.meterVersion == null && options.meterSchemaUrl == null; + } + function validateViewOptions(viewOptions) { + if (isSelectorNotProvided(viewOptions)) throw new Error("Cannot create view with no selector arguments supplied"); + if (viewOptions.name != null && (viewOptions?.instrumentName == null || Predicate_1.PatternPredicate.hasWildcard(viewOptions.instrumentName))) throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter."); + } + /** + * Can be passed to a {@link MeterProvider} to select instruments and alter their metric stream. + */ + var View = class { + name; + description; + aggregation; + attributesProcessor; + instrumentSelector; + meterSelector; + aggregationCardinalityLimit; + /** + * Create a new {@link View} instance. + * + * Parameters can be categorized as two types: + * Instrument selection criteria: Used to describe the instrument(s) this view will be applied to. + * Will be treated as additive (the Instrument has to meet all the provided criteria to be selected). + * + * Metric stream altering: Alter the metric stream of instruments selected by instrument selection criteria. + * + * @param viewOptions {@link ViewOptions} for altering the metric stream and instrument selection. + * @param viewOptions.name + * Alters the metric stream: + * This will be used as the name of the metrics stream. + * If not provided, the original Instrument name will be used. + * @param viewOptions.description + * Alters the metric stream: + * This will be used as the description of the metrics stream. + * If not provided, the original Instrument description will be used by default. + * @param viewOptions.attributesProcessors + * Alters the metric stream: + * If provided, the attributes will be modified as defined by the added processors. + * If not provided, all attribute keys will be used by default. + * @param viewOptions.aggregationCardinalityLimit + * Alters the metric stream: + * Sets a limit on the number of unique attribute combinations (cardinality) that can be aggregated. + * If not provided, the default limit of 2000 will be used. + * @param viewOptions.aggregation + * Alters the metric stream: + * Alters the {@link Aggregation} of the metric stream. + * @param viewOptions.instrumentName + * Instrument selection criteria: + * Original name of the Instrument(s) with wildcard support. + * @param viewOptions.instrumentType + * Instrument selection criteria: + * The original type of the Instrument(s). + * @param viewOptions.instrumentUnit + * Instrument selection criteria: + * The unit of the Instrument(s). + * @param viewOptions.meterName + * Instrument selection criteria: + * The name of the Meter. No wildcard support, name must match the meter exactly. + * @param viewOptions.meterVersion + * Instrument selection criteria: + * The version of the Meter. No wildcard support, version must match exactly. + * @param viewOptions.meterSchemaUrl + * Instrument selection criteria: + * The schema URL of the Meter. No wildcard support, schema URL must match exactly. + * + * @example + * // Create a view that changes the Instrument 'my.instrument' to use to an + * // ExplicitBucketHistogramAggregation with the boundaries [20, 30, 40] + * new View({ + * aggregation: new ExplicitBucketHistogramAggregation([20, 30, 40]), + * instrumentName: 'my.instrument' + * }) + */ + constructor(viewOptions) { + validateViewOptions(viewOptions); + if (viewOptions.attributesProcessors != null) this.attributesProcessor = (0, AttributesProcessor_1.createMultiAttributesProcessor)(viewOptions.attributesProcessors); + else this.attributesProcessor = (0, AttributesProcessor_1.createNoopAttributesProcessor)(); + this.name = viewOptions.name; + this.description = viewOptions.description; + this.aggregation = (0, AggregationOption_1.toAggregation)(viewOptions.aggregation ?? { type: AggregationOption_1.AggregationType.DEFAULT }); + this.instrumentSelector = new InstrumentSelector_1.InstrumentSelector({ + name: viewOptions.instrumentName, + type: viewOptions.instrumentType, + unit: viewOptions.instrumentUnit + }); + this.meterSelector = new MeterSelector_1.MeterSelector({ + name: viewOptions.meterName, + version: viewOptions.meterVersion, + schemaUrl: viewOptions.meterSchemaUrl + }); + this.aggregationCardinalityLimit = viewOptions.aggregationCardinalityLimit; + } + }; + exports.View = View; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js +var require_MeterProvider = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterProvider = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const resources_1 = require_src$6(); + const MetricReader_1 = require_MetricReader(); + const MeterProviderSharedState_1 = require_MeterProviderSharedState(); + const MetricCollector_1 = require_MetricCollector(); + const View_1 = require_View(); + /** + * This class implements the {@link MeterProvider} interface. + */ + var MeterProvider = class { + _sharedState; + _shutdown = false; + constructor(options) { + this._sharedState = new MeterProviderSharedState_1.MeterProviderSharedState(options?.resource ?? (0, resources_1.defaultResource)()); + if (options?.views != null && options.views.length > 0) for (const viewOption of options.views) this._sharedState.viewRegistry.addView(new View_1.View(viewOption)); + if (options?.readers != null && options.readers.length > 0) for (const metricReader of options.readers) { + const collector = new MetricCollector_1.MetricCollector(this._sharedState, metricReader); + metricReader.setMetricProducer(collector); + this._sharedState.metricCollectors.push(collector); + if (options.sdkMetricsEnabled && metricReader instanceof MetricReader_1.MetricReader) metricReader._setSelfObsMeterProvider(this); + } + } + /** + * Get a meter with the configuration of the MeterProvider. + */ + getMeter(name, version = "", options = {}) { + if (this._shutdown) { + api_1.diag.warn("A shutdown MeterProvider cannot provide a Meter"); + return (0, api_1.createNoopMeter)(); + } + return this._sharedState.getMeterSharedState({ + name, + version, + schemaUrl: options.schemaUrl + }).meter; + } + /** + * Shut down the MeterProvider and all registered + * MetricReaders. + * + * Returns a promise which is resolved when all flushes are complete. + */ + async shutdown(options) { + if (this._shutdown) { + api_1.diag.warn("shutdown may only be called once per MeterProvider"); + return; + } + this._shutdown = true; + await Promise.all(this._sharedState.metricCollectors.map((collector) => { + return collector.shutdown(options); + })); + } + /** + * Notifies all registered MetricReaders to flush any buffered data. + * + * Returns a promise which is resolved when all flushes are complete. + */ + async forceFlush(options) { + if (this._shutdown) { + api_1.diag.warn("invalid attempt to force flush after MeterProvider shutdown"); + return; + } + await Promise.all(this._sharedState.metricCollectors.map((collector) => { + return collector.forceFlush(options); + })); + } + }; + exports.MeterProvider = MeterProvider; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-metrics@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-metrics/build/src/index.js +var require_src$5 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TimeoutError = exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.AggregationType = exports.MeterProvider = exports.ConsoleMetricExporter = exports.InMemoryMetricExporter = exports.PeriodicExportingMetricReader = exports.MetricReader = exports.InstrumentType = exports.DataPointType = exports.AggregationTemporality = void 0; + var AggregationTemporality_1 = require_AggregationTemporality(); + Object.defineProperty(exports, "AggregationTemporality", { + enumerable: true, + get: function() { + return AggregationTemporality_1.AggregationTemporality; + } + }); + var MetricData_1 = require_MetricData(); + Object.defineProperty(exports, "DataPointType", { + enumerable: true, + get: function() { + return MetricData_1.DataPointType; + } + }); + Object.defineProperty(exports, "InstrumentType", { + enumerable: true, + get: function() { + return MetricData_1.InstrumentType; + } + }); + var MetricReader_1 = require_MetricReader(); + Object.defineProperty(exports, "MetricReader", { + enumerable: true, + get: function() { + return MetricReader_1.MetricReader; + } + }); + var PeriodicExportingMetricReader_1 = require_PeriodicExportingMetricReader(); + Object.defineProperty(exports, "PeriodicExportingMetricReader", { + enumerable: true, + get: function() { + return PeriodicExportingMetricReader_1.PeriodicExportingMetricReader; + } + }); + var InMemoryMetricExporter_1 = require_InMemoryMetricExporter(); + Object.defineProperty(exports, "InMemoryMetricExporter", { + enumerable: true, + get: function() { + return InMemoryMetricExporter_1.InMemoryMetricExporter; + } + }); + var ConsoleMetricExporter_1 = require_ConsoleMetricExporter(); + Object.defineProperty(exports, "ConsoleMetricExporter", { + enumerable: true, + get: function() { + return ConsoleMetricExporter_1.ConsoleMetricExporter; + } + }); + var MeterProvider_1 = require_MeterProvider(); + Object.defineProperty(exports, "MeterProvider", { + enumerable: true, + get: function() { + return MeterProvider_1.MeterProvider; + } + }); + var AggregationOption_1 = require_AggregationOption(); + Object.defineProperty(exports, "AggregationType", { + enumerable: true, + get: function() { + return AggregationOption_1.AggregationType; + } + }); + var AttributesProcessor_1 = require_AttributesProcessor(); + Object.defineProperty(exports, "createAllowListAttributesProcessor", { + enumerable: true, + get: function() { + return AttributesProcessor_1.createAllowListAttributesProcessor; + } + }); + Object.defineProperty(exports, "createDenyListAttributesProcessor", { + enumerable: true, + get: function() { + return AttributesProcessor_1.createDenyListAttributesProcessor; + } + }); + var utils_1 = require_utils$3(); + Object.defineProperty(exports, "TimeoutError", { + enumerable: true, + get: function() { + return utils_1.TimeoutError; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics-serializer.js +var require_metrics_serializer = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serializeMetricsExportRequest = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const sdk_metrics_1 = require_src$5(); + const common_serializer_1 = require_common_serializer(); + const protobuf_size_estimator_1 = require_protobuf_size_estimator(); + const protobuf_writer_1 = require_protobuf_writer(); + /** + * Serialize a NumberDataPoint directly from SDK DataPoint + * + * Proto fields (NumberDataPoint): + * 7 attributes repeated KeyValue (wire type 2) + * 2 start_time_unix_nano fixed64 (wire type 1) + * 3 time_unix_nano fixed64 (wire type 1) + * 4 as_double double (wire type 1) + * 6 as_int sfixed64 (wire type 1) + * 5 exemplars repeated Exemplar (wire type 2) + * 8 flags uint32 (wire type 0) + */ + function serializeNumberDataPoint(writer, dataPoint, valueType) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + writer.writeTag(2, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.startTime); + writer.writeTag(3, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.endTime); + if (valueType === api_1.ValueType.INT) { + writer.writeTag(6, 1); + writer.writeSfixed64(dataPoint.value); + } else { + writer.writeTag(4, 1); + writer.writeDouble(dataPoint.value); + } + if (dataPoint.attributes) (0, common_serializer_1.writeAttributes)(writer, dataPoint.attributes, 7); + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Serialize a HistogramDataPoint directly from SDK DataPoint + * + * Proto fields (HistogramDataPoint): + * 9 attributes repeated KeyValue (wire type 2) + * 2 start_time_unix_nano fixed64 (wire type 1) + * 3 time_unix_nano fixed64 (wire type 1) + * 4 count fixed64 (wire type 1) + * 5 sum optional double (wire type 1) + * 6 bucket_counts repeated fixed64 (packed, wire type 2) + * 7 explicit_bounds repeated double (packed, wire type 2) + * 8 exemplars repeated Exemplar (wire type 2) + * 10 flags uint32 (wire type 0) + * 11 min optional double (wire type 1) + * 12 max optional double (wire type 1) + */ + function serializeHistogramDataPoint(writer, dataPoint) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + const histogram = dataPoint.value; + writer.writeTag(2, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.startTime); + writer.writeTag(3, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.endTime); + writer.writeTag(4, 1); + writer.writeFixed64(histogram.count >>> 0, histogram.count / 4294967296 >>> 0); + if (histogram.sum !== void 0) { + writer.writeTag(5, 1); + writer.writeDouble(histogram.sum); + } + if (histogram.buckets.counts.length > 0) { + writer.writeTag(6, 2); + const countsStart = writer.startLengthDelimited(); + const countsStartPos = writer.pos; + for (const count of histogram.buckets.counts) writer.writeFixed64(count >>> 0, count / 4294967296 >>> 0); + writer.finishLengthDelimited(countsStart, writer.pos - countsStartPos); + } + if (histogram.buckets.boundaries.length > 0) { + writer.writeTag(7, 2); + const boundsStart = writer.startLengthDelimited(); + const boundsStartPos = writer.pos; + for (const bound of histogram.buckets.boundaries) writer.writeDouble(bound); + writer.finishLengthDelimited(boundsStart, writer.pos - boundsStartPos); + } + if (dataPoint.attributes) (0, common_serializer_1.writeAttributes)(writer, dataPoint.attributes, 9); + if (histogram.min !== void 0) { + writer.writeTag(11, 1); + writer.writeDouble(histogram.min); + } + if (histogram.max !== void 0) { + writer.writeTag(12, 1); + writer.writeDouble(histogram.max); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Serialize ExponentialHistogramDataPoint.Buckets + * + * Proto fields (Buckets): + * 1 offset sint32 (wire type 0, zigzag) + * 2 bucket_counts repeated uint64 (packed, wire type 2) + */ + function serializeExponentialBuckets(writer, offset, bucketCounts) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + if (offset !== 0) { + writer.writeTag(1, 0); + writer.writeSint32(offset); + } + if (bucketCounts.length > 0) { + writer.writeTag(2, 2); + const bcStart = writer.startLengthDelimited(); + const bcStartPos = writer.pos; + for (const count of bucketCounts) writer.writeVarint(count); + writer.finishLengthDelimited(bcStart, writer.pos - bcStartPos); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Serialize an ExponentialHistogramDataPoint directly from SDK DataPoint + * + * Proto fields (ExponentialHistogramDataPoint): + * 1 attributes repeated KeyValue (wire type 2) + * 2 start_time_unix_nano fixed64 (wire type 1) + * 3 time_unix_nano fixed64 (wire type 1) + * 4 count fixed64 (wire type 1) + * 5 sum optional double (wire type 1) + * 6 scale sint32 (wire type 0, zigzag) + * 7 zero_count fixed64 (wire type 1) + * 8 positive Buckets (wire type 2) + * 9 negative Buckets (wire type 2) + * 10 flags uint32 (wire type 0) + * 11 exemplars repeated Exemplar (wire type 2) + * 12 min optional double (wire type 1) + * 13 max optional double (wire type 1) + */ + function serializeExponentialHistogramDataPoint(writer, dataPoint) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + const histogram = dataPoint.value; + if (dataPoint.attributes) (0, common_serializer_1.writeAttributes)(writer, dataPoint.attributes, 1); + writer.writeTag(2, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.startTime); + writer.writeTag(3, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.endTime); + writer.writeTag(4, 1); + writer.writeFixed64(histogram.count >>> 0, histogram.count / 4294967296 >>> 0); + if (histogram.sum !== void 0) { + writer.writeTag(5, 1); + writer.writeDouble(histogram.sum); + } + if (histogram.scale !== 0) { + writer.writeTag(6, 0); + writer.writeSint32(histogram.scale); + } + writer.writeTag(7, 1); + writer.writeFixed64(histogram.zeroCount >>> 0, histogram.zeroCount / 4294967296 >>> 0); + writer.writeTag(8, 2); + serializeExponentialBuckets(writer, histogram.positive.offset, histogram.positive.bucketCounts); + writer.writeTag(9, 2); + serializeExponentialBuckets(writer, histogram.negative.offset, histogram.negative.bucketCounts); + if (histogram.min !== void 0) { + writer.writeTag(12, 1); + writer.writeDouble(histogram.min); + } + if (histogram.max !== void 0) { + writer.writeTag(13, 1); + writer.writeDouble(histogram.max); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Serialize a Metric message with its data type + * + * Proto fields (Metric): + * 1 name string (wire type 2) + * 2 description string (wire type 2) + * 3 unit string (wire type 2) + * 5 gauge Gauge (wire type 2) + * 7 sum Sum (wire type 2) + * 9 histogram Histogram (wire type 2) + * 10 exponential_histogram ExponentialHist (wire type 2) + * 11 summary Summary (wire type 2) + */ + function serializeMetric(writer, metricData) { + const metricStart = writer.startLengthDelimited(); + const metricStartPos = writer.pos; + writer.writeTag(1, 2); + writer.writeString(metricData.descriptor.name); + if (metricData.descriptor.description) { + writer.writeTag(2, 2); + writer.writeString(metricData.descriptor.description); + } + if (metricData.descriptor.unit) { + writer.writeTag(3, 2); + writer.writeString(metricData.descriptor.unit); + } + switch (metricData.dataPointType) { + case sdk_metrics_1.DataPointType.GAUGE: + writer.writeTag(5, 2); + serializeGauge(writer, metricData); + break; + case sdk_metrics_1.DataPointType.SUM: + writer.writeTag(7, 2); + serializeSum(writer, metricData); + break; + case sdk_metrics_1.DataPointType.HISTOGRAM: + writer.writeTag(9, 2); + serializeHistogramMetric(writer, metricData); + break; + case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM: + writer.writeTag(10, 2); + serializeExponentialHistogramMetric(writer, metricData); + } + writer.finishLengthDelimited(metricStart, writer.pos - metricStartPos); + } + /** + * Proto fields (Gauge): + * 1 data_points repeated NumberDataPoint (wire type 2) + */ + function serializeGauge(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeNumberDataPoint(writer, dataPoint, metricData.descriptor.valueType); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Proto fields (Sum): + * 1 data_points repeated NumberDataPoint (wire type 2) + * 2 aggregation_temporality AggregationTemporality (wire type 0) + * 3 is_monotonic bool (wire type 0) + */ + function serializeSum(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeNumberDataPoint(writer, dataPoint, metricData.descriptor.valueType); + } + const temporality = toProtoAggregationTemporality(metricData.aggregationTemporality); + if (temporality !== 0) { + writer.writeTag(2, 0); + writer.writeVarint(temporality); + } + if (metricData.isMonotonic) { + writer.writeTag(3, 0); + writer.writeVarint(1); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Proto fields (Histogram): + * 1 data_points repeated HistogramDataPoint (wire type 2) + * 2 aggregation_temporality AggregationTemporality (wire type 0) + */ + function serializeHistogramMetric(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeHistogramDataPoint(writer, dataPoint); + } + const temporality = toProtoAggregationTemporality(metricData.aggregationTemporality); + if (temporality !== 0) { + writer.writeTag(2, 0); + writer.writeVarint(temporality); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Proto fields (ExponentialHistogram): + * 1 data_points repeated ExponentialHistogramDataPoint (wire type 2) + * 2 aggregation_temporality AggregationTemporality (wire type 0) + */ + function serializeExponentialHistogramMetric(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeExponentialHistogramDataPoint(writer, dataPoint); + } + const temporality = toProtoAggregationTemporality(metricData.aggregationTemporality); + if (temporality !== 0) { + writer.writeTag(2, 0); + writer.writeVarint(temporality); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + /** + * Serialize ScopeMetrics directly from SDK types + */ + function serializeScopeMetrics(writer, scopeMetrics) { + const scopeStart = writer.startLengthDelimited(); + const scopeStartPos = writer.pos; + (0, common_serializer_1.writeInstrumentationScope)(writer, scopeMetrics.scope, 1); + for (const metric of scopeMetrics.metrics) { + writer.writeTag(2, 2); + serializeMetric(writer, metric); + } + if (scopeMetrics.scope.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(scopeMetrics.scope.schemaUrl); + } + writer.finishLengthDelimited(scopeStart, writer.pos - scopeStartPos); + } + /** + * Serialize ResourceMetrics directly from SDK types + * + * Proto fields (ResourceMetrics): + * 1 resource Resource (wire type 2) + * 2 scope_metrics repeated ScopeMetrics (wire type 2) + * 3 schema_url string (wire type 2) + */ + function serializeResourceMetrics(writer, resourceMetrics) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + (0, common_serializer_1.writeResource)(writer, resourceMetrics.resource, 1); + for (const scopeMetrics of resourceMetrics.scopeMetrics) { + writer.writeTag(2, 2); + serializeScopeMetrics(writer, scopeMetrics); + } + if (resourceMetrics.resource.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(resourceMetrics.resource.schemaUrl); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function toProtoAggregationTemporality(temporality) { + switch (temporality) { + case sdk_metrics_1.AggregationTemporality.DELTA: return 1; + case sdk_metrics_1.AggregationTemporality.CUMULATIVE: return 2; + default: return 0; + } + } + /** + * Serialize ExportMetricsServiceRequest directly from ResourceMetrics + */ + function serializeMetricsExportRequest(resourceMetrics) { + const estimator = new protobuf_size_estimator_1.ProtobufSizeEstimator(); + estimator.writeTag(1, 2); + serializeResourceMetrics(estimator, resourceMetrics); + const writer = new protobuf_writer_1.ProtobufWriter(estimator.pos); + writer.writeTag(1, 2); + serializeResourceMetrics(writer, resourceMetrics); + return writer.finish(); + } + exports.serializeMetricsExportRequest = serializeMetricsExportRequest; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/response-deserializer.js +var require_response_deserializer$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deserializeExportMetricsServiceResponse = void 0; + const protobuf_reader_1 = require_protobuf_reader(); + /** + * Parse an ExportMetricsPartialSuccess embedded message from raw bytes. + * + * Field map (opentelemetry/proto/collector/metrics/v1/metrics_service.proto): + * 1 rejected_data_points int64 (varint) + * 2 error_message string (length-delimited) + */ + function deserializePartialSuccess(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 0) result.rejectedDataPoints = reader.readVarint(); + else reader.skip(wireType); + break; + case 2: + if (wireType === 2) result.errorMessage = reader.readString(); + else reader.skip(wireType); + break; + default: reader.skip(wireType); + } + } + return result; + } + /** + * Parse an ExportMetricsServiceResponse protobuf message from raw bytes. + * + * Field map (opentelemetry/proto/collector/metrics/v1/metrics_service.proto): + * 1 partial_success ExportMetricsPartialSuccess (length-delimited) + */ + function deserializeExportMetricsServiceResponse(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 2) result.partialSuccess = deserializePartialSuccess(reader.readBytes()); + else reader.skip(wireType); + break; + default: reader.skip(wireType); + } + } + return result; + } + exports.deserializeExportMetricsServiceResponse = deserializeExportMetricsServiceResponse; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js +var require_metrics$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufMetricsSerializer = void 0; + const metrics_serializer_1 = require_metrics_serializer(); + const response_deserializer_1 = require_response_deserializer$1(); + exports.ProtobufMetricsSerializer = { + serializeRequest: (arg) => { + return (0, metrics_serializer_1.serializeMetricsExportRequest)(arg); + }, + deserializeResponse: (arg) => { + return (0, response_deserializer_1.deserializeExportMetricsServiceResponse)(arg); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js +var require_protobuf$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufMetricsSerializer = void 0; + var metrics_1 = require_metrics$1(); + Object.defineProperty(exports, "ProtobufMetricsSerializer", { + enumerable: true, + get: function() { + return metrics_1.ProtobufMetricsSerializer; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace-serializer.js +var require_trace_serializer = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serializeTraceExportRequest = void 0; + const protobuf_writer_1 = require_protobuf_writer(); + const hex_to_binary_1 = require_hex_to_binary(); + const common_serializer_1 = require_common_serializer(); + const protobuf_size_estimator_1 = require_protobuf_size_estimator(); + const SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256; + const SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512; + function buildSpanFlags(traceFlags, isRemote) { + let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK; + if (isRemote) flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK; + return flags; + } + /** + * Serialize a Span.Status message + * + * Proto fields (Status): + * 1 (reserved) + * 2 message string (length-delimited) + * 3 code StatusCode (varint) + */ + function serializeStatus(writer, status) { + const statusStart = writer.startLengthDelimited(); + const statusStartPos = writer.pos; + if (status.message) { + writer.writeTag(2, 2); + writer.writeString(status.message); + } + writer.writeTag(3, 0); + writer.writeVarint(status.code); + writer.finishLengthDelimited(statusStart, writer.pos - statusStartPos); + } + /** + * Serialize a Span.Event message + * + * Proto fields (Span.Event): + * 1 time_unix_nano fixed64 (wire type 1) + * 2 name string (wire type 2) + * 3 attributes repeated KeyValue (wire type 2) + * 4 dropped_attributes_count uint32 (wire type 0) + */ + function serializeEvent(writer, event) { + const eventStart = writer.startLengthDelimited(); + const eventStartPos = writer.pos; + writer.writeTag(1, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, event.time); + writer.writeTag(2, 2); + writer.writeString(event.name); + if (event.attributes) (0, common_serializer_1.writeAttributes)(writer, event.attributes, 3); + writer.writeTag(4, 0); + writer.writeVarint(event.droppedAttributesCount || 0); + writer.finishLengthDelimited(eventStart, writer.pos - eventStartPos); + } + /** + * Serialize a Span.Link message + * + * Proto fields (Span.Link): + * 1 trace_id bytes (wire type 2) + * 2 span_id bytes (wire type 2) + * 3 trace_state string (wire type 2) + * 4 attributes repeated KeyValue (wire type 2) + * 5 dropped_attributes_count uint32 (wire type 0) + * 6 flags fixed32 (wire type 5) + */ + function serializeLink(writer, link) { + const linkStart = writer.startLengthDelimited(); + const linkStartPos = writer.pos; + const context = link.context; + writer.writeTag(1, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(context.traceId)); + writer.writeTag(2, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(context.spanId)); + const linkTraceState = context.traceState?.serialize(); + if (linkTraceState) { + writer.writeTag(3, 2); + writer.writeString(linkTraceState); + } + if (link.attributes) (0, common_serializer_1.writeAttributes)(writer, link.attributes, 4); + writer.writeTag(5, 0); + writer.writeVarint(link.droppedAttributesCount || 0); + const linkFlags = buildSpanFlags(context.traceFlags, context.isRemote); + if (linkFlags) { + writer.writeTag(6, 5); + writer.writeFixed32(linkFlags); + } + writer.finishLengthDelimited(linkStart, writer.pos - linkStartPos); + } + /** + * Serialize a single Span message directly from ReadableSpan + * + * Proto fields (Span): + * 1 trace_id bytes (wire type 2) + * 2 span_id bytes (wire type 2) + * 3 trace_state string (wire type 2) + * 4 parent_span_id bytes (wire type 2) + * 5 name string (wire type 2) + * 6 kind SpanKind (wire type 0) + * 7 start_time_unix_nano fixed64 (wire type 1) + * 8 end_time_unix_nano fixed64 (wire type 1) + * 9 attributes repeated KeyValue (wire type 2) + * 10 dropped_attributes_count uint32 (wire type 0) + * 11 events repeated Event (wire type 2) + * 12 dropped_events_count uint32 (wire type 0) + * 13 links repeated Link (wire type 2) + * 14 dropped_links_count uint32 (wire type 0) + * 15 status Status (wire type 2) + * 16 flags fixed32 (wire type 5) + */ + function serializeSpan(writer, span) { + const spanStart = writer.startLengthDelimited(); + const spanStartPos = writer.pos; + const ctx = span.spanContext(); + writer.writeTag(1, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(ctx.traceId)); + writer.writeTag(2, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(ctx.spanId)); + const traceState = ctx.traceState?.serialize(); + if (traceState) { + writer.writeTag(3, 2); + writer.writeString(traceState); + } + if (span.parentSpanContext?.spanId) { + writer.writeTag(4, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(span.parentSpanContext.spanId)); + } + writer.writeTag(5, 2); + writer.writeString(span.name); + const kind = span.kind == null ? 0 : span.kind + 1; + if (kind !== 0) { + writer.writeTag(6, 0); + writer.writeVarint(kind); + } + writer.writeTag(7, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, span.startTime); + writer.writeTag(8, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, span.endTime); + if (span.attributes) (0, common_serializer_1.writeAttributes)(writer, span.attributes, 9); + writer.writeTag(10, 0); + writer.writeVarint(span.droppedAttributesCount); + for (const event of span.events) { + writer.writeTag(11, 2); + serializeEvent(writer, event); + } + writer.writeTag(12, 0); + writer.writeVarint(span.droppedEventsCount); + for (const link of span.links) { + writer.writeTag(13, 2); + serializeLink(writer, link); + } + writer.writeTag(14, 0); + writer.writeVarint(span.droppedLinksCount); + writer.writeTag(15, 2); + serializeStatus(writer, span.status); + const flags = buildSpanFlags(ctx.traceFlags, span.parentSpanContext?.isRemote); + if (flags) { + writer.writeTag(16, 5); + writer.writeFixed32(flags); + } + writer.finishLengthDelimited(spanStart, writer.pos - spanStartPos); + } + /** + * Serialize ScopeSpans directly from SDK types + */ + function serializeScopeSpans(writer, scope, spans) { + const scopeSpansStart = writer.startLengthDelimited(); + const scopeSpansStartPos = writer.pos; + (0, common_serializer_1.writeInstrumentationScope)(writer, scope, 1); + for (const span of spans) { + writer.writeTag(2, 2); + serializeSpan(writer, span); + } + if (scope.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(scope.schemaUrl); + } + writer.finishLengthDelimited(scopeSpansStart, writer.pos - scopeSpansStartPos); + } + /** + * Serialize ResourceSpans directly from SDK Resource type + */ + function serializeResourceSpans(writer, resource, scopeMap) { + const resourceSpansStart = writer.startLengthDelimited(); + const resourceSpansStartPos = writer.pos; + (0, common_serializer_1.writeResource)(writer, resource, 1); + for (const scopeSpans of scopeMap.values()) { + writer.writeTag(2, 2); + const scope = scopeSpans[0].instrumentationScope; + serializeScopeSpans(writer, scope, scopeSpans); + } + if (resource.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(resource.schemaUrl); + } + writer.finishLengthDelimited(resourceSpansStart, writer.pos - resourceSpansStartPos); + } + /** + * Group spans by resource and instrumentation scope using identity comparison + */ + function createResourceMap(spans) { + const resourceMap = /* @__PURE__ */ new Map(); + for (const span of spans) { + const resource = span.resource; + const scope = span.instrumentationScope; + let scopeMap = resourceMap.get(resource); + if (!scopeMap) { + scopeMap = /* @__PURE__ */ new Map(); + resourceMap.set(resource, scopeMap); + } + let records = scopeMap.get(scope); + if (!records) { + records = []; + scopeMap.set(scope, records); + } + records.push(span); + } + return resourceMap; + } + /** + * Serialize ExportTraceServiceRequest directly from ReadableSpan[] + */ + function serializeTraceExportRequest(spans) { + const resourceMap = createResourceMap(spans); + const estimator = new protobuf_size_estimator_1.ProtobufSizeEstimator(); + for (const [resource, scopeMap] of resourceMap) { + estimator.writeTag(1, 2); + serializeResourceSpans(estimator, resource, scopeMap); + } + const writer = new protobuf_writer_1.ProtobufWriter(estimator.pos); + for (const [resource, scopeMap] of resourceMap) { + writer.writeTag(1, 2); + serializeResourceSpans(writer, resource, scopeMap); + } + return writer.finish(); + } + exports.serializeTraceExportRequest = serializeTraceExportRequest; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/response-deserializer.js +var require_response_deserializer = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deserializeExportTraceServiceResponse = void 0; + const protobuf_reader_1 = require_protobuf_reader(); + /** + * Parse an ExportTracePartialSuccess embedded message from raw bytes. + * + * Field map (opentelemetry/proto/collector/trace/v1/trace_service.proto): + * 1 rejected_spans int64 (varint) + * 2 error_message string (length-delimited) + */ + function deserializePartialSuccess(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 0) result.rejectedSpans = reader.readVarint(); + else reader.skip(wireType); + break; + case 2: + if (wireType === 2) result.errorMessage = reader.readString(); + else reader.skip(wireType); + break; + default: reader.skip(wireType); + } + } + return result; + } + /** + * Parse an ExportTraceServiceResponse protobuf message from raw bytes. + * + * Field map (opentelemetry/proto/collector/trace/v1/trace_service.proto): + * 1 partial_success ExportTracePartialSuccess (length-delimited) + */ + function deserializeExportTraceServiceResponse(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 2) result.partialSuccess = deserializePartialSuccess(reader.readBytes()); + else reader.skip(wireType); + break; + default: reader.skip(wireType); + } + } + return result; + } + exports.deserializeExportTraceServiceResponse = deserializeExportTraceServiceResponse; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js +var require_trace$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufTraceSerializer = void 0; + const trace_serializer_1 = require_trace_serializer(); + const response_deserializer_1 = require_response_deserializer(); + exports.ProtobufTraceSerializer = { + serializeRequest: (arg) => { + return (0, trace_serializer_1.serializeTraceExportRequest)(arg); + }, + deserializeResponse: (arg) => { + return (0, response_deserializer_1.deserializeExportTraceServiceResponse)(arg); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js +var require_protobuf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufTraceSerializer = void 0; + var trace_1 = require_trace$1(); + Object.defineProperty(exports, "ProtobufTraceSerializer", { + enumerable: true, + get: function() { + return trace_1.ProtobufTraceSerializer; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js +var require_internal$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toAnyValue = exports.toKeyValue = exports.toAttributes = exports.createInstrumentationScope = exports.createResource = void 0; + function createResource(resource, encoder) { + const result = { + attributes: toAttributes(resource.attributes, encoder), + droppedAttributesCount: 0 + }; + const schemaUrl = resource.schemaUrl; + if (schemaUrl && schemaUrl !== "") result.schemaUrl = schemaUrl; + return result; + } + exports.createResource = createResource; + function createInstrumentationScope(scope, encoder) { + const result = { + name: scope.name, + version: scope.version + }; + if (scope.attributes && Object.keys(scope.attributes).length > 0) { + result.attributes = toAttributes(scope.attributes, encoder); + result.droppedAttributesCount = scope.droppedAttributesCount ?? 0; + } + return result; + } + exports.createInstrumentationScope = createInstrumentationScope; + function toAttributes(attributes, encoder) { + return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key], encoder)); + } + exports.toAttributes = toAttributes; + function toKeyValue(key, value, encoder) { + return { + key, + value: toAnyValue(value, encoder) + }; + } + exports.toKeyValue = toKeyValue; + function toAnyValue(value, encoder) { + const t = typeof value; + if (t === "string") return { stringValue: value }; + if (t === "number") { + if (!Number.isInteger(value)) return { doubleValue: value }; + return { intValue: value }; + } + if (t === "boolean") return { boolValue: value }; + if (value instanceof Uint8Array) return { bytesValue: encoder.encodeUint8Array(value) }; + if (Array.isArray(value)) { + const values = new Array(value.length); + for (let i = 0; i < value.length; i++) values[i] = toAnyValue(value[i], encoder); + return { arrayValue: { values } }; + } + if (t === "object" && value != null) { + const keys = Object.keys(value); + const values = new Array(keys.length); + for (let i = 0; i < keys.length; i++) values[i] = { + key: keys[i], + value: toAnyValue(value[keys[i]], encoder) + }; + return { kvlistValue: { values } }; + } + return {}; + } + exports.toAnyValue = toAnyValue; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js +var require_internal$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createExportLogsServiceRequest = void 0; + const internal_1 = require_internal$3(); + function createExportLogsServiceRequest(logRecords, encoder) { + return { resourceLogs: logRecordsToResourceLogs(logRecords, encoder) }; + } + exports.createExportLogsServiceRequest = createExportLogsServiceRequest; + function createResourceMap(logRecords) { + const resourceMap = /* @__PURE__ */ new Map(); + for (const record of logRecords) { + const { resource, instrumentationScope } = record; + let ismMap = resourceMap.get(resource); + if (!ismMap) { + ismMap = /* @__PURE__ */ new Map(); + resourceMap.set(resource, ismMap); + } + let records = ismMap.get(instrumentationScope); + if (!records) { + records = []; + ismMap.set(instrumentationScope, records); + } + records.push(record); + } + return resourceMap; + } + function logRecordsToResourceLogs(logRecords, encoder) { + const resourceMap = createResourceMap(logRecords); + return Array.from(resourceMap, ([resource, ismMap]) => { + const processedResource = (0, internal_1.createResource)(resource, encoder); + return { + resource: processedResource, + scopeLogs: Array.from(ismMap, ([, scopeLogs]) => { + return { + scope: (0, internal_1.createInstrumentationScope)(scopeLogs[0].instrumentationScope, encoder), + logRecords: scopeLogs.map((log) => toLogRecord(log, encoder)), + schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl + }; + }), + schemaUrl: processedResource.schemaUrl + }; + }); + } + function toLogRecord(log, encoder) { + return { + timeUnixNano: encoder.encodeHrTime(log.hrTime), + observedTimeUnixNano: encoder.encodeHrTime(log.hrTimeObserved), + severityNumber: toSeverityNumber(log.severityNumber), + severityText: log.severityText, + body: (0, internal_1.toAnyValue)(log.body, encoder), + eventName: log.eventName, + attributes: (0, internal_1.toAttributes)(log.attributes, encoder), + droppedAttributesCount: log.droppedAttributesCount, + flags: log.spanContext?.traceFlags, + traceId: encoder.encodeOptionalSpanContext(log.spanContext?.traceId), + spanId: encoder.encodeOptionalSpanContext(log.spanContext?.spanId) + }; + } + function toSeverityNumber(severityNumber) { + return severityNumber; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JSON_ENCODER = exports.PROTOBUF_ENCODER = exports.encodeAsString = exports.encodeAsLongBits = exports.toLongBits = exports.hrTimeToNanos = void 0; + const core_1 = require_src$8(); + const hex_to_binary_1 = require_hex_to_binary(); + function hrTimeToNanos(hrTime) { + const NANOSECONDS = BigInt(1e9); + return BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1])); + } + exports.hrTimeToNanos = hrTimeToNanos; + function toLongBits(value) { + return { + low: Number(BigInt.asUintN(32, value)), + high: Number(BigInt.asUintN(32, value >> BigInt(32))) + }; + } + exports.toLongBits = toLongBits; + function encodeAsLongBits(hrTime) { + return toLongBits(hrTimeToNanos(hrTime)); + } + exports.encodeAsLongBits = encodeAsLongBits; + function encodeAsString(hrTime) { + return hrTimeToNanos(hrTime).toString(); + } + exports.encodeAsString = encodeAsString; + const encodeTimestamp = typeof BigInt !== "undefined" ? encodeAsString : core_1.hrTimeToNanoseconds; + function identity(value) { + return value; + } + function optionalHexToBinary(str) { + if (str === void 0) return void 0; + return (0, hex_to_binary_1.hexToBinary)(str); + } + /** + * Encoder for protobuf format. + * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is. + */ + exports.PROTOBUF_ENCODER = { + encodeHrTime: encodeAsLongBits, + encodeSpanContext: hex_to_binary_1.hexToBinary, + encodeOptionalSpanContext: optionalHexToBinary, + encodeUint8Array: identity + }; + /** + * Encoder for JSON format. + * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array. + */ + exports.JSON_ENCODER = { + encodeHrTime: encodeTimestamp, + encodeSpanContext: identity, + encodeOptionalSpanContext: identity, + encodeUint8Array: (bytes) => { + if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64"); + const chars = new Array(bytes.length); + for (let i = 0; i < bytes.length; i++) chars[i] = String.fromCharCode(bytes[i]); + return btoa(chars.join("")); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js +var require_logs = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonLogsSerializer = void 0; + const internal_1 = require_internal$2(); + const utils_1 = require_utils(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + /** + * @experimental this serializer may receive breaking changes in minor versions, pin this package's version when using this constant + */ + exports.JsonLogsSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportLogsServiceRequest)(arg, utils_1.JSON_ENCODER); + return new TextEncoder().encode(JSON.stringify(request)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) return {}; + const decoder = new TextDecoder(); + try { + return JSON.parse(decoder.decode(arg)); + } catch (err) { + api_1.diag.warn(`Failed to parse logs export response: ${err.message}. Returning empty response`); + return {}; + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js +var require_json$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonLogsSerializer = void 0; + var logs_1 = require_logs(); + Object.defineProperty(exports, "JsonLogsSerializer", { + enumerable: true, + get: function() { + return logs_1.JsonLogsSerializer; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js +var require_internal_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EAggregationTemporality = void 0; + /** + * AggregationTemporality defines how a metric aggregator reports aggregated + * values. It describes how those values relate to the time interval over + * which they are aggregated. + */ + var EAggregationTemporality; + (function(EAggregationTemporality) { + EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"; + /** DELTA is an AggregationTemporality for a metric aggregator which reports + changes since last report time. Successive metrics contain aggregation of + values from continuous and non-overlapping intervals. + + The values for a DELTA metric are based only on the time interval + associated with one measurement cycle. There is no dependency on + previous measurements like is the case for CUMULATIVE metrics. + + For example, consider a system measuring the number of requests that + it receives and reports the sum of these requests every second as a + DELTA metric: + + 1. The system starts receiving at time=t_0. + 2. A request is received, the system measures 1 request. + 3. A request is received, the system measures 1 request. + 4. A request is received, the system measures 1 request. + 5. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0 to + t_0+1 with a value of 3. + 6. A request is received, the system measures 1 request. + 7. A request is received, the system measures 1 request. + 8. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0+1 to + t_0+2 with a value of 2. */ + EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_DELTA"] = 1] = "AGGREGATION_TEMPORALITY_DELTA"; + /** CUMULATIVE is an AggregationTemporality for a metric aggregator which + reports changes since a fixed start time. This means that current values + of a CUMULATIVE metric depend on all previous measurements since the + start time. Because of this, the sender is required to retain this state + in some form. If this state is lost or invalidated, the CUMULATIVE metric + values MUST be reset and a new fixed start time following the last + reported measurement time sent MUST be used. + + For example, consider a system measuring the number of requests that + it receives and reports the sum of these requests every second as a + CUMULATIVE metric: + + 1. The system starts receiving at time=t_0. + 2. A request is received, the system measures 1 request. + 3. A request is received, the system measures 1 request. + 4. A request is received, the system measures 1 request. + 5. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0 to + t_0+1 with a value of 3. + 6. A request is received, the system measures 1 request. + 7. A request is received, the system measures 1 request. + 8. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_0 to + t_0+2 with a value of 5. + 9. The system experiences a fault and loses state. + 10. The system recovers and resumes receiving at time=t_1. + 11. A request is received, the system measures 1 request. + 12. The 1 second collection cycle ends. A metric is exported for the + number of requests received over the interval of time t_1 to + t_0+1 with a value of 1. + + Note: Even though, when reporting changes since last report time, using + CUMULATIVE is valid, it is not recommended. This may cause problems for + systems that do not use start_time to determine when the aggregation + value was reset (e.g. Prometheus). */ + EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"; + })(EAggregationTemporality || (exports.EAggregationTemporality = EAggregationTemporality = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js +var require_internal$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createExportMetricsServiceRequest = exports.toMetric = exports.toScopeMetrics = exports.toResourceMetrics = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const sdk_metrics_1 = require_src$5(); + const internal_types_1 = require_internal_types(); + const internal_1 = require_internal$3(); + function toResourceMetrics(resourceMetrics, encoder) { + const processedResource = (0, internal_1.createResource)(resourceMetrics.resource, encoder); + return { + resource: processedResource, + schemaUrl: processedResource.schemaUrl, + scopeMetrics: toScopeMetrics(resourceMetrics.scopeMetrics, encoder) + }; + } + exports.toResourceMetrics = toResourceMetrics; + function toScopeMetrics(scopeMetrics, encoder) { + return Array.from(scopeMetrics.map((metrics) => ({ + scope: (0, internal_1.createInstrumentationScope)(metrics.scope, encoder), + metrics: metrics.metrics.map((metricData) => toMetric(metricData, encoder)), + schemaUrl: metrics.scope.schemaUrl + }))); + } + exports.toScopeMetrics = toScopeMetrics; + function toMetric(metricData, encoder) { + const out = { + name: metricData.descriptor.name, + description: metricData.descriptor.description, + unit: metricData.descriptor.unit + }; + const aggregationTemporality = toAggregationTemporality(metricData.aggregationTemporality); + switch (metricData.dataPointType) { + case sdk_metrics_1.DataPointType.SUM: + out.sum = { + aggregationTemporality, + isMonotonic: metricData.isMonotonic, + dataPoints: toSingularDataPoints(metricData, encoder) + }; + break; + case sdk_metrics_1.DataPointType.GAUGE: + out.gauge = { dataPoints: toSingularDataPoints(metricData, encoder) }; + break; + case sdk_metrics_1.DataPointType.HISTOGRAM: + out.histogram = { + aggregationTemporality, + dataPoints: toHistogramDataPoints(metricData, encoder) + }; + break; + case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM: out.exponentialHistogram = { + aggregationTemporality, + dataPoints: toExponentialHistogramDataPoints(metricData, encoder) + }; + } + return out; + } + exports.toMetric = toMetric; + function toSingularDataPoint(dataPoint, valueType, encoder) { + const out = { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes, encoder), + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime) + }; + switch (valueType) { + case api_1.ValueType.INT: + out.asInt = dataPoint.value; + break; + case api_1.ValueType.DOUBLE: out.asDouble = dataPoint.value; + } + return out; + } + function toSingularDataPoints(metricData, encoder) { + return metricData.dataPoints.map((dataPoint) => { + return toSingularDataPoint(dataPoint, metricData.descriptor.valueType, encoder); + }); + } + function toHistogramDataPoints(metricData, encoder) { + return metricData.dataPoints.map((dataPoint) => { + const histogram = dataPoint.value; + return { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes, encoder), + bucketCounts: histogram.buckets.counts, + explicitBounds: histogram.buckets.boundaries, + count: histogram.count, + sum: histogram.sum, + min: histogram.min, + max: histogram.max, + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime) + }; + }); + } + function toExponentialHistogramDataPoints(metricData, encoder) { + return metricData.dataPoints.map((dataPoint) => { + const histogram = dataPoint.value; + return { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes, encoder), + count: histogram.count, + min: histogram.min, + max: histogram.max, + sum: histogram.sum, + positive: { + offset: histogram.positive.offset, + bucketCounts: histogram.positive.bucketCounts + }, + negative: { + offset: histogram.negative.offset, + bucketCounts: histogram.negative.bucketCounts + }, + scale: histogram.scale, + zeroCount: histogram.zeroCount, + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime) + }; + }); + } + function toAggregationTemporality(temporality) { + switch (temporality) { + case sdk_metrics_1.AggregationTemporality.DELTA: return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA; + case sdk_metrics_1.AggregationTemporality.CUMULATIVE: return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE; + } + } + function createExportMetricsServiceRequest(resourceMetrics, encoder) { + return { resourceMetrics: resourceMetrics.map((metrics) => toResourceMetrics(metrics, encoder)) }; + } + exports.createExportMetricsServiceRequest = createExportMetricsServiceRequest; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js +var require_metrics = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonMetricsSerializer = void 0; + const internal_1 = require_internal$1(); + const utils_1 = require_utils(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + exports.JsonMetricsSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportMetricsServiceRequest)([arg], utils_1.JSON_ENCODER); + return new TextEncoder().encode(JSON.stringify(request)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) return {}; + const decoder = new TextDecoder(); + try { + return JSON.parse(decoder.decode(arg)); + } catch (err) { + api_1.diag.warn(`Failed to parse metrics export response: ${err.message}. Returning empty response`); + return {}; + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js +var require_json$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonMetricsSerializer = void 0; + var metrics_1 = require_metrics(); + Object.defineProperty(exports, "JsonMetricsSerializer", { + enumerable: true, + get: function() { + return metrics_1.JsonMetricsSerializer; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js +var require_internal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createExportTraceServiceRequest = exports.toOtlpSpanEvent = exports.toOtlpLink = exports.sdkSpanToOtlpSpan = void 0; + const internal_1 = require_internal$3(); + const SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256; + const SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512; + /** + * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags + * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec. + */ + function buildSpanFlagsFrom(traceFlags, isRemote) { + let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK; + if (isRemote) flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK; + return flags; + } + function sdkSpanToOtlpSpan(span, encoder) { + const ctx = span.spanContext(); + const status = span.status; + const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : void 0; + return { + traceId: encoder.encodeSpanContext(ctx.traceId), + spanId: encoder.encodeSpanContext(ctx.spanId), + parentSpanId, + traceState: ctx.traceState?.serialize(), + name: span.name, + kind: span.kind == null ? 0 : span.kind + 1, + startTimeUnixNano: encoder.encodeHrTime(span.startTime), + endTimeUnixNano: encoder.encodeHrTime(span.endTime), + attributes: (0, internal_1.toAttributes)(span.attributes, encoder), + droppedAttributesCount: span.droppedAttributesCount, + events: span.events.map((event) => toOtlpSpanEvent(event, encoder)), + droppedEventsCount: span.droppedEventsCount, + status: { + code: status.code, + message: status.message + }, + links: span.links.map((link) => toOtlpLink(link, encoder)), + droppedLinksCount: span.droppedLinksCount, + flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote) + }; + } + exports.sdkSpanToOtlpSpan = sdkSpanToOtlpSpan; + function toOtlpLink(link, encoder) { + return { + attributes: link.attributes ? (0, internal_1.toAttributes)(link.attributes, encoder) : [], + spanId: encoder.encodeSpanContext(link.context.spanId), + traceId: encoder.encodeSpanContext(link.context.traceId), + traceState: link.context.traceState?.serialize(), + droppedAttributesCount: link.droppedAttributesCount || 0, + flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote) + }; + } + exports.toOtlpLink = toOtlpLink; + function toOtlpSpanEvent(timedEvent, encoder) { + return { + attributes: timedEvent.attributes ? (0, internal_1.toAttributes)(timedEvent.attributes, encoder) : [], + name: timedEvent.name, + timeUnixNano: encoder.encodeHrTime(timedEvent.time), + droppedAttributesCount: timedEvent.droppedAttributesCount || 0 + }; + } + exports.toOtlpSpanEvent = toOtlpSpanEvent; + function createExportTraceServiceRequest(spans, encoder) { + return { resourceSpans: spanRecordsToResourceSpans(spans, encoder) }; + } + exports.createExportTraceServiceRequest = createExportTraceServiceRequest; + function createResourceMap(readableSpans) { + const resourceMap = /* @__PURE__ */ new Map(); + for (const record of readableSpans) { + let ilsMap = resourceMap.get(record.resource); + if (!ilsMap) { + ilsMap = /* @__PURE__ */ new Map(); + resourceMap.set(record.resource, ilsMap); + } + const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ""}:${record.instrumentationScope.schemaUrl || ""}`; + let records = ilsMap.get(instrumentationScopeKey); + if (!records) { + records = []; + ilsMap.set(instrumentationScopeKey, records); + } + records.push(record); + } + return resourceMap; + } + function spanRecordsToResourceSpans(readableSpans, encoder) { + const resourceMap = createResourceMap(readableSpans); + const out = []; + const entryIterator = resourceMap.entries(); + let entry = entryIterator.next(); + while (!entry.done) { + const [resource, ilmMap] = entry.value; + const scopeResourceSpans = []; + const ilmIterator = ilmMap.values(); + let ilmEntry = ilmIterator.next(); + while (!ilmEntry.done) { + const scopeSpans = ilmEntry.value; + if (scopeSpans.length > 0) { + const spans = scopeSpans.map((readableSpan) => sdkSpanToOtlpSpan(readableSpan, encoder)); + scopeResourceSpans.push({ + scope: (0, internal_1.createInstrumentationScope)(scopeSpans[0].instrumentationScope, encoder), + spans, + schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl + }); + } + ilmEntry = ilmIterator.next(); + } + const processedResource = (0, internal_1.createResource)(resource, encoder); + const transformedSpans = { + resource: processedResource, + scopeSpans: scopeResourceSpans, + schemaUrl: processedResource.schemaUrl + }; + out.push(transformedSpans); + entry = entryIterator.next(); + } + return out; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js +var require_trace = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonTraceSerializer = void 0; + const internal_1 = require_internal(); + const utils_1 = require_utils(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + exports.JsonTraceSerializer = { + serializeRequest: (arg) => { + const request = (0, internal_1.createExportTraceServiceRequest)(arg, utils_1.JSON_ENCODER); + return new TextEncoder().encode(JSON.stringify(request)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) return {}; + const decoder = new TextDecoder(); + try { + return JSON.parse(decoder.decode(arg)); + } catch (err) { + api_1.diag.warn(`Failed to parse trace export response: ${err.message}. Returning empty response`); + return {}; + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js +var require_json = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonTraceSerializer = void 0; + var trace_1 = require_trace(); + Object.defineProperty(exports, "JsonTraceSerializer", { + enumerable: true, + get: function() { + return trace_1.JsonTraceSerializer; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-transformer@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-transformer/build/src/index.js +var require_src$4 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonTraceSerializer = exports.JsonMetricsSerializer = exports.JsonLogsSerializer = exports.ProtobufTraceSerializer = exports.ProtobufMetricsSerializer = exports.ProtobufLogsSerializer = exports.LogsExporterMetricsHelper = exports.TraceExporterMetricsHelper = exports.MetricsExporterMetricsHelper = void 0; + var metrics_1 = require_metrics$2(); + Object.defineProperty(exports, "MetricsExporterMetricsHelper", { + enumerable: true, + get: function() { + return metrics_1.MetricsExporterMetricsHelper; + } + }); + var trace_1 = require_trace$2(); + Object.defineProperty(exports, "TraceExporterMetricsHelper", { + enumerable: true, + get: function() { + return trace_1.TraceExporterMetricsHelper; + } + }); + var logs_1 = require_logs$3(); + Object.defineProperty(exports, "LogsExporterMetricsHelper", { + enumerable: true, + get: function() { + return logs_1.LogsExporterMetricsHelper; + } + }); + var protobuf_1 = require_protobuf$2(); + Object.defineProperty(exports, "ProtobufLogsSerializer", { + enumerable: true, + get: function() { + return protobuf_1.ProtobufLogsSerializer; + } + }); + var protobuf_2 = require_protobuf$1(); + Object.defineProperty(exports, "ProtobufMetricsSerializer", { + enumerable: true, + get: function() { + return protobuf_2.ProtobufMetricsSerializer; + } + }); + var protobuf_3 = require_protobuf(); + Object.defineProperty(exports, "ProtobufTraceSerializer", { + enumerable: true, + get: function() { + return protobuf_3.ProtobufTraceSerializer; + } + }); + var json_1 = require_json$2(); + Object.defineProperty(exports, "JsonLogsSerializer", { + enumerable: true, + get: function() { + return json_1.JsonLogsSerializer; + } + }); + var json_2 = require_json$1(); + Object.defineProperty(exports, "JsonMetricsSerializer", { + enumerable: true, + get: function() { + return json_2.JsonMetricsSerializer; + } + }); + var json_3 = require_json(); + Object.defineProperty(exports, "JsonTraceSerializer", { + enumerable: true, + get: function() { + return json_3.JsonTraceSerializer; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/util.js +/** +* Parses headers from config leaving only those that have defined values +* @param partialHeaders +*/ +function validateAndNormalizeHeaders(partialHeaders) { + const headers = {}; + Object.entries(partialHeaders ?? {}).forEach(([key, value]) => { + if (typeof value !== "undefined") headers[key] = String(value); + else diag.warn(`Header "${key}" has invalid value (${value}) and will be ignored`); + }); + return headers; +} +var init_util = __esmMin((() => { + init_esm$2(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-configuration.js +function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) { + return async () => { + const requiredHeaders = { ...await defaultHeaders() }; + const headers = {}; + if (fallbackHeaders != null) Object.assign(headers, await fallbackHeaders()); + if (userProvidedHeaders != null) Object.assign(headers, validateAndNormalizeHeaders(await userProvidedHeaders())); + return Object.assign(headers, requiredHeaders); + }; +} +function validateUserProvidedUrl(url) { + if (url == null) return; + try { + const base = globalThis.location?.href; + return new URL(url, base).href; + } catch { + throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`); + } +} +/** +* @param userProvidedConfiguration Configuration options provided by the user in code. +* @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. +* @param defaultConfiguration The defaults as defined by the exporter specification +*/ +function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + ...mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + headers: mergeHeaders(userProvidedConfiguration.headers, fallbackConfiguration.headers, defaultConfiguration.headers), + url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? fallbackConfiguration.url ?? defaultConfiguration.url + }; +} +function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { + return { + ...getSharedConfigurationDefaults(), + headers: async () => requiredHeaders, + url: "http://localhost:4318/" + signalResourcePath + }; +} +var init_otlp_http_configuration = __esmMin((() => { + init_shared_configuration(); + init_util(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-node-http-configuration.js +function httpAgentFactoryFromOptions(options) { + return async (protocol) => { + const isInsecure = protocol === "http:"; + const { Agent } = await (isInsecure ? import("http") : import("https")); + if (isInsecure) { + const { ca, cert, key, ...insecureOptions } = options; + return new Agent(insecureOptions); + } + return new Agent(options); + }; +} +/** +* @param userProvidedConfiguration Configuration options provided by the user in code. +* @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. +* @param defaultConfiguration The defaults as defined by the exporter specification +*/ +function mergeOtlpNodeHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + ...mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + agentFactory: userProvidedConfiguration.agentFactory ?? fallbackConfiguration.agentFactory ?? defaultConfiguration.agentFactory, + userAgent: userProvidedConfiguration.userAgent + }; +} +function getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { + return { + ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath), + agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }) + }; +} +var init_otlp_node_http_configuration = __esmMin((() => { + init_otlp_http_configuration(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js +function isExportHTTPErrorRetryable(statusCode) { + return statusCode === 429 || statusCode === 502 || statusCode === 503 || statusCode === 504; +} +function parseRetryAfterToMills(retryAfter) { + if (retryAfter == null) return; + const seconds = Number.parseInt(retryAfter, 10); + if (Number.isInteger(seconds)) return seconds > 0 ? seconds * 1e3 : -1; + const delay = new Date(retryAfter).getTime() - Date.now(); + if (delay >= 0) return delay; + return 0; +} +var init_is_export_retryable = __esmMin((() => {})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js +/** +* Sends data using http +* @param request +* @param url +* @param headers +* @param compression +* @param userAgent +* @param agent +* @param data +* @param timeoutMillis +*/ +function sendWithHttp(request, url, headers, compression, userAgent, agent, data, timeoutMillis) { + return new Promise((resolve) => { + const parsedUrl = new URL(url); + if (userAgent) headers["User-Agent"] = `${userAgent} ${DEFAULT_USER_AGENT}`; + else headers["User-Agent"] = DEFAULT_USER_AGENT; + const req = request(parsedUrl, { + method: "POST", + headers, + agent + }, (res) => { + const responseData = []; + let responseSize = 0; + res.on("data", (chunk) => { + responseSize += chunk.length; + if (responseSize > 4194304) { + resolve({ + status: "failure", + error: /* @__PURE__ */ new Error(`OTLP export response body exceeded size limit of ${MAX_RESPONSE_BODY_SIZE} bytes`) + }); + res.destroy(); + return; + } + responseData.push(chunk); + }); + res.on("end", () => { + if (res.statusCode && res.statusCode <= 299) resolve({ + status: "success", + data: Buffer.concat(responseData) + }); + else if (res.statusCode && isExportHTTPErrorRetryable(res.statusCode)) resolve({ + status: "retryable", + retryInMillis: parseRetryAfterToMills(res.headers["retry-after"]) + }); + else resolve({ + status: "failure", + error: new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString()) + }); + }); + res.on("error", (error) => { + if (res.statusCode && res.statusCode <= 299) resolve({ status: "success" }); + else if (res.statusCode && isExportHTTPErrorRetryable(res.statusCode)) resolve({ + status: "retryable", + error, + retryInMillis: parseRetryAfterToMills(res.headers["retry-after"]) + }); + else resolve({ + status: "failure", + error + }); + }); + }); + req.setTimeout(timeoutMillis, () => { + req.destroy(); + resolve({ + status: "retryable", + error: /* @__PURE__ */ new Error("Request timed out") + }); + }); + req.on("error", (error) => { + if (isHttpTransportNetworkErrorRetryable(error)) resolve({ + status: "retryable", + error + }); + else resolve({ + status: "failure", + error + }); + }); + compressAndSend(req, compression, data, (error) => { + resolve({ + status: "failure", + error + }); + }); + }); +} +function compressAndSend(req, compression, data, onError) { + let dataStream = readableFromUint8Array(data); + if (compression === "gzip") { + req.setHeader("Content-Encoding", "gzip"); + dataStream = dataStream.on("error", onError).pipe(zlib.createGzip()).on("error", onError); + } + dataStream.pipe(req).on("error", onError); +} +function readableFromUint8Array(buff) { + const readable = new Readable(); + readable.push(buff); + readable.push(null); + return readable; +} +function isHttpTransportNetworkErrorRetryable(error) { + const RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([ + "ECONNRESET", + "ECONNREFUSED", + "EPIPE", + "ETIMEDOUT", + "EAI_AGAIN", + "ENOTFOUND", + "ENETUNREACH", + "EHOSTUNREACH" + ]); + if ("code" in error && typeof error.code === "string") return RETRYABLE_NETWORK_ERROR_CODES.has(error.code); + return false; +} +var DEFAULT_USER_AGENT, MAX_RESPONSE_BODY_SIZE; +var init_http_transport_utils = __esmMin((() => { + init_is_export_retryable(); + init_types(); + init_version(); + DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION}`; + MAX_RESPONSE_BODY_SIZE = 4194304; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js +async function requestFunctionFactory(protocol) { + const { request } = await (protocol === "http:" ? import("http") : import("https")); + return request; +} +function createHttpExporterTransport(parameters) { + return new HttpExporterTransport(parameters); +} +var HttpExporterTransport; +var init_http_exporter_transport = __esmMin((() => { + init_http_transport_utils(); + HttpExporterTransport = class { + _utils = null; + _parameters; + constructor(parameters) { + this._parameters = parameters; + } + async send(data, timeoutMillis) { + const { agent, request } = await this._loadUtils(); + const headers = await this._parameters.headers(); + return sendWithHttp(request, this._parameters.url, headers, this._parameters.compression, this._parameters.userAgent, agent, data, timeoutMillis); + } + shutdown() {} + async _loadUtils() { + let utils = this._utils; + if (utils === null) { + const protocol = new URL(this._parameters.url).protocol; + const [agent, request] = await Promise.all([this._parameters.agentFactory(protocol), requestFunctionFactory(protocol)]); + utils = this._utils = { + agent, + request + }; + } + return utils; + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js +/** +* Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER] +*/ +function getJitter() { + return Math.random() * (2 * JITTER) - JITTER; +} +/** +* Creates an Exporter Transport that retries on 'retryable' response. +*/ +function createRetryingTransport(options) { + return new RetryingTransport(options.transport); +} +var MAX_ATTEMPTS, INITIAL_BACKOFF, MAX_BACKOFF, BACKOFF_MULTIPLIER, JITTER, RetryingTransport; +var init_retrying_transport = __esmMin((() => { + init_esm$2(); + MAX_ATTEMPTS = 5; + INITIAL_BACKOFF = 1e3; + MAX_BACKOFF = 5e3; + BACKOFF_MULTIPLIER = 1.5; + JITTER = .2; + RetryingTransport = class { + _transport; + constructor(transport) { + this._transport = transport; + } + retry(data, timeoutMillis, inMillis) { + return new Promise((resolve, reject) => { + setTimeout(() => { + this._transport.send(data, timeoutMillis).then(resolve, reject); + }, inMillis); + }); + } + async send(data, timeoutMillis) { + let attempts = MAX_ATTEMPTS; + let nextBackoff = INITIAL_BACKOFF; + const deadline = Date.now() + timeoutMillis; + let result = await this._transport.send(data, timeoutMillis); + while (result.status === "retryable" && attempts > 0) { + attempts--; + const backoff = Math.max(Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF), 0); + nextBackoff = nextBackoff * BACKOFF_MULTIPLIER; + const retryInMillis = result.retryInMillis ?? backoff; + const remainingTimeoutMillis = deadline - Date.now(); + if (retryInMillis > remainingTimeoutMillis) { + diag.info(`Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(remainingTimeoutMillis)}ms, not retrying further.`); + return result; + } + diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`); + result = await this.retry(data, remainingTimeoutMillis, retryInMillis); + } + if (result.status === "success") diag.verbose(`Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`); + else if (result.status === "retryable") diag.info(`Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`); + else diag.info(`Export failed with non-retryable error: ${result.error}`); + return result; + } + shutdown() { + return this._transport.shutdown(); + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js +function createOtlpHttpExporterMetrics(metricsComponentType, exporterMetricsHelper, url, meterProvider) { + return new ExporterMetrics({ + componentType: metricsComponentType, + metricsHelper: exporterMetricsHelper, + url, + meterProvider, + responseAttributesFromError: (error) => { + if (!error) return { [ATTR_HTTP_RESPONSE_STATUS_CODE]: 200 }; + if (!(error instanceof OTLPExporterError)) return {}; + return { [ATTR_HTTP_RESPONSE_STATUS_CODE]: error.code }; + } + }); +} +function createOtlpHttpExportDelegate(options, serializer, metricsComponentType, exporterMetricsHelper, meterProvider) { + return createOtlpExportDelegate({ + transport: createRetryingTransport({ transport: createHttpExporterTransport(options) }), + serializer, + promiseHandler: createBoundedQueueExportPromiseHandler(options), + metrics: createOtlpHttpExporterMetrics(metricsComponentType, exporterMetricsHelper, options.url, meterProvider) + }, { timeout: options.timeoutMillis }); +} +var init_otlp_http_export_delegate = __esmMin((() => { + init_otlp_export_delegate(); + init_http_exporter_transport(); + init_bounded_queue_export_promise_handler(); + init_retrying_transport(); + init_types(); + init_semconv(); + init_ExporterMetrics(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-env-configuration.js +function parseAndValidateTimeoutFromEnv(timeoutEnvVar) { + const envTimeout = (0, import_src$6.getNumberFromEnv)(timeoutEnvVar); + if (envTimeout != null) { + if (Number.isFinite(envTimeout) && envTimeout > 0) return envTimeout; + diag.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`); + } +} +function getTimeoutFromEnv(signalIdentifier) { + const specificTimeout = parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`); + const nonSpecificTimeout = parseAndValidateTimeoutFromEnv("OTEL_EXPORTER_OTLP_TIMEOUT"); + return specificTimeout ?? nonSpecificTimeout; +} +function parseAndValidateCompressionFromEnv(compressionEnvVar) { + const compression = (0, import_src$6.getStringFromEnv)(compressionEnvVar)?.trim(); + if (compression == null || compression === "none" || compression === "gzip") return compression; + diag.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`); +} +function getCompressionFromEnv(signalIdentifier) { + const specificCompression = parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`); + const nonSpecificCompression = parseAndValidateCompressionFromEnv("OTEL_EXPORTER_OTLP_COMPRESSION"); + return specificCompression ?? nonSpecificCompression; +} +function getSharedConfigurationFromEnvironment(signalIdentifier) { + return { + timeoutMillis: getTimeoutFromEnv(signalIdentifier), + compression: getCompressionFromEnv(signalIdentifier) + }; +} +var import_src$6; +var init_shared_env_configuration = __esmMin((() => { + import_src$6 = require_src$8(); + init_esm$2(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-node-http-env-configuration.js +function getStaticHeadersFromEnv(signalIdentifier) { + const signalSpecificRawHeaders = (0, import_src$5.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`); + const nonSignalSpecificRawHeaders = (0, import_src$5.getStringFromEnv)("OTEL_EXPORTER_OTLP_HEADERS"); + const signalSpecificHeaders = (0, import_src$5.parseKeyPairsIntoRecord)(signalSpecificRawHeaders); + const nonSignalSpecificHeaders = (0, import_src$5.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders); + if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) return; + return Object.assign({}, (0, import_src$5.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders), (0, import_src$5.parseKeyPairsIntoRecord)(signalSpecificRawHeaders)); +} +function appendRootPathToUrlIfNeeded(url) { + try { + return new URL(url).toString(); + } catch { + diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); + return; + } +} +function appendResourcePathToUrl(url, path) { + try { + new URL(url); + } catch { + diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); + return; + } + if (!url.endsWith("/")) url = url + "/"; + url += path; + try { + new URL(url); + } catch { + diag.warn(`Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`); + return; + } + return url; +} +function getNonSpecificUrlFromEnv(signalResourcePath) { + const envUrl = (0, import_src$5.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT"); + if (envUrl === void 0) return; + return appendResourcePathToUrl(envUrl, signalResourcePath); +} +function getSpecificUrlFromEnv(signalIdentifier) { + const envUrl = (0, import_src$5.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`); + if (envUrl === void 0) return; + return appendRootPathToUrlIfNeeded(envUrl); +} +function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) { + const signalSpecificPath = (0, import_src$5.getStringFromEnv)(signalSpecificEnvVar); + const nonSignalSpecificPath = (0, import_src$5.getStringFromEnv)(nonSignalSpecificEnvVar); + const filePath = signalSpecificPath ?? nonSignalSpecificPath; + if (filePath != null) try { + return fs.readFileSync(path.resolve(process.cwd(), filePath)); + } catch { + diag.warn(warningMessage); + return; + } + else return; +} +function getClientCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file"); +} +function getClientKeyFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file"); +} +function getRootCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file"); +} +/** +* Reads and returns configuration from the environment +* +* @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS) +* @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs) +*/ +function getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) { + return { + ...getSharedConfigurationFromEnvironment(signalIdentifier), + url: getSpecificUrlFromEnv(signalIdentifier) ?? getNonSpecificUrlFromEnv(signalResourcePath), + headers: wrapStaticHeadersInFunction(getStaticHeadersFromEnv(signalIdentifier)), + agentFactory: httpAgentFactoryFromOptions({ + keepAlive: true, + ca: getRootCertificateFromEnv(signalIdentifier), + cert: getClientCertificateFromEnv(signalIdentifier), + key: getClientKeyFromEnv(signalIdentifier) + }) + }; +} +var import_src$5; +var init_otlp_node_http_env_configuration = __esmMin((() => { + import_src$5 = require_src$8(); + init_esm$2(); + init_shared_env_configuration(); + init_shared_configuration(); + init_otlp_node_http_configuration(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-http-options.js +function convertLegacyHeaders(config) { + if (typeof config.headers === "function") return config.headers; + return wrapStaticHeadersInFunction(config.headers); +} +var init_convert_legacy_http_options = __esmMin((() => { + init_shared_configuration(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-node-http-options.js +function convertLegacyAgentOptions(config) { + if (typeof config.httpAgentOptions === "function") return config.httpAgentOptions; + let legacy = config.httpAgentOptions; + if (config.keepAlive != null) legacy = { + keepAlive: config.keepAlive, + ...legacy + }; + if (legacy != null) return httpAgentFactoryFromOptions(legacy); + else return; +} +/** +* @deprecated this will be removed in 2.0 +* @param config +* @param signalIdentifier +* @param signalResourcePath +* @param requiredHeaders +*/ +function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) { + if (config.metadata) diag.warn("Metadata cannot be set when using http"); + return mergeOtlpNodeHttpConfigurationWithDefaults({ + url: config.url, + headers: convertLegacyHeaders(config), + concurrencyLimit: config.concurrencyLimit, + timeoutMillis: config.timeoutMillis, + compression: config.compression, + agentFactory: convertLegacyAgentOptions(config), + userAgent: config.userAgent + }, getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath), getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath)); +} +var init_convert_legacy_node_http_options = __esmMin((() => { + init_esm$2(); + init_otlp_node_http_configuration(); + init_index_node_http(); + init_otlp_node_http_env_configuration(); + init_convert_legacy_http_options(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+otlp-exporter-base@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/otlp-exporter-base/build/esm/index-node-http.js +var index_node_http_exports = /* @__PURE__ */ __exportAll({ + convertLegacyHttpOptions: () => convertLegacyHttpOptions, + createOtlpHttpExportDelegate: () => createOtlpHttpExportDelegate, + createOtlpHttpExporterMetrics: () => createOtlpHttpExporterMetrics, + getSharedConfigurationFromEnvironment: () => getSharedConfigurationFromEnvironment, + httpAgentFactoryFromOptions: () => httpAgentFactoryFromOptions +}); +var init_index_node_http = __esmMin((() => { + init_otlp_node_http_configuration(); + init_otlp_http_export_delegate(); + init_shared_env_configuration(); + init_convert_legacy_node_http_options(); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/semconv.js +var require_semconv$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTEL_COMPONENT_TYPE_VALUE_OTLP_HTTP_SPAN_EXPORTER = void 0; + /** + * Enum value "otlp_http_span_exporter" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}. + * + * OTLP span exporter over HTTP with protobuf serialization + * + * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.OTEL_COMPONENT_TYPE_VALUE_OTLP_HTTP_SPAN_EXPORTER = "otlp_http_span_exporter"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js +var require_OTLPTraceExporter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = void 0; + const otlp_exporter_base_1 = (init_esm(), __toCommonJS(esm_exports)); + const otlp_transformer_1 = require_src$4(); + const node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports)); + const semconv_1 = require_semconv$1(); + /** + * Collector Trace Exporter for Node + */ + var OTLPTraceExporter = class extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "TRACES", "v1/traces", { "Content-Type": "application/json" }), otlp_transformer_1.JsonTraceSerializer, semconv_1.OTEL_COMPONENT_TYPE_VALUE_OTLP_HTTP_SPAN_EXPORTER, otlp_transformer_1.TraceExporterMetricsHelper, config.selfObsMeterProvider)); + } + }; + exports.OTLPTraceExporter = OTLPTraceExporter; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js +var require_node$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = void 0; + var OTLPTraceExporter_1 = require_OTLPTraceExporter(); + Object.defineProperty(exports, "OTLPTraceExporter", { + enumerable: true, + get: function() { + return OTLPTraceExporter_1.OTLPTraceExporter; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js +var require_platform$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = void 0; + var node_1 = require_node$1(); + Object.defineProperty(exports, "OTLPTraceExporter", { + enumerable: true, + get: function() { + return node_1.OTLPTraceExporter; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+exporter-trace-otlp-http@0.222.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js +var require_src$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = void 0; + var platform_1 = require_platform$1(); + Object.defineProperty(exports, "OTLPTraceExporter", { + enumerable: true, + get: function() { + return platform_1.OTLPTraceExporter; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/enums.js +var require_enums = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExceptionEventName = void 0; + exports.ExceptionEventName = "exception"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/inspect.js +var require_inspect = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatInspect = exports.settledResourceAttributes = exports.inspectCustom = void 0; + /** + * Well-known symbol used by Node.js `util.inspect` (and `console.*`) to + * render an object via a custom representation. Defined as a global Symbol + * so it works without importing from `node:util`, keeping this module safe + * for browser builds (where the symbol is simply never looked up). + */ + exports.inspectCustom = Symbol.for("nodejs.util.inspect.custom"); + /** + * Collect a Resource's settled attributes without touching the + * `attributes` getter, which emits diag.error/debug entries when async + * attribute detectors are still pending. Promise-like (unsettled) + * entries are silently skipped so logging a Span/Tracer/Provider during + * startup doesn't recurse through the diag pipeline. + */ + function settledResourceAttributes(resource) { + const attrs = {}; + for (const [k, v] of resource.getRawAttributes()) { + if (typeof v?.then === "function") continue; + if (v != null) attrs[k] ??= v; + } + return attrs; + } + exports.settledResourceAttributes = settledResourceAttributes; + /** + * Build a class-tagged inspect representation. Returns a stub like + * `[ClassName]` once the recursion budget is exhausted, otherwise returns + * `ClassName ` so nested fields keep proper coloring, + * indentation, and depth handling. In environments that don't supply an + * `inspect` callback (e.g. browsers), falls back to returning the raw + * payload object. + */ + function formatInspect(className, payload, depth, options, inspect) { + if (typeof depth === "number" && depth < 0) { + const tag = `[${className}]`; + return options?.stylize ? options.stylize(tag, "special") : tag; + } + if (typeof inspect !== "function" || !options) return payload; + return `${className} ${inspect(payload, { + ...options, + depth: options.depth == null ? options.depth : options.depth - 1 + })}`; + } + exports.formatInspect = formatInspect; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/Span.js +var require_Span = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanImpl = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const semantic_conventions_1 = (init_esm$1(), __toCommonJS(esm_exports$1)); + const enums_1 = require_enums(); + const inspect_1 = require_inspect(); + /** + * This class represents a span. + */ + var SpanImpl = class { + _spanContext; + kind; + parentSpanContext; + attributes = {}; + links = []; + events = []; + startTime; + resource; + instrumentationScope; + _droppedAttributesCount = 0; + _droppedEventsCount = 0; + _droppedLinksCount = 0; + _attributesCount = 0; + name; + status = { code: api_1.SpanStatusCode.UNSET }; + endTime = [0, 0]; + _ended = false; + _duration = [-1, -1]; + _spanProcessor; + _spanLimits; + _attributeValueLengthLimit; + _recordEndMetrics; + _performanceStartTime; + _performanceOffset; + _startTimeProvided; + /** + * Constructs a new SpanImpl instance. + */ + constructor(opts) { + const now = Date.now(); + this._spanContext = opts.spanContext; + this._performanceStartTime = core_1.otperformance.now(); + this._performanceOffset = now - (this._performanceStartTime + core_1.otperformance.timeOrigin); + this._startTimeProvided = opts.startTime != null; + this._spanLimits = opts.spanLimits; + this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit ?? 0; + this._spanProcessor = opts.spanProcessor; + this.name = opts.name; + this.parentSpanContext = opts.parentSpanContext; + this.kind = opts.kind; + if (opts.links) for (const link of opts.links) this.addLink(link); + this.startTime = this._getTime(opts.startTime ?? now); + this.resource = opts.resource; + this.instrumentationScope = opts.scope; + this._recordEndMetrics = opts.recordEndMetrics; + if (opts.attributes != null) this.setAttributes(opts.attributes); + this._spanProcessor.onStart(this, opts.context); + } + spanContext() { + return this._spanContext; + } + setAttribute(key, value) { + if (value == null || this._isSpanEnded()) return this; + if (key.length === 0) { + api_1.diag.warn(`Invalid attribute key: ${key}`); + return this; + } + if (!(0, core_1.isAttributeValue)(value)) { + api_1.diag.warn(`Invalid attribute value set for key: ${key}`); + return this; + } + const { attributeCountLimit } = this._spanLimits; + const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key); + if (attributeCountLimit !== void 0 && this._attributesCount >= attributeCountLimit && isNewKey) { + this._droppedAttributesCount++; + return this; + } + this.attributes[key] = this._truncateToSize(value); + if (isNewKey) this._attributesCount++; + return this; + } + setAttributes(attributes) { + for (const key in attributes) if (Object.prototype.hasOwnProperty.call(attributes, key)) this.setAttribute(key, attributes[key]); + return this; + } + /** + * + * @param name Span Name + * @param [attributesOrStartTime] Span attributes or start time + * if type is {@type TimeInput} and 3rd param is undefined + * @param [timeStamp] Specified time stamp for the event + */ + addEvent(name, attributesOrStartTime, timeStamp) { + if (this._isSpanEnded()) return this; + const { eventCountLimit } = this._spanLimits; + if (eventCountLimit === 0) { + api_1.diag.warn("No events allowed."); + this._droppedEventsCount++; + return this; + } + if (eventCountLimit !== void 0 && this.events.length >= eventCountLimit) { + if (this._droppedEventsCount === 0) api_1.diag.debug("Dropping extra events."); + this.events.shift(); + this._droppedEventsCount++; + } + if ((0, core_1.isTimeInput)(attributesOrStartTime)) { + if (!(0, core_1.isTimeInput)(timeStamp)) timeStamp = attributesOrStartTime; + attributesOrStartTime = void 0; + } + const sanitized = (0, core_1.sanitizeAttributes)(attributesOrStartTime); + const { attributePerEventCountLimit } = this._spanLimits; + const attributes = {}; + let droppedAttributesCount = 0; + let eventAttributesCount = 0; + for (const attr in sanitized) { + if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) continue; + const attrVal = sanitized[attr]; + if (attributePerEventCountLimit !== void 0 && eventAttributesCount >= attributePerEventCountLimit) { + droppedAttributesCount++; + continue; + } + attributes[attr] = this._truncateToSize(attrVal); + eventAttributesCount++; + } + this.events.push({ + name, + attributes, + time: this._getTime(timeStamp), + droppedAttributesCount + }); + return this; + } + addLink(link) { + if (this._isSpanEnded()) return this; + const { linkCountLimit } = this._spanLimits; + if (linkCountLimit === 0) { + this._droppedLinksCount++; + return this; + } + if (linkCountLimit !== void 0 && this.links.length >= linkCountLimit) { + if (this._droppedLinksCount === 0) api_1.diag.debug("Dropping extra links."); + this.links.shift(); + this._droppedLinksCount++; + } + const { attributePerLinkCountLimit } = this._spanLimits; + const sanitized = (0, core_1.sanitizeAttributes)(link.attributes); + const attributes = {}; + let droppedAttributesCount = 0; + let linkAttributesCount = 0; + for (const attr in sanitized) { + if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) continue; + const attrVal = sanitized[attr]; + if (attributePerLinkCountLimit !== void 0 && linkAttributesCount >= attributePerLinkCountLimit) { + droppedAttributesCount++; + continue; + } + attributes[attr] = this._truncateToSize(attrVal); + linkAttributesCount++; + } + const processedLink = { context: link.context }; + if (linkAttributesCount > 0) processedLink.attributes = attributes; + if (droppedAttributesCount > 0) processedLink.droppedAttributesCount = droppedAttributesCount; + this.links.push(processedLink); + return this; + } + addLinks(links) { + for (const link of links) this.addLink(link); + return this; + } + setStatus(status) { + if (this._isSpanEnded()) return this; + if (status.code === api_1.SpanStatusCode.UNSET) return this; + if (this.status.code === api_1.SpanStatusCode.OK) return this; + const newStatus = { code: status.code }; + if (status.code === api_1.SpanStatusCode.ERROR) { + if (typeof status.message === "string") newStatus.message = status.message; + else if (status.message != null) api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`); + } + this.status = newStatus; + return this; + } + updateName(name) { + if (this._isSpanEnded()) return this; + this.name = name; + return this; + } + end(endTime) { + if (this._isSpanEnded()) { + api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`); + return; + } + this.endTime = this._getTime(endTime); + this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime); + if (this._duration[0] < 0) { + api_1.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime); + this.endTime = this.startTime.slice(); + this._duration = [0, 0]; + } + if (this._droppedEventsCount > 0) api_1.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`); + if (this._droppedLinksCount > 0) api_1.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`); + if (this._spanProcessor.onEnding) this._spanProcessor.onEnding(this); + this._recordEndMetrics?.(); + this._ended = true; + this._spanProcessor.onEnd(this); + } + _getTime(inp) { + if (typeof inp === "number" && inp <= core_1.otperformance.now()) return (0, core_1.hrTime)(inp + this._performanceOffset); + if (typeof inp === "number") return (0, core_1.millisToHrTime)(inp); + if (inp instanceof Date) return (0, core_1.millisToHrTime)(inp.getTime()); + if ((0, core_1.isTimeInputHrTime)(inp)) return inp; + if (this._startTimeProvided) return (0, core_1.millisToHrTime)(Date.now()); + const msDuration = core_1.otperformance.now() - this._performanceStartTime; + return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration)); + } + isRecording() { + return this._ended === false; + } + recordException(exception, time) { + const attributes = {}; + if (typeof exception === "string") attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception; + else if (exception) { + if (exception.code) attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.code.toString(); + else if (exception.name) attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.name; + if (exception.message) attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception.message; + if (exception.stack) attributes[semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE] = exception.stack; + } + if (attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] || attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE]) this.addEvent(enums_1.ExceptionEventName, attributes, time); + else api_1.diag.warn(`Failed to record an exception ${exception}`); + } + get duration() { + return this._duration; + } + get ended() { + return this._ended; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + get droppedEventsCount() { + return this._droppedEventsCount; + } + get droppedLinksCount() { + return this._droppedLinksCount; + } + _isSpanEnded() { + if (this._ended) { + const error = /* @__PURE__ */ new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`); + api_1.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error); + } + return this._ended; + } + _truncateToLimitUtil(value, limit) { + if (value.length <= limit) return value; + return value.substring(0, limit); + } + /** + * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then + * return string with truncated to {@code attributeValueLengthLimit} characters + * + * If the given attribute value is array of strings then + * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters + * + * Otherwise return same Attribute {@code value} + * + * @param value Attribute value + * @returns truncated attribute value if required, otherwise same value + */ + _truncateToSize(value) { + const limit = this._attributeValueLengthLimit; + if (limit <= 0) { + api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`); + return value; + } + if (typeof value === "string") return this._truncateToLimitUtil(value, limit); + if (Array.isArray(value)) return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val); + return value; + } + [inspect_1.inspectCustom](depth, options, inspect) { + const payload = { + name: this.name, + kind: this.kind, + spanContext: this._spanContext, + parentSpanContext: this.parentSpanContext, + status: this.status, + startTime: this.startTime, + endTime: this.endTime, + duration: this._duration, + ended: this._ended, + attributes: this.attributes, + events: this.events, + links: this.links, + droppedAttributesCount: this._droppedAttributesCount, + droppedEventsCount: this._droppedEventsCount, + droppedLinksCount: this._droppedLinksCount, + instrumentationScope: this.instrumentationScope, + resource: { attributes: (0, inspect_1.settledResourceAttributes)(this.resource) } + }; + return (0, inspect_1.formatInspect)("SpanImpl", payload, depth, options, inspect); + } + }; + exports.SpanImpl = SpanImpl; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/Sampler.js +var require_Sampler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SamplingDecision = void 0; + /** + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ + var SamplingDecision; + (function(SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(SamplingDecision || (exports.SamplingDecision = SamplingDecision = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/semconv.js +var require_semconv = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTEL_COMPONENT_TYPE_VALUE_SIMPLE_SPAN_PROCESSOR = exports.OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR = exports.METRIC_OTEL_SDK_SPAN_STARTED = exports.METRIC_OTEL_SDK_SPAN_LIVE = exports.METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE = exports.METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY = exports.METRIC_OTEL_SDK_PROCESSOR_SPAN_PROCESSED = exports.ATTR_OTEL_SPAN_SAMPLING_RESULT = exports.ATTR_OTEL_SPAN_PARENT_ORIGIN = exports.ATTR_OTEL_COMPONENT_TYPE = exports.ATTR_OTEL_COMPONENT_NAME = void 0; + /** + * A name uniquely identifying the instance of the OpenTelemetry component within its containing SDK instance. + * + * @example otlp_grpc_span_exporter/0 + * @example custom-name + * + * @note Implementations **SHOULD** ensure a low cardinality for this attribute, even across application or SDK restarts. + * E.g. implementations **MUST NOT** use UUIDs as values for this attribute. + * + * Implementations **MAY** achieve these goals by following a `/` pattern, e.g. `batching_span_processor/0`. + * Hereby `otel.component.type` refers to the corresponding attribute value of the component. + * + * The value of `instance-counter` **MAY** be automatically assigned by the component and uniqueness within the enclosing SDK instance **MUST** be guaranteed. + * For example, `` **MAY** be implemented by using a monotonically increasing counter (starting with `0`), which is incremented every time an + * instance of the given component type is started. + * + * With this implementation, for example the first Batching Span Processor would have `batching_span_processor/0` + * as `otel.component.name`, the second one `batching_span_processor/1` and so on. + * These values will therefore be reused in the case of an application restart. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OTEL_COMPONENT_NAME = "otel.component.name"; + /** + * A name identifying the type of the OpenTelemetry component. + * + * @example batching_span_processor + * @example com.example.MySpanExporter + * + * @note If none of the standardized values apply, implementations **SHOULD** use the language-defined name of the type. + * E.g. for Java the fully qualified classname **SHOULD** be used in this case. + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OTEL_COMPONENT_TYPE = "otel.component.type"; + /** + * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote) + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OTEL_SPAN_PARENT_ORIGIN = "otel.span.parent.origin"; + /** + * The result value of the sampler for this span + * + * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.ATTR_OTEL_SPAN_SAMPLING_RESULT = "otel.span.sampling_result"; + /** + * The number of spans for which the processing has finished, either successful or failed. + * + * @note For successful processing, `error.type` **MUST NOT** be set. For failed processing, `error.type` **MUST** contain the failure cause. + * For the SDK Simple and Batching Span Processor a span is considered to be processed already when it has been submitted to the exporter, not when the corresponding export call has finished. + * + * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.METRIC_OTEL_SDK_PROCESSOR_SPAN_PROCESSED = "otel.sdk.processor.span.processed"; + /** + * The maximum number of spans the queue of a given instance of an SDK span processor can hold. + * + * @note Only applies to span processors which use a queue, e.g. the SDK Batching Span Processor. + * + * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY = "otel.sdk.processor.span.queue.capacity"; + /** + * The number of spans in the queue of a given instance of an SDK span processor. + * + * @note Only applies to span processors which use a queue, e.g. the SDK Batching Span Processor. + * + * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE = "otel.sdk.processor.span.queue.size"; + /** + * The number of created spans with `recording=true` for which the end operation has not been called yet. + * + * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.METRIC_OTEL_SDK_SPAN_LIVE = "otel.sdk.span.live"; + /** + * The number of created spans. + * + * @note Implementations **MUST** record this metric for all spans, even for non-recording ones. + * + * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.METRIC_OTEL_SDK_SPAN_STARTED = "otel.sdk.span.started"; + /** + * Enum value "batching_span_processor" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}. + * + * The builtin SDK batching span processor + * + * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR = "batching_span_processor"; + /** + * Enum value "simple_span_processor" for attribute {@link ATTR_OTEL_COMPONENT_TYPE}. + * + * The builtin SDK simple span processor + * + * @experimental This enum value is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. + */ + exports.OTEL_COMPONENT_TYPE_VALUE_SIMPLE_SPAN_PROCESSOR = "simple_span_processor"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/TracerMetrics.js +var require_TracerMetrics = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TracerMetrics = void 0; + const Sampler_1 = require_Sampler(); + const semconv_1 = require_semconv(); + /** + * Generates `otel.sdk.span.*` metrics. + * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics + */ + var TracerMetrics = class { + startedSpans; + liveSpans; + constructor(meter) { + this.startedSpans = meter.createCounter(semconv_1.METRIC_OTEL_SDK_SPAN_STARTED, { + unit: "{span}", + description: "The number of created spans." + }); + this.liveSpans = meter.createUpDownCounter(semconv_1.METRIC_OTEL_SDK_SPAN_LIVE, { + unit: "{span}", + description: "The number of currently live spans." + }); + } + startSpan(parentSpanCtx, samplingDecision) { + const samplingDecisionStr = samplingDecisionToString(samplingDecision); + this.startedSpans.add(1, { + [semconv_1.ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx), + [semconv_1.ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr + }); + if (samplingDecision === Sampler_1.SamplingDecision.NOT_RECORD) return () => {}; + const liveSpanAttributes = { [semconv_1.ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr }; + this.liveSpans.add(1, liveSpanAttributes); + return () => { + this.liveSpans.add(-1, liveSpanAttributes); + }; + } + }; + exports.TracerMetrics = TracerMetrics; + function parentOrigin(parentSpanContext) { + if (!parentSpanContext) return "none"; + if (parentSpanContext.isRemote) return "remote"; + return "local"; + } + function samplingDecisionToString(decision) { + switch (decision) { + case Sampler_1.SamplingDecision.RECORD_AND_SAMPLED: return "RECORD_AND_SAMPLE"; + case Sampler_1.SamplingDecision.RECORD: return "RECORD_ONLY"; + case Sampler_1.SamplingDecision.NOT_RECORD: return "DROP"; + } + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/version.js +var require_version = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = void 0; + exports.VERSION = "2.11.0"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/Tracer.js +var require_Tracer = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Tracer = void 0; + const api = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const Span_1 = require_Span(); + const TracerMetrics_1 = require_TracerMetrics(); + const version_1 = require_version(); + const inspect_1 = require_inspect(); + /** + * This class represents a basic tracer. + */ + var Tracer = class { + _sampler; + _spanLimits; + _idGenerator; + instrumentationScope; + _resource; + _spanProcessor; + _tracerMetrics; + /** + * Constructs a new Tracer instance. + */ + constructor(instrumentationScope, options) { + this.instrumentationScope = instrumentationScope; + this._sampler = options.sampler; + this._spanLimits = options.spanLimits; + this._resource = options.resource; + this._idGenerator = options.idGenerator; + this._spanProcessor = options.spanProcessor; + const meter = options.meterProvider.getMeter("@opentelemetry/sdk-trace", version_1.VERSION); + this._tracerMetrics = new TracerMetrics_1.TracerMetrics(meter); + } + /** + * Starts a new Span or returns the default NoopSpan based on the sampling + * decision. + */ + startSpan(name, options = {}, context = api.context.active()) { + if (options.root) context = api.trace.deleteSpan(context); + const parentSpan = api.trace.getSpan(context); + if ((0, core_1.isTracingSuppressed)(context)) { + api.diag.debug("Instrumentation suppressed, returning Noop Span"); + return api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); + } + const parentSpanContext = parentSpan?.spanContext(); + const spanId = this._idGenerator.generateSpanId(); + let validParentSpanContext; + let traceId; + let traceState; + if (!parentSpanContext || !api.trace.isSpanContextValid(parentSpanContext)) traceId = this._idGenerator.generateTraceId(); + else { + traceId = parentSpanContext.traceId; + traceState = parentSpanContext.traceState; + validParentSpanContext = parentSpanContext; + } + const spanKind = options.kind ?? api.SpanKind.INTERNAL; + const links = (options.links ?? []).map((link) => { + return { + context: link.context, + attributes: (0, core_1.sanitizeAttributes)(link.attributes) + }; + }); + const attributes = (0, core_1.sanitizeAttributes)(options.attributes); + const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links); + const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision); + traceState = samplingResult.traceState ?? traceState; + const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE; + const spanContext = { + traceId, + spanId, + traceFlags, + traceState + }; + if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) { + api.diag.debug("Recording is off, propagating context in a non-recording span"); + return api.trace.wrapSpanContext(spanContext); + } + const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes)); + return new Span_1.SpanImpl({ + resource: this._resource, + scope: this.instrumentationScope, + context, + spanContext, + name, + kind: spanKind, + links, + parentSpanContext: validParentSpanContext, + attributes: initAttributes, + startTime: options.startTime, + spanProcessor: this._spanProcessor, + spanLimits: this._spanLimits, + recordEndMetrics + }); + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) return; + else if (arguments.length === 2) fn = arg2; + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx ?? api.context.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = api.trace.setSpan(parentContext, span); + return api.context.with(contextWithSpanSet, fn, void 0, span); + } + [inspect_1.inspectCustom](depth, options, inspect) { + const payload = { + instrumentationScope: this.instrumentationScope, + resource: { attributes: (0, inspect_1.settledResourceAttributes)(this._resource) }, + spanLimits: this._spanLimits + }; + return (0, inspect_1.formatInspect)("Tracer", payload, depth, options, inspect); + } + }; + exports.Tracer = Tracer; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/MultiSpanProcessor.js +var require_MultiSpanProcessor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MultiSpanProcessor = void 0; + const core_1 = require_src$8(); + /** + * Implementation of the {@link SpanProcessor} that simply forwards all + * received events to a list of {@link SpanProcessor}s. + */ + var MultiSpanProcessor = class { + _spanProcessors; + constructor(spanProcessors) { + this._spanProcessors = spanProcessors; + } + forceFlush() { + const promises = []; + for (const spanProcessor of this._spanProcessors) promises.push(spanProcessor.forceFlush()); + return new Promise((resolve) => { + Promise.all(promises).then(() => { + resolve(); + }).catch((error) => { + (0, core_1.globalErrorHandler)(error || /* @__PURE__ */ new Error("MultiSpanProcessor: forceFlush failed")); + resolve(); + }); + }); + } + onStart(span, context) { + for (const spanProcessor of this._spanProcessors) spanProcessor.onStart(span, context); + } + onEnding(span) { + for (const spanProcessor of this._spanProcessors) if (spanProcessor.onEnding) spanProcessor.onEnding(span); + } + onEnd(span) { + for (const spanProcessor of this._spanProcessors) spanProcessor.onEnd(span); + } + shutdown() { + const promises = []; + for (const spanProcessor of this._spanProcessors) promises.push(spanProcessor.shutdown()); + return new Promise((resolve, reject) => { + Promise.all(promises).then(() => { + resolve(); + }, reject); + }); + } + }; + exports.MultiSpanProcessor = MultiSpanProcessor; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/sampler/AlwaysOffSampler.js +var require_AlwaysOffSampler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AlwaysOffSampler = void 0; + const Sampler_1 = require_Sampler(); + /** Sampler that samples no traces. */ + var AlwaysOffSampler = class { + shouldSample() { + return { decision: Sampler_1.SamplingDecision.NOT_RECORD }; + } + toString() { + return "AlwaysOffSampler"; + } + }; + exports.AlwaysOffSampler = AlwaysOffSampler; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/sampler/AlwaysOnSampler.js +var require_AlwaysOnSampler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AlwaysOnSampler = void 0; + const Sampler_1 = require_Sampler(); + /** Sampler that samples all traces. */ + var AlwaysOnSampler = class { + shouldSample() { + return { decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED }; + } + toString() { + return "AlwaysOnSampler"; + } + }; + exports.AlwaysOnSampler = AlwaysOnSampler; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/sampler/ParentBasedSampler.js +var require_ParentBasedSampler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ParentBasedSampler = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const AlwaysOffSampler_1 = require_AlwaysOffSampler(); + const AlwaysOnSampler_1 = require_AlwaysOnSampler(); + /** + * A composite sampler that either respects the parent span's sampling decision + * or delegates to `delegateSampler` for root spans. + */ + var ParentBasedSampler = class { + _root; + _remoteParentSampled; + _remoteParentNotSampled; + _localParentSampled; + _localParentNotSampled; + constructor(config) { + this._root = config.root; + if (!this._root) { + (0, core_1.globalErrorHandler)(/* @__PURE__ */ new Error("ParentBasedSampler must have a root sampler configured")); + this._root = new AlwaysOnSampler_1.AlwaysOnSampler(); + } + this._remoteParentSampled = config.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler(); + this._remoteParentNotSampled = config.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler(); + this._localParentSampled = config.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler(); + this._localParentNotSampled = config.localParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler(); + } + shouldSample(context, traceId, spanName, spanKind, attributes, links) { + const parentContext = api_1.trace.getSpanContext(context); + if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links); + if (parentContext.isRemote) { + if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + toString() { + return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`; + } + }; + exports.ParentBasedSampler = ParentBasedSampler; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/export/SpanProcessorMetrics.js +var require_SpanProcessorMetrics = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanProcessorMetrics = void 0; + const semantic_conventions_1 = (init_esm$1(), __toCommonJS(esm_exports$1)); + const semconv_1 = require_semconv(); + const componentCounter = /* @__PURE__ */ new Map(); + var SpanProcessorMetrics = class { + processedSpans; + queueSize; + queueSizeCallback; + standardAttrs; + droppedAttrs; + constructor(componentType, meter, queueConfig) { + const counter = componentCounter.get(componentType) ?? 0; + componentCounter.set(componentType, counter + 1); + this.standardAttrs = { + [semconv_1.ATTR_OTEL_COMPONENT_TYPE]: componentType, + [semconv_1.ATTR_OTEL_COMPONENT_NAME]: `${componentType}/${counter}` + }; + this.droppedAttrs = { + ...this.standardAttrs, + [semantic_conventions_1.ATTR_ERROR_TYPE]: "queue_full" + }; + this.processedSpans = meter.createCounter(semconv_1.METRIC_OTEL_SDK_PROCESSOR_SPAN_PROCESSED, { + unit: "{span}", + description: "The number of spans for which the processing has finished, either successful or failed." + }); + if (queueConfig) { + const { capacity, getQueueSize } = queueConfig; + meter.createUpDownCounter(semconv_1.METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY, { + unit: "{span}", + description: "The maximum number of spans the queue of a given instance of an SDK span processor can hold." + }).add(capacity, this.standardAttrs); + this.queueSize = meter.createObservableUpDownCounter(semconv_1.METRIC_OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE, { + unit: "{span}", + description: "The number of spans in the queue of a given instance of an SDK span processor." + }); + this.queueSizeCallback = (result) => result.observe(getQueueSize(), this.standardAttrs); + this.queueSize.addCallback(this.queueSizeCallback); + } + } + dropSpans(count) { + this.processedSpans.add(count, this.droppedAttrs); + } + finishSpans(count, error) { + if (!error) { + this.processedSpans.add(count, this.standardAttrs); + return; + } + const attrs = { + ...this.standardAttrs, + [semantic_conventions_1.ATTR_ERROR_TYPE]: error.name + }; + this.processedSpans.add(count, attrs); + } + shutdown() { + if (this.queueSize && this.queueSizeCallback) this.queueSize.removeCallback(this.queueSizeCallback); + } + }; + exports.SpanProcessorMetrics = SpanProcessorMetrics; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/export/BatchSpanProcessorBase.js +var require_BatchSpanProcessorBase = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchSpanProcessorBase = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const SpanProcessorMetrics_1 = require_SpanProcessorMetrics(); + const semconv_1 = require_semconv(); + /** + * Implementation of the {@link SpanProcessor} that batches spans exported by + * the SDK then pushes them to the exporter pipeline. + */ + var BatchSpanProcessorBase = class { + _maxExportBatchSize; + _maxQueueSize; + _scheduledDelayMillis; + _exportTimeoutMillis; + _exporter; + _metrics; + _isExporting = false; + _finishedSpans = []; + _timer; + _shutdownOnce; + _droppedSpansCount = 0; + constructor(options) { + this._exporter = options.exporter; + this._maxExportBatchSize = options.maxExportBatchSize ?? 512; + this._maxQueueSize = options.maxQueueSize ?? 2048; + this._scheduledDelayMillis = options.scheduledDelayMillis ?? 5e3; + this._exportTimeoutMillis = options.exportTimeoutMillis ?? 3e4; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + if (this._maxExportBatchSize > this._maxQueueSize) { + api_1.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"); + this._maxExportBatchSize = this._maxQueueSize; + } + const meter = options.selfObsMeterProvider ? options.selfObsMeterProvider.getMeter("@opentelemetry/sdk-trace") : (0, api_1.createNoopMeter)(); + this._metrics = new SpanProcessorMetrics_1.SpanProcessorMetrics(semconv_1.OTEL_COMPONENT_TYPE_VALUE_BATCHING_SPAN_PROCESSOR, meter, { + capacity: this._maxQueueSize, + getQueueSize: () => this._finishedSpans.length + }); + } + forceFlush() { + if (this._shutdownOnce.isCalled) return this._shutdownOnce.promise; + return this._flushAll(); + } + onStart(_span, _parentContext) {} + onEnd(span) { + if (this._shutdownOnce.isCalled) return; + if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) return; + this._addToBuffer(span); + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + return Promise.resolve().then(() => { + return this.onShutdown(); + }).then(() => { + return this._flushAll(); + }).then(() => { + this._metrics.shutdown(); + return this._exporter.shutdown(); + }); + } + /** Add a span in the buffer. */ + _addToBuffer(span) { + if (this._finishedSpans.length >= this._maxQueueSize) { + if (this._droppedSpansCount === 0) api_1.diag.debug("maxQueueSize reached, dropping spans"); + this._droppedSpansCount++; + this._metrics.dropSpans(1); + return; + } + if (this._droppedSpansCount > 0) { + api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`); + this._droppedSpansCount = 0; + } + this._finishedSpans.push(span); + this._maybeStartTimer(); + } + /** + * Send all spans to the exporter respecting the batch size limit + * This function is used only on forceFlush or shutdown, + * for all other cases _flush should be used + * */ + _flushAll() { + return new Promise((resolve, reject) => { + const promises = []; + const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize); + for (let i = 0, j = count; i < j; i++) promises.push(this._flushOneBatch()); + Promise.all(promises).then(() => { + resolve(); + }).catch(reject); + }); + } + _flushOneBatch() { + this._clearTimer(); + if (this._finishedSpans.length === 0) return Promise.resolve(); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(/* @__PURE__ */ new Error("Timeout")); + }, this._exportTimeoutMillis); + api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => { + let spans; + if (this._finishedSpans.length <= this._maxExportBatchSize) { + spans = this._finishedSpans; + this._finishedSpans = []; + } else spans = this._finishedSpans.splice(0, this._maxExportBatchSize); + const doExport = () => this._exporter.export(spans, (result) => { + clearTimeout(timer); + this._metrics.finishSpans(spans.length, result.error); + if (result.code === core_1.ExportResultCode.SUCCESS) resolve(); + else reject(result.error ?? /* @__PURE__ */ new Error("BatchSpanProcessor: span export failed")); + }); + let pendingResources = null; + for (let i = 0, len = spans.length; i < len; i++) { + const span = spans[i]; + if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) { + pendingResources ??= []; + pendingResources.push(span.resource.waitForAsyncAttributes()); + } + } + if (pendingResources === null) doExport(); + else Promise.all(pendingResources).then(doExport, (err) => { + (0, core_1.globalErrorHandler)(err); + reject(err); + }); + }); + }); + } + _maybeStartTimer() { + if (this._isExporting) return; + const flush = () => { + this._isExporting = true; + this._flushOneBatch().finally(() => { + this._isExporting = false; + if (this._finishedSpans.length > 0) { + this._clearTimer(); + this._maybeStartTimer(); + } + }).catch((e) => { + this._isExporting = false; + (0, core_1.globalErrorHandler)(e); + }); + }; + if (this._finishedSpans.length >= this._maxExportBatchSize) return flush(); + if (this._timer !== void 0) return; + this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); + if (typeof this._timer !== "number") this._timer.unref(); + } + _clearTimer() { + if (this._timer !== void 0) { + clearTimeout(this._timer); + this._timer = void 0; + } + } + }; + exports.BatchSpanProcessorBase = BatchSpanProcessorBase; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/platform/node/export/BatchSpanProcessor.js +var require_BatchSpanProcessor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchSpanProcessor = void 0; + const BatchSpanProcessorBase_1 = require_BatchSpanProcessorBase(); + var BatchSpanProcessor = class extends BatchSpanProcessorBase_1.BatchSpanProcessorBase { + onShutdown() {} + }; + exports.BatchSpanProcessor = BatchSpanProcessor; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/platform/node/RandomIdGenerator.js +var require_RandomIdGenerator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RandomIdGenerator = void 0; + const SPAN_ID_BYTES = 8; + const TRACE_ID_BYTES = 16; + var RandomIdGenerator = class { + /** + * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex + * characters corresponding to 128 bits. + */ + generateTraceId = getIdGenerator(TRACE_ID_BYTES); + /** + * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex + * characters corresponding to 64 bits. + */ + generateSpanId = getIdGenerator(SPAN_ID_BYTES); + }; + exports.RandomIdGenerator = RandomIdGenerator; + const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES); + function getIdGenerator(bytes) { + return function generateId() { + for (let i = 0; i < bytes / 4; i++) SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i * 4); + for (let i = 0; i < bytes; i++) if (SHARED_BUFFER[i] > 0) break; + else if (i === bytes - 1) SHARED_BUFFER[bytes - 1] = 1; + return SHARED_BUFFER.toString("hex", 0, bytes); + }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/platform/node/index.js +var require_node = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0; + var BatchSpanProcessor_1 = require_BatchSpanProcessor(); + Object.defineProperty(exports, "BatchSpanProcessor", { + enumerable: true, + get: function() { + return BatchSpanProcessor_1.BatchSpanProcessor; + } + }); + var RandomIdGenerator_1 = require_RandomIdGenerator(); + Object.defineProperty(exports, "RandomIdGenerator", { + enumerable: true, + get: function() { + return RandomIdGenerator_1.RandomIdGenerator; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/platform/index.js +var require_platform = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0; + var node_1 = require_node(); + Object.defineProperty(exports, "BatchSpanProcessor", { + enumerable: true, + get: function() { + return node_1.BatchSpanProcessor; + } + }); + Object.defineProperty(exports, "RandomIdGenerator", { + enumerable: true, + get: function() { + return node_1.RandomIdGenerator; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/TracerProvider.js +var require_TracerProvider = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TracerProvider = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const resources_1 = require_src$6(); + const Tracer_1 = require_Tracer(); + const MultiSpanProcessor_1 = require_MultiSpanProcessor(); + const ParentBasedSampler_1 = require_ParentBasedSampler(); + const AlwaysOnSampler_1 = require_AlwaysOnSampler(); + const platform_1 = require_platform(); + const inspect_1 = require_inspect(); + var ForceFlushState; + (function(ForceFlushState) { + ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved"; + ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout"; + ForceFlushState[ForceFlushState["error"] = 2] = "error"; + ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved"; + })(ForceFlushState || (ForceFlushState = {})); + /** + * This class represents a basic tracer provider which platform libraries can extend + */ + var TracerProvider = class { + _resource; + _activeSpanProcessor; + _forceFlushTimeoutMillis; + _tracerOptions; + _tracers = /* @__PURE__ */ new Map(); + constructor(options = {}) { + this._forceFlushTimeoutMillis = options.forceFlushTimeoutMillis ?? 3e4; + this._resource = options.resource ?? (0, resources_1.defaultResource)(); + const spanProcessors = options.spanProcessors ?? []; + this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors); + this._tracerOptions = { + resource: this._resource, + sampler: options.sampler ?? new ParentBasedSampler_1.ParentBasedSampler({ root: new AlwaysOnSampler_1.AlwaysOnSampler() }), + spanLimits: { + attributeCountLimit: options.spanLimits?.attributeCountLimit ?? 128, + attributeValueLengthLimit: options.spanLimits?.attributeValueLengthLimit ?? Infinity, + eventCountLimit: options.spanLimits?.eventCountLimit ?? 128, + linkCountLimit: options.spanLimits?.linkCountLimit ?? 128, + attributePerEventCountLimit: options.spanLimits?.attributePerEventCountLimit ?? 128, + attributePerLinkCountLimit: options.spanLimits?.attributePerLinkCountLimit ?? 128 + }, + idGenerator: options.idGenerator || new platform_1.RandomIdGenerator(), + spanProcessor: this._activeSpanProcessor, + meterProvider: options.meterProvider ?? { getMeter() { + return (0, api_1.createNoopMeter)(); + } } + }; + } + getTracer(name, version, options) { + const key = `${name}@${version || ""}:${options?.schemaUrl || ""}`; + if (!this._tracers.has(key)) this._tracers.set(key, new Tracer_1.Tracer({ + name, + version, + schemaUrl: options?.schemaUrl + }, this._tracerOptions)); + return this._tracers.get(key); + } + forceFlush(options) { + const timeout = options?.timeoutMillis ?? this._forceFlushTimeoutMillis; + const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => { + return new Promise((resolve) => { + let state; + const timeoutInterval = setTimeout(() => { + resolve(/* @__PURE__ */ new Error(`Span processor did not completed within timeout period of ${timeout} ms`)); + state = ForceFlushState.timeout; + }, timeout); + spanProcessor.forceFlush().then(() => { + clearTimeout(timeoutInterval); + if (state !== ForceFlushState.timeout) { + state = ForceFlushState.resolved; + resolve(state); + } + }).catch((error) => { + clearTimeout(timeoutInterval); + state = ForceFlushState.error; + resolve(error); + }); + }); + }); + return new Promise((resolve, reject) => { + Promise.all(promises).then((results) => { + const errors = results.filter((result) => result !== ForceFlushState.resolved); + if (errors.length > 0) reject(errors); + else resolve(); + }).catch((error) => reject([error])); + }); + } + shutdown() { + return this._activeSpanProcessor.shutdown(); + } + [inspect_1.inspectCustom](depth, options, inspect) { + const processors = this._activeSpanProcessor["_spanProcessors"]; + const payload = { + resource: { attributes: (0, inspect_1.settledResourceAttributes)(this._resource) }, + tracers: Array.from(this._tracers.keys()), + spanProcessors: processors.map((p) => p.constructor?.name ?? "SpanProcessor") + }; + return (0, inspect_1.formatInspect)("TracerProvider", payload, depth, options, inspect); + } + }; + exports.TracerProvider = TracerProvider; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/export/ConsoleSpanExporter.js +var require_ConsoleSpanExporter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConsoleSpanExporter = void 0; + const core_1 = require_src$8(); + /** + * This is implementation of {@link SpanExporter} that prints spans to the + * console. This class can be used for diagnostic purposes. + * + * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time. + */ + var ConsoleSpanExporter = class { + /** + * Export spans. + * @param spans + * @param resultCallback + */ + export(spans, resultCallback) { + return this._sendSpans(spans, resultCallback); + } + /** + * Shutdown the exporter. + */ + shutdown() { + this._sendSpans([]); + return this.forceFlush(); + } + /** + * Exports any pending spans in exporter + */ + forceFlush() { + return Promise.resolve(); + } + /** + * converts span info into more readable format + * @param span + */ + _exportInfo(span) { + return { + resource: { attributes: span.resource.attributes }, + instrumentationScope: span.instrumentationScope, + traceId: span.spanContext().traceId, + parentSpanContext: span.parentSpanContext, + traceState: span.spanContext().traceState?.serialize(), + name: span.name, + id: span.spanContext().spanId, + kind: span.kind, + timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime), + duration: (0, core_1.hrTimeToMicroseconds)(span.duration), + attributes: span.attributes, + status: span.status, + events: span.events, + links: span.links + }; + } + /** + * Showing spans in console + * @param spans + * @param done + */ + _sendSpans(spans, done) { + for (const span of spans) console.dir(this._exportInfo(span), { depth: 3 }); + if (done) return done({ code: core_1.ExportResultCode.SUCCESS }); + } + }; + exports.ConsoleSpanExporter = ConsoleSpanExporter; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/export/InMemorySpanExporter.js +var require_InMemorySpanExporter = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InMemorySpanExporter = void 0; + const core_1 = require_src$8(); + /** + * This class can be used for testing purposes. It stores the exported spans + * in a list in memory that can be retrieved using the `getFinishedSpans()` + * method. + */ + var InMemorySpanExporter = class { + _finishedSpans = []; + /** + * Indicates if the exporter has been "shutdown." + * When false, exported spans will not be stored in-memory. + */ + _stopped = false; + export(spans, resultCallback) { + if (this._stopped) return resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: /* @__PURE__ */ new Error("Exporter has been stopped") + }); + this._finishedSpans.push(...spans); + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); + } + shutdown() { + this._stopped = true; + this._finishedSpans = []; + return this.forceFlush(); + } + /** + * Exports any pending spans in the exporter + */ + forceFlush() { + return Promise.resolve(); + } + reset() { + this._finishedSpans = []; + } + getFinishedSpans() { + return this._finishedSpans; + } + }; + exports.InMemorySpanExporter = InMemorySpanExporter; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/export/SimpleSpanProcessor.js +var require_SimpleSpanProcessor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SimpleSpanProcessor = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const SpanProcessorMetrics_1 = require_SpanProcessorMetrics(); + const semconv_1 = require_semconv(); + /** + * An implementation of the {@link SpanProcessor} that converts the {@link Span} + * to {@link ReadableSpan} and passes it to the configured exporter. + * + * Only spans that are sampled are converted. + * + * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead. + */ + var SimpleSpanProcessor = class { + _exporter; + _metrics; + _shutdownOnce; + _pendingExports; + constructor(options) { + this._exporter = options.exporter; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + this._pendingExports = /* @__PURE__ */ new Set(); + const meter = options.selfObsMeterProvider ? options.selfObsMeterProvider.getMeter("@opentelemetry/sdk-trace") : (0, api_1.createNoopMeter)(); + this._metrics = new SpanProcessorMetrics_1.SpanProcessorMetrics(semconv_1.OTEL_COMPONENT_TYPE_VALUE_SIMPLE_SPAN_PROCESSOR, meter); + } + async forceFlush() { + let pendingExportError; + let pendingExportRejected = false; + try { + await Promise.all(Array.from(this._pendingExports)); + } catch (err) { + pendingExportError = err; + pendingExportRejected = true; + } + if (this._exporter.forceFlush) await this._exporter.forceFlush(); + if (pendingExportRejected) throw pendingExportError; + } + onStart(_span, _parentContext) {} + onEnd(span) { + if (this._shutdownOnce.isCalled) return; + if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) return; + const pendingExport = this._doExport(span); + this._pendingExports.add(pendingExport); + pendingExport.then(() => { + this._pendingExports.delete(pendingExport); + }, (err) => { + (0, core_1.globalErrorHandler)(err); + this._pendingExports.delete(pendingExport); + }); + } + async _doExport(span) { + if (span.resource.asyncAttributesPending) await span.resource.waitForAsyncAttributes?.(); + const result = await core_1.internal._export(this._exporter, [span]); + this._metrics.finishSpans(1, result.error); + if (result.code !== core_1.ExportResultCode.SUCCESS) throw result.error ?? /* @__PURE__ */ new Error(`SimpleSpanProcessor: span export failed (status ${result})`); + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + this._metrics.shutdown(); + return this._exporter.shutdown(); + } + }; + exports.SimpleSpanProcessor = SimpleSpanProcessor; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/export/NoopSpanProcessor.js +var require_NoopSpanProcessor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopSpanProcessor = void 0; + /** No-op implementation of SpanProcessor */ + var NoopSpanProcessor = class { + onStart(_span, _context) {} + onEnd(_span) {} + shutdown() { + return Promise.resolve(); + } + forceFlush() { + return Promise.resolve(); + } + }; + exports.NoopSpanProcessor = NoopSpanProcessor; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/sampler/AlwaysRecordSampler.js +var require_AlwaysRecordSampler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createAlwaysRecordSampler = void 0; + const Sampler_1 = require_Sampler(); + /** + * Creates a sampler that wraps a delegate and upgrades NOT_RECORD decisions to + * RECORD, ensuring all spans are recorded without affecting the sampling rate. + */ + function createAlwaysRecordSampler(delegate) { + if (!delegate) throw new Error("createAlwaysRecordSampler requires a delegate sampler"); + return { + shouldSample(context, traceId, spanName, spanKind, attributes, links) { + const result = delegate.shouldSample(context, traceId, spanName, spanKind, attributes, links); + if (result.decision === Sampler_1.SamplingDecision.NOT_RECORD) return { + decision: Sampler_1.SamplingDecision.RECORD, + attributes: result.attributes, + traceState: result.traceState + }; + return result; + }, + toString() { + return `AlwaysRecordSampler{${delegate.toString()}}`; + } + }; + } + exports.createAlwaysRecordSampler = createAlwaysRecordSampler; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/sampler/TraceIdRatioBasedSampler.js +var require_TraceIdRatioBasedSampler = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceIdRatioBasedSampler = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const Sampler_1 = require_Sampler(); + /** Sampler that samples a given fraction of traces based of trace id deterministically. */ + var TraceIdRatioBasedSampler = class { + _ratio; + _upperBound; + constructor(ratio = 0) { + this._ratio = this._normalize(ratio); + this._upperBound = this._ratio === 1 ? 4294967296 : Math.floor(this._ratio * 4294967295); + } + shouldSample(context, traceId) { + return { decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound ? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED : Sampler_1.SamplingDecision.NOT_RECORD }; + } + toString() { + return `TraceIdRatioBased{${this._ratio}}`; + } + _normalize(ratio) { + if (typeof ratio !== "number" || isNaN(ratio)) return 0; + return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio; + } + _accumulate(traceId) { + let accumulation = 0; + for (let i = 0; i < 32; i += 8) { + let part = 0; + for (let j = 0; j < 8; j++) { + const c = traceId.charCodeAt(i + j); + const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87; + part = part << 4 | v; + } + accumulation = (accumulation ^ part) >>> 0; + } + return accumulation; + } + }; + exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace/build/src/index.js +var require_src$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.createAlwaysRecordSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.SimpleSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.RandomIdGenerator = exports.BatchSpanProcessor = exports.TracerProvider = void 0; + var TracerProvider_1 = require_TracerProvider(); + Object.defineProperty(exports, "TracerProvider", { + enumerable: true, + get: function() { + return TracerProvider_1.TracerProvider; + } + }); + var platform_1 = require_platform(); + Object.defineProperty(exports, "BatchSpanProcessor", { + enumerable: true, + get: function() { + return platform_1.BatchSpanProcessor; + } + }); + Object.defineProperty(exports, "RandomIdGenerator", { + enumerable: true, + get: function() { + return platform_1.RandomIdGenerator; + } + }); + var ConsoleSpanExporter_1 = require_ConsoleSpanExporter(); + Object.defineProperty(exports, "ConsoleSpanExporter", { + enumerable: true, + get: function() { + return ConsoleSpanExporter_1.ConsoleSpanExporter; + } + }); + var InMemorySpanExporter_1 = require_InMemorySpanExporter(); + Object.defineProperty(exports, "InMemorySpanExporter", { + enumerable: true, + get: function() { + return InMemorySpanExporter_1.InMemorySpanExporter; + } + }); + var SimpleSpanProcessor_1 = require_SimpleSpanProcessor(); + Object.defineProperty(exports, "SimpleSpanProcessor", { + enumerable: true, + get: function() { + return SimpleSpanProcessor_1.SimpleSpanProcessor; + } + }); + var NoopSpanProcessor_1 = require_NoopSpanProcessor(); + Object.defineProperty(exports, "NoopSpanProcessor", { + enumerable: true, + get: function() { + return NoopSpanProcessor_1.NoopSpanProcessor; + } + }); + var AlwaysOffSampler_1 = require_AlwaysOffSampler(); + Object.defineProperty(exports, "AlwaysOffSampler", { + enumerable: true, + get: function() { + return AlwaysOffSampler_1.AlwaysOffSampler; + } + }); + var AlwaysOnSampler_1 = require_AlwaysOnSampler(); + Object.defineProperty(exports, "AlwaysOnSampler", { + enumerable: true, + get: function() { + return AlwaysOnSampler_1.AlwaysOnSampler; + } + }); + var AlwaysRecordSampler_1 = require_AlwaysRecordSampler(); + Object.defineProperty(exports, "createAlwaysRecordSampler", { + enumerable: true, + get: function() { + return AlwaysRecordSampler_1.createAlwaysRecordSampler; + } + }); + var ParentBasedSampler_1 = require_ParentBasedSampler(); + Object.defineProperty(exports, "ParentBasedSampler", { + enumerable: true, + get: function() { + return ParentBasedSampler_1.ParentBasedSampler; + } + }); + var TraceIdRatioBasedSampler_1 = require_TraceIdRatioBasedSampler(); + Object.defineProperty(exports, "TraceIdRatioBasedSampler", { + enumerable: true, + get: function() { + return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler; + } + }); + var Sampler_1 = require_Sampler(); + Object.defineProperty(exports, "SamplingDecision", { + enumerable: true, + get: function() { + return Sampler_1.SamplingDecision; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js +var require_config = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildSamplerFromEnv = exports.loadDefaultConfig = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + const sdk_trace_1 = require_src$2(); + var TracesSamplerValues; + (function(TracesSamplerValues) { + TracesSamplerValues["AlwaysOff"] = "always_off"; + TracesSamplerValues["AlwaysOn"] = "always_on"; + TracesSamplerValues["ParentBasedAlwaysOff"] = "parentbased_always_off"; + TracesSamplerValues["ParentBasedAlwaysOn"] = "parentbased_always_on"; + TracesSamplerValues["ParentBasedTraceIdRatio"] = "parentbased_traceidratio"; + TracesSamplerValues["TraceIdRatio"] = "traceidratio"; + })(TracesSamplerValues || (TracesSamplerValues = {})); + const DEFAULT_RATIO = 1; + /** + * Load default configuration. For fields with primitive values, any user-provided + * value will override the corresponding default value. For fields with + * non-primitive values (like `spanLimits`), the user-provided value will be + * used to extend the default value. + */ + function loadDefaultConfig() { + return { + sampler: buildSamplerFromEnv(), + forceFlushTimeoutMillis: 3e4, + generalLimits: { + attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity, + attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128 + }, + spanLimits: { + attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity, + attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128, + linkCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128, + eventCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128, + attributePerEventCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128, + attributePerLinkCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128 + } + }; + } + exports.loadDefaultConfig = loadDefaultConfig; + /** + * Based on environment, builds a sampler, complies with specification. + */ + function buildSamplerFromEnv() { + const sampler = (0, core_1.getStringFromEnv)("OTEL_TRACES_SAMPLER") ?? TracesSamplerValues.ParentBasedAlwaysOn; + switch (sampler) { + case TracesSamplerValues.AlwaysOn: return new sdk_trace_1.AlwaysOnSampler(); + case TracesSamplerValues.AlwaysOff: return new sdk_trace_1.AlwaysOffSampler(); + case TracesSamplerValues.ParentBasedAlwaysOn: return new sdk_trace_1.ParentBasedSampler({ root: new sdk_trace_1.AlwaysOnSampler() }); + case TracesSamplerValues.ParentBasedAlwaysOff: return new sdk_trace_1.ParentBasedSampler({ root: new sdk_trace_1.AlwaysOffSampler() }); + case TracesSamplerValues.TraceIdRatio: return new sdk_trace_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()); + case TracesSamplerValues.ParentBasedTraceIdRatio: return new sdk_trace_1.ParentBasedSampler({ root: new sdk_trace_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()) }); + default: + api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`); + return new sdk_trace_1.ParentBasedSampler({ root: new sdk_trace_1.AlwaysOnSampler() }); + } + } + exports.buildSamplerFromEnv = buildSamplerFromEnv; + function getSamplerProbabilityFromEnv() { + const probability = (0, core_1.getNumberFromEnv)("OTEL_TRACES_SAMPLER_ARG"); + if (probability == null) { + api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + if (probability < 0 || probability > 1) { + api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + return probability; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js +var require_utility = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reconfigureLimits = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0; + const core_1 = require_src$8(); + exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128; + exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity; + /** + * When general limits are provided and model specific limits are not, + * configures the model specific limits by using the values from the general ones. + * @param userConfig User provided tracer configuration + */ + function reconfigureLimits(userConfig) { + const spanLimits = Object.assign({}, userConfig.spanLimits); + /** + * Reassign span attribute count limit to use first non null value defined by user or use default value + */ + spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT; + /** + * Reassign span attribute value length limit to use first non null value defined by user or use default value + */ + spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT; + return Object.assign({}, userConfig, { spanLimits }); + } + exports.reconfigureLimits = reconfigureLimits; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider-shim.js +var require_BasicTracerProvider_shim = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BasicTracerProvider = void 0; + const core_1 = require_src$8(); + const config_1 = require_config(); + const utility_1 = require_utility(); + const sdk_trace_1 = require_src$2(); + /** + * A TracerProvider implementation that reads configuration defaults from + * OTEL_* environment variables per + * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/ + */ + var BasicTracerProvider = class extends sdk_trace_1.TracerProvider { + constructor(config = {}) { + const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config)); + delete mergedConfig.generalLimits; + super(mergedConfig); + } + }; + exports.BasicTracerProvider = BasicTracerProvider; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/src/BatchSpanProcessor-shim.js +var require_BatchSpanProcessor_shim = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchSpanProcessor = void 0; + const core_1 = require_src$8(); + const sdk_trace_1 = require_src$2(); + /** + * A BatchSpanProcessor that applies `OTEL_*` environment variable fallbacks per + * https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/ + */ + var BatchSpanProcessor = class extends sdk_trace_1.BatchSpanProcessor { + constructor(exporter, config) { + if (!config) config = {}; + for (const [configName, envName] of [ + ["maxExportBatchSize", "OTEL_BSP_MAX_EXPORT_BATCH_SIZE"], + ["maxQueueSize", "OTEL_BSP_MAX_QUEUE_SIZE"], + ["scheduledDelayMillis", "OTEL_BSP_SCHEDULE_DELAY"], + ["exportTimeoutMillis", "OTEL_BSP_EXPORT_TIMEOUT"] + ]) if (config[configName] === void 0) { + const envFallback = (0, core_1.getNumberFromEnv)(envName); + if (envFallback !== void 0) config[configName] = envFallback; + } + super({ + exporter, + ...config + }); + } + }; + exports.BatchSpanProcessor = BatchSpanProcessor; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/src/SimpleSpanProcessor-shim.js +var require_SimpleSpanProcessor_shim = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SimpleSpanProcessor = void 0; + const sdk_trace_1 = require_src$2(); + /** + * A SimpleSpanProcessor with the old constructor call signature that + * takes just a single exporter argument. This version does not support + * the additional options that the SimpleSpanProcessor in sdk-trace does. + */ + var SimpleSpanProcessor = class extends sdk_trace_1.SimpleSpanProcessor { + constructor(exporter) { + super({ exporter }); + } + }; + exports.SimpleSpanProcessor = SimpleSpanProcessor; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-base@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-base/build/src/index-shim.js +var require_index_shim = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.InMemorySpanExporter = exports.RandomIdGenerator = exports.ConsoleSpanExporter = exports.SimpleSpanProcessor = exports.BatchSpanProcessor = exports.BasicTracerProvider = void 0; + var BasicTracerProvider_shim_1 = require_BasicTracerProvider_shim(); + Object.defineProperty(exports, "BasicTracerProvider", { + enumerable: true, + get: function() { + return BasicTracerProvider_shim_1.BasicTracerProvider; + } + }); + var BatchSpanProcessor_shim_1 = require_BatchSpanProcessor_shim(); + Object.defineProperty(exports, "BatchSpanProcessor", { + enumerable: true, + get: function() { + return BatchSpanProcessor_shim_1.BatchSpanProcessor; + } + }); + var SimpleSpanProcessor_shim_1 = require_SimpleSpanProcessor_shim(); + Object.defineProperty(exports, "SimpleSpanProcessor", { + enumerable: true, + get: function() { + return SimpleSpanProcessor_shim_1.SimpleSpanProcessor; + } + }); + var sdk_trace_1 = require_src$2(); + Object.defineProperty(exports, "ConsoleSpanExporter", { + enumerable: true, + get: function() { + return sdk_trace_1.ConsoleSpanExporter; + } + }); + Object.defineProperty(exports, "RandomIdGenerator", { + enumerable: true, + get: function() { + return sdk_trace_1.RandomIdGenerator; + } + }); + Object.defineProperty(exports, "InMemorySpanExporter", { + enumerable: true, + get: function() { + return sdk_trace_1.InMemorySpanExporter; + } + }); + Object.defineProperty(exports, "NoopSpanProcessor", { + enumerable: true, + get: function() { + return sdk_trace_1.NoopSpanProcessor; + } + }); + Object.defineProperty(exports, "AlwaysOffSampler", { + enumerable: true, + get: function() { + return sdk_trace_1.AlwaysOffSampler; + } + }); + Object.defineProperty(exports, "AlwaysOnSampler", { + enumerable: true, + get: function() { + return sdk_trace_1.AlwaysOnSampler; + } + }); + Object.defineProperty(exports, "ParentBasedSampler", { + enumerable: true, + get: function() { + return sdk_trace_1.ParentBasedSampler; + } + }); + Object.defineProperty(exports, "TraceIdRatioBasedSampler", { + enumerable: true, + get: function() { + return sdk_trace_1.TraceIdRatioBasedSampler; + } + }); + Object.defineProperty(exports, "SamplingDecision", { + enumerable: true, + get: function() { + return sdk_trace_1.SamplingDecision; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@langfuse+otel@5.11.1_@opentelemetry+api@1.9.1_@opentelemetry+core@2.11.0_@opentelemetry+api@_arcuz4zgoea7lbavwww3dmooja/node_modules/@langfuse/otel/dist/index.mjs +var import_src$3 = require_src$8(); +var import_src$4 = require_src$3(); +var import_index_shim = require_index_shim(); +var MediaService = class { + constructor(params) { + this.pendingMediaUploads = /* @__PURE__ */ new Set(); + this.apiClient = params.apiClient; + } + get logger() { + return getGlobalLogger(); + } + async flush() { + await Promise.all(Array.from(this.pendingMediaUploads)); + } + async process(span) { + var _a; + const mediaAttributes = [ + LangfuseOtelSpanAttributes.OBSERVATION_INPUT, + LangfuseOtelSpanAttributes.TRACE_INPUT, + LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT, + LangfuseOtelSpanAttributes.TRACE_OUTPUT, + LangfuseOtelSpanAttributes.OBSERVATION_METADATA, + LangfuseOtelSpanAttributes.TRACE_METADATA + ]; + for (const mediaAttribute of mediaAttributes) { + const mediaRelevantAttributeKeys = Object.keys(span.attributes).filter((attributeName) => attributeName.startsWith(mediaAttribute)); + for (const key of mediaRelevantAttributeKeys) { + const value = span.attributes[key]; + if (typeof value !== "string") { + this.logger.warn(`Span attribute ${mediaAttribute} is not a stringified object. Skipping media handling.`); + continue; + } + let mediaReplacedValue = value; + const foundMedia = [...new Set((_a = value.match(/data:[^;]+;base64,[A-Za-z0-9+/]+=*/g)) != null ? _a : [])]; + if (foundMedia.length === 0) continue; + for (const mediaDataUri of foundMedia) { + const media = new LangfuseMedia({ + base64DataUri: mediaDataUri, + source: "base64_data_uri" + }); + const langfuseMediaTag = await media.getTag(); + if (!langfuseMediaTag) { + this.logger.warn("Failed to create Langfuse media tag. Skipping media item."); + continue; + } + this.scheduleUpload({ + span, + media, + field: mediaAttribute.includes("input") ? "input" : mediaAttribute.includes("output") ? "output" : "metadata" + }); + mediaReplacedValue = mediaReplacedValue.replaceAll(mediaDataUri, langfuseMediaTag); + } + span.attributes[key] = mediaReplacedValue; + } + } + if (["ai", "gen_ai"].includes(span.instrumentationScope.name)) { + for (const mediaAttribute of ["ai.prompt.messages", "ai.prompt"]) { + const value = span.attributes[mediaAttribute]; + if (!value || typeof value !== "string") continue; + let mediaReplacedValue = value; + try { + const parsed = JSON.parse(value); + if (Array.isArray(parsed)) { + for (const message of parsed) if (Array.isArray(message["content"])) { + const contentParts = message["content"]; + for (const part of contentParts) if (part["type"] === "file") { + let base64Content = null; + const mediaType = part["mediaType"]; + if (typeof part["data"] === "string" && !part["data"].startsWith("http")) base64Content = part["data"]; + if (typeof part["image"] === "string" && !part["image"].startsWith("http")) base64Content = part["image"]; + if (!base64Content || typeof mediaType !== "string") continue; + mediaReplacedValue = await this.replaceBytesMedia({ + span, + mediaReplacedValue, + base64Content, + contentType: mediaType, + field: "input" + }); + } + } + } + span.attributes[mediaAttribute] = mediaReplacedValue; + } catch (err) { + this.logger.warn(`Failed to handle media for AI SDK attribute ${mediaAttribute} for span ${span.spanContext().spanId}`, err); + } + } + for (const { attribute, field } of [{ + attribute: "gen_ai.input.messages", + field: "input" + }, { + attribute: "gen_ai.output.messages", + field: "output" + }]) { + const value = span.attributes[attribute]; + if (!value || typeof value !== "string") continue; + let mediaReplacedValue = value; + try { + const parsed = JSON.parse(value); + if (Array.isArray(parsed)) for (const message of parsed) { + if (!Array.isArray(message["parts"])) continue; + for (const part of message["parts"]) { + const content = part["content"]; + const mediaType = part["mime_type"]; + if (part["type"] !== "blob" || typeof content !== "string" || !content || typeof mediaType !== "string" || content.startsWith("http")) continue; + const normalizedContent = normalizeBase64Content(content); + if (!normalizedContent) continue; + mediaReplacedValue = await this.replaceBytesMedia({ + span, + mediaReplacedValue, + base64Content: normalizedContent.base64Content, + contentToReplace: content, + contentType: mediaType, + field + }); + } + } + span.attributes[attribute] = mediaReplacedValue; + } catch (err) { + this.logger.warn(`Failed to handle media for AI SDK v7 attribute ${attribute} for span ${span.spanContext().spanId}`, err); + } + } + } + } + async replaceBytesMedia(params) { + var _a; + const media = new LangfuseMedia({ + contentType: params.contentType, + contentBytes: base64ToBytes(params.base64Content), + source: "bytes" + }); + const langfuseMediaTag = await media.getTag(); + if (!langfuseMediaTag) { + this.logger.warn("Failed to create Langfuse media tag. Skipping media item."); + return params.mediaReplacedValue; + } + this.scheduleUpload({ + span: params.span, + media, + field: params.field + }); + return params.mediaReplacedValue.replaceAll((_a = params.contentToReplace) != null ? _a : params.base64Content, langfuseMediaTag); + } + scheduleUpload(params) { + const { span, field, media } = params; + const uploadPromise = this.handleUpload({ + media, + traceId: span.spanContext().traceId, + observationId: span.spanContext().spanId, + field + }).catch((err) => { + this.logger.error("Media upload failed with error: ", err); + }); + this.pendingMediaUploads.add(uploadPromise); + uploadPromise.finally(() => { + this.pendingMediaUploads.delete(uploadPromise); + }); + } + async handleUpload({ media, traceId, observationId, field }) { + try { + await uploadMedia({ + apiClient: this.apiClient, + media, + traceId, + observationId, + field, + logger: this.logger + }); + } catch (err) { + this.logger.error(`Error processing media item: ${err}`); + } + } +}; +function normalizeBase64Content(content) { + if (!content.startsWith("data:")) return { base64Content: content }; + const base64Start = content.indexOf(";base64,"); + if (base64Start === -1) return; + const base64Content = content.slice(base64Start + 8); + if (!base64Content) return; + return { base64Content }; +} +var KNOWN_LLM_INSTRUMENTATION_SCOPE_PREFIXES = [ + LANGFUSE_TRACER_NAME, + "agent_framework", + "ai", + "haystack", + "langsmith", + "litellm", + "openinference", + "opentelemetry.instrumentation.anthropic", + "opentelemetry.instrumentation.aws_bedrock", + "opentelemetry.instrumentation.bedrock", + "opentelemetry.instrumentation.gemini", + "opentelemetry.instrumentation.google_genai", + "opentelemetry.instrumentation.google_generativeai", + "opentelemetry.instrumentation.openai", + "opentelemetry.instrumentation.openai_v2", + "opentelemetry.instrumentation.vertex_ai", + "opentelemetry.instrumentation.vertexai", + "strands-agents", + "vllm" +]; +var EXACT_LLM_INSTRUMENTATION_SCOPES = /* @__PURE__ */ new Set(["ai"]); +function isLangfuseSpan(span) { + return span.instrumentationScope.name === LANGFUSE_TRACER_NAME; +} +function isGenAISpan(span) { + return Object.keys(span.attributes).some((attributeKey) => attributeKey.startsWith("gen_ai.")); +} +function isKnownLLMInstrumentor(span) { + const scope = span.instrumentationScope.name; + return KNOWN_LLM_INSTRUMENTATION_SCOPE_PREFIXES.some((prefix) => scope === prefix || !EXACT_LLM_INSTRUMENTATION_SCOPES.has(prefix) && scope.startsWith(`${prefix}.`)); +} +function isDefaultExportSpan(span) { + return isLangfuseSpan(span) || isGenAISpan(span) || isKnownLLMInstrumentor(span); +} +var LangfuseSpanProcessor = class { + /** + * Creates a new LangfuseSpanProcessor instance. + * + * @param params - Configuration parameters for the processor + * + * @example + * ```typescript + * const processor = new LangfuseSpanProcessor({ + * publicKey: 'pk_...', + * secretKey: 'sk_...', + * environment: 'staging', + * flushAt: 10, + * flushInterval: 2, + * mask: ({ data }) => { + * // Custom masking logic + * return typeof data === 'string' + * ? data.replace(/secret_\w+/g, 'secret_***') + * : data; + * }, + * shouldExportSpan: ({ otelSpan }) => { + * // Full override of default filtering: + * // export only spans from specific services + * return otelSpan.name.startsWith("my-service"); + * } + * }); + * ``` + */ + constructor(params) { + this.pendingEndedSpans = /* @__PURE__ */ new Set(); + this.spanExportExpectationById = /* @__PURE__ */ new Map(); + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n; + const logger = getGlobalLogger(); + const publicKey = (_a = params == null ? void 0 : params.publicKey) != null ? _a : getEnv("LANGFUSE_PUBLIC_KEY"); + const secretKey = (_b = params == null ? void 0 : params.secretKey) != null ? _b : getEnv("LANGFUSE_SECRET_KEY"); + const baseUrl = (_e = (_d = (_c = params == null ? void 0 : params.baseUrl) != null ? _c : getEnv("LANGFUSE_BASE_URL")) != null ? _d : getEnv("LANGFUSE_BASEURL")) != null ? _e : "https://cloud.langfuse.com"; + if (!(params == null ? void 0 : params.exporter) && !publicKey) logger.warn("No exporter configured and no public key provided in constructor or as LANGFUSE_PUBLIC_KEY env var. Span exports will fail."); + if (!(params == null ? void 0 : params.exporter) && !secretKey) logger.warn("No exporter configured and no secret key provided in constructor or as LANGFUSE_SECRET_KEY env var. Span exports will fail."); + const flushAt = (_f = params == null ? void 0 : params.flushAt) != null ? _f : getEnv("LANGFUSE_FLUSH_AT"); + const flushIntervalSeconds = (_g = params == null ? void 0 : params.flushInterval) != null ? _g : getEnv("LANGFUSE_FLUSH_INTERVAL"); + const authHeaderValue = base64Encode(`${publicKey}:${secretKey}`); + const timeoutSeconds = (_i = params == null ? void 0 : params.timeout) != null ? _i : Number((_h = getEnv("LANGFUSE_TIMEOUT")) != null ? _h : 5); + const envMediaUploadEnabled = getEnv("LANGFUSE_MEDIA_UPLOAD_ENABLED"); + const mediaUploadEnabled = (_j = params == null ? void 0 : params.mediaUploadEnabled) != null ? _j : envMediaUploadEnabled ? !["false", "0"].includes(envMediaUploadEnabled.toLowerCase()) : true; + const exporter = (_k = params == null ? void 0 : params.exporter) != null ? _k : new import_src$4.OTLPTraceExporter({ + url: `${baseUrl}/api/public/otel/v1/traces`, + headers: { + Authorization: `Basic ${authHeaderValue}`, + "x-langfuse-sdk-name": "javascript", + "x-langfuse-sdk-version": LANGFUSE_SDK_VERSION, + "x-langfuse-public-key": publicKey != null ? publicKey : "", + ...params == null ? void 0 : params.additionalHeaders + }, + timeoutMillis: timeoutSeconds * 1e3 + }); + this.processor = (params == null ? void 0 : params.exportMode) === "immediate" ? new import_index_shim.SimpleSpanProcessor(exporter) : new import_index_shim.BatchSpanProcessor(exporter, { + maxExportBatchSize: flushAt ? Number(flushAt) : void 0, + scheduledDelayMillis: flushIntervalSeconds ? Number(flushIntervalSeconds) * 1e3 : void 0 + }); + this.publicKey = publicKey; + this.baseUrl = baseUrl; + this.environment = (_l = params == null ? void 0 : params.environment) != null ? _l : getEnv("LANGFUSE_TRACING_ENVIRONMENT"); + this.release = (_m = params == null ? void 0 : params.release) != null ? _m : getEnv("LANGFUSE_RELEASE"); + this.mask = params == null ? void 0 : params.mask; + this.shouldExportSpan = (_n = params == null ? void 0 : params.shouldExportSpan) != null ? _n : ({ otelSpan }) => isDefaultExportSpan(otelSpan); + this.mediaUploadEnabled = mediaUploadEnabled; + this.apiClient = new LangfuseAPIClient({ + baseUrl: this.baseUrl, + username: this.publicKey, + password: secretKey, + xLangfusePublicKey: this.publicKey, + xLangfuseSdkVersion: LANGFUSE_SDK_VERSION, + xLangfuseSdkName: "javascript", + environment: "", + headers: params == null ? void 0 : params.additionalHeaders + }); + this.mediaService = new MediaService({ apiClient: this.apiClient }); + logger.debug("Initialized LangfuseSpanProcessor with params:", { + publicKey, + baseUrl, + environment: this.environment, + release: this.release, + timeoutSeconds, + flushAt, + flushIntervalSeconds, + mediaUploadEnabled + }); + } + get logger() { + return getGlobalLogger(); + } + /** + * Called when a span is started. Adds environment, release, and propagated attributes to the span. + * + * @param span - The span that was started + * @param parentContext - The parent context + * + * @override + */ + onStart(span, parentContext) { + const propagatedAttributes = getPropagatedAttributesFromContext(parentContext); + if (span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME] != null) { + delete propagatedAttributes[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME]; + delete propagatedAttributes[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION]; + } + span.setAttributes({ + [LangfuseOtelSpanAttributes.ENVIRONMENT]: this.environment, + [LangfuseOtelSpanAttributes.RELEASE]: this.release, + ...propagatedAttributes + }); + try { + this.markAppRootCandidate(span, parentContext); + } catch (err) { + this.logger.debug("App-root start-time check failed. Span will not be marked as app root.", { spanName: span.name }, err); + } + return this.processor.onStart(span, parentContext); + } + /** + * Called when a span ends. Processes the span for export to Langfuse. + * + * This method: + * 1. Checks if the span should be exported using shouldExportSpan + * (custom override or default smart filter) + * 2. Applies data masking to sensitive attributes + * 3. Handles media content extraction and upload + * 4. Logs span details in debug mode + * 5. Passes the span to the parent processor for export + * + * @param span - The span that ended + * + * @override + */ + onEnd(span) { + this.spanExportExpectationById.delete(span.spanContext().spanId); + const processEndedSpanPromise = this.processEndedSpan(span).catch((err) => { + this.logger.error(err); + }); + this.pendingEndedSpans.add(processEndedSpanPromise); + processEndedSpanPromise.finally(() => this.pendingEndedSpans.delete(processEndedSpanPromise)); + } + async flush() { + await Promise.all(Array.from(this.pendingEndedSpans)); + await this.mediaService.flush(); + } + /** + * Forces an immediate flush of all pending spans and media uploads. + * + * @returns Promise that resolves when all pending operations are complete + * + * @override + */ + async forceFlush() { + await this.flush(); + return this.processor.forceFlush(); + } + /** + * Gracefully shuts down the processor, ensuring all pending operations are completed. + * + * @returns Promise that resolves when shutdown is complete + * + * @override + */ + async shutdown() { + await this.flush(); + return this.processor.shutdown(); + } + async processEndedSpan(span) { + var _a, _b; + try { + if (this.shouldExportSpan({ otelSpan: span }) === false) { + this.logger.debug("Dropped span due to shouldExportSpan filter.", { + spanName: span.name, + instrumentationScope: span.instrumentationScope.name + }); + return; + } + } catch (err) { + this.logger.error("shouldExportSpan failed with error. Dropping span.", { + spanName: span.name, + instrumentationScope: span.instrumentationScope.name + }, err); + return; + } + await this.applyMaskInPlace(span); + if (this.mediaUploadEnabled) await this.mediaService.process(span); + if (this.logger.isLevelEnabled(LogLevel.DEBUG)) this.logger.debug(`Processed span: +${JSON.stringify({ + name: span.name, + traceId: span.spanContext().traceId, + spanId: span.spanContext().spanId, + parentSpanId: (_b = (_a = span.parentSpanContext) == null ? void 0 : _a.spanId) != null ? _b : null, + attributes: span.attributes, + startTime: new Date((0, import_src$3.hrTimeToMilliseconds)(span.startTime)), + endTime: new Date((0, import_src$3.hrTimeToMilliseconds)(span.endTime)), + durationMs: (0, import_src$3.hrTimeToMilliseconds)(span.duration), + kind: span.kind, + status: span.status, + resource: span.resource.attributes, + instrumentationScope: span.instrumentationScope + }, null, 2)}`); + this.processor.onEnd(span); + } + markAppRootCandidate(span, parentContext) { + var _a; + const traceId = span.spanContext().traceId; + const spanId = span.spanContext().spanId; + const parentSpanId = (_a = span.parentSpanContext) == null ? void 0 : _a.spanId; + const expectedExportedAtStart = this.isExpectedExportedAtStart(span); + const propagatedClaim = getLangfuseTraceIdFromBaggage(parentContext); + const isParentExpectedExported = parentSpanId !== void 0 ? this.spanExportExpectationById.get(parentSpanId) === true : false; + const suppressedByParentClaim = propagatedClaim === traceId; + this.spanExportExpectationById.set(spanId, expectedExportedAtStart); + if (expectedExportedAtStart && !isParentExpectedExported && !suppressedByParentClaim) span.setAttribute(LangfuseOtelSpanAttributes.IS_APP_ROOT, true); + } + isExpectedExportedAtStart(span) { + const readable = span; + try { + return this.shouldExportSpan({ otelSpan: readable }) === true; + } catch (err) { + this.logger.debug("shouldExportSpan threw during app-root start-time check. Span will not be marked as app root.", { + spanName: span.name, + instrumentationScope: readable.instrumentationScope.name + }, err); + return false; + } + } + async applyMaskInPlace(span) { + const maskCandidates = [ + LangfuseOtelSpanAttributes.OBSERVATION_INPUT, + LangfuseOtelSpanAttributes.TRACE_INPUT, + LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT, + LangfuseOtelSpanAttributes.TRACE_OUTPUT, + LangfuseOtelSpanAttributes.OBSERVATION_METADATA, + LangfuseOtelSpanAttributes.TRACE_METADATA + ]; + for (const maskCandidate of maskCandidates) if (maskCandidate in span.attributes) span.attributes[maskCandidate] = await this.applyMask(span.attributes[maskCandidate]); + } + async applyMask(data) { + if (!this.mask) return data; + try { + return await this.mask({ data }); + } catch (err) { + this.logger.warn(`Applying mask function failed due to error, fully masking property. Error: ${err}`); + return ""; + } + } +}; + +//#endregion +//#region ../../node_modules/.pnpm/@langfuse+tracing@5.11.1_@opentelemetry+api@1.9.1/node_modules/@langfuse/tracing/dist/index.mjs +init_esm$2(); +function createTraceAttributes({ input, output } = {}) { + const attributes = { + [LangfuseOtelSpanAttributes.TRACE_INPUT]: _serialize(input), + [LangfuseOtelSpanAttributes.TRACE_OUTPUT]: _serialize(output) + }; + return Object.fromEntries(Object.entries(attributes).filter(([_, v]) => v != null)); +} +function createObservationAttributes(type, attributes) { + const { metadata, input, output, level, statusMessage, version, environment, completionStartTime, model, modelParameters, usageDetails, costDetails, prompt } = attributes; + let otelAttributes = { + [LangfuseOtelSpanAttributes.OBSERVATION_TYPE]: type, + [LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: level, + [LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage, + [LangfuseOtelSpanAttributes.VERSION]: version, + [LangfuseOtelSpanAttributes.ENVIRONMENT]: environment, + [LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input), + [LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output), + [LangfuseOtelSpanAttributes.OBSERVATION_MODEL]: model, + [LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS]: _serialize(usageDetails), + [LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS]: _serialize(costDetails), + [LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME]: _serialize(completionStartTime), + [LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]: _serialize(modelParameters), + ...prompt && !prompt.isFallback ? { + [LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME]: prompt.name, + [LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION]: prompt.version + } : {}, + ..._flattenAndSerializeMetadata(metadata, "observation") + }; + return Object.fromEntries(Object.entries(otelAttributes).filter(([_, v]) => v != null)); +} +function _serialize(obj) { + try { + if (typeof obj === "string") return obj; + return obj != null ? JSON.stringify(obj) : void 0; + } catch { + return ""; + } +} +function _flattenAndSerializeMetadata(metadata, type) { + const prefix = type === "observation" ? LangfuseOtelSpanAttributes.OBSERVATION_METADATA : LangfuseOtelSpanAttributes.TRACE_METADATA; + const metadataAttributes = {}; + if (metadata === void 0 || metadata === null) return metadataAttributes; + if (typeof metadata !== "object" || Array.isArray(metadata)) { + const serialized = _serialize(metadata); + if (serialized) metadataAttributes[prefix] = serialized; + } else for (const [key, value] of Object.entries(metadata)) { + const serialized = typeof value === "string" ? value : _serialize(value); + if (serialized) metadataAttributes[`${prefix}.${key}`] = serialized; + } + return metadataAttributes; +} +var LANGFUSE_GLOBAL_SYMBOL = Symbol.for("langfuse"); +function createState() { + return { isolatedTracerProvider: null }; +} +function getGlobalState() { + const initialState = createState(); + try { + const g = globalThis; + if (typeof g !== "object" || g === null) { + getGlobalLogger().warn("globalThis is not available, using fallback state"); + return initialState; + } + if (!g[LANGFUSE_GLOBAL_SYMBOL]) Object.defineProperty(g, LANGFUSE_GLOBAL_SYMBOL, { + value: initialState, + writable: false, + configurable: false, + enumerable: false + }); + return g[LANGFUSE_GLOBAL_SYMBOL]; + } catch (err) { + if (err instanceof Error) getGlobalLogger().error(`Failed to access global state: ${err.message}`); + else getGlobalLogger().error(`Failed to access global state: ${String(err)}`); + return initialState; + } +} +function setLangfuseTracerProvider(provider) { + getGlobalState().isolatedTracerProvider = provider; +} +function getLangfuseTracerProvider() { + const { isolatedTracerProvider } = getGlobalState(); + if (isolatedTracerProvider) return isolatedTracerProvider; + return trace.getTracerProvider(); +} +function getLangfuseTracer() { + return getLangfuseTracerProvider().getTracer(LANGFUSE_TRACER_NAME, LANGFUSE_SDK_VERSION); +} +var LangfuseBaseObservation = class { + constructor(params) { + var _a; + this.otelSpan = params.otelSpan; + this.id = params.otelSpan.spanContext().spanId; + this.traceId = params.otelSpan.spanContext().traceId; + this.type = params.type; + this.otelSpan.setAttributes(createObservationAttributes(params.type, (_a = params.attributes) != null ? _a : {})); + } + /** Gets the Langfuse OpenTelemetry tracer instance */ + get tracer() { + return getLangfuseTracer(); + } + /** + * Ends the observation, marking it as complete. + * + * @param endTime - Optional end time, defaults to current time + */ + end(endTime) { + this.otelSpan.end(endTime); + } + updateOtelSpanAttributes(attributes) { + this.otelSpan.setAttributes(createObservationAttributes(this.type, attributes)); + } + /** + * Set trace-level input and output for the trace this observation belongs to. + * + * @deprecated This is a legacy method for backward compatibility with Langfuse platform + * features that still rely on trace-level input/output (e.g., legacy LLM-as-a-judge + * evaluators). It will be removed in a future major version. + * + * For setting other trace attributes (userId, sessionId, metadata, tags, version), + * use {@link propagateAttributes} instead. + * + * @param attributes - Input and output data to associate with the trace + * @returns The observation instance for method chaining + * + * @example + * ```typescript + * const span = startObservation('my-operation'); + * span.setTraceIO({ + * input: { query: 'user question' }, + * output: { response: 'assistant answer' } + * }); + * ``` + */ + setTraceIO(attributes) { + this.otelSpan.setAttributes(createTraceAttributes(attributes)); + return this; + } + /** + * Make the trace this observation belongs to publicly accessible via its URL. + * + * When a trace is published, anyone with the trace link can view the full trace + * without needing to be logged in to Langfuse. This action cannot be undone + * programmatically - once any span in a trace is published, the entire trace + * becomes public. + * + * @returns The observation instance for method chaining + * + * @example + * ```typescript + * const span = startObservation('my-operation'); + * span.setTraceAsPublic(); + * ``` + */ + setTraceAsPublic() { + this.otelSpan.setAttributes({ [LangfuseOtelSpanAttributes.TRACE_PUBLIC]: true }); + return this; + } + startObservation(name, attributes, options) { + const { asType = "span" } = options || {}; + return startObservation(name, attributes, { + asType, + parentSpanContext: this.otelSpan.spanContext() + }); + } +}; +var LangfuseSpan = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "span" + }); + } + /** + * Updates this span with new attributes. + * + * @param attributes - Span attributes to set + * @returns This span for method chaining + * + * @example + * ```typescript + * span.update({ + * output: { result: 'success' }, + * level: 'DEFAULT', + * metadata: { duration: 150 } + * }); + * ``` + */ + update(attributes) { + super.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseAgent = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "agent" + }); + } + /** + * Updates this agent observation with new attributes. + * + * @param attributes - Agent attributes to set + * @returns This agent for method chaining + * + * @example + * ```typescript + * agent.update({ + * output: { + * taskCompleted: true, + * iterationsUsed: 5, + * toolsInvoked: ['web-search', 'calculator', 'summarizer'], + * finalResult: 'Research completed with high confidence' + * }, + * metadata: { + * efficiency: 0.85, + * qualityScore: 0.92, + * resourcesConsumed: { tokens: 15000, apiCalls: 12 } + * } + * }); + * ``` + */ + update(attributes) { + super.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseTool = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "tool" + }); + } + /** + * Updates this tool observation with new attributes. + * + * @param attributes - Tool attributes to set + * @returns This tool for method chaining + * + * @example + * ```typescript + * tool.update({ + * output: { + * result: searchResults, + * count: searchResults.length, + * relevanceScore: 0.89, + * executionTime: 1250 + * }, + * metadata: { + * cacheHit: false, + * apiCost: 0.025, + * rateLimitRemaining: 950 + * } + * }); + * ``` + */ + update(attributes) { + super.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseChain = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "chain" + }); + } + /** + * Updates this chain observation with new attributes. + * + * @param attributes - Chain attributes to set + * @returns This chain for method chaining + * + * @example + * ```typescript + * chain.update({ + * output: { + * stepsCompleted: 5, + * stepsSuccessful: 4, + * finalResult: processedData, + * pipelineEfficiency: 0.87 + * }, + * metadata: { + * bottleneckStep: 'data-validation', + * parallelizationOpportunities: ['step-2', 'step-3'], + * optimizationSuggestions: ['cache-intermediate-results'] + * } + * }); + * ``` + */ + update(attributes) { + super.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseRetriever = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "retriever" + }); + } + /** + * Updates this retriever observation with new attributes. + * + * @param attributes - Retriever attributes to set + * @returns This retriever for method chaining + */ + update(attributes) { + super.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseEvaluator = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "evaluator" + }); + } + /** + * Updates this evaluator observation with new attributes. + * + * @param attributes - Evaluator attributes to set + * @returns This evaluator for method chaining + */ + update(attributes) { + super.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseGuardrail = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "guardrail" + }); + } + /** + * Updates this guardrail observation with new attributes. + * + * @param attributes - Guardrail attributes to set + * @returns This guardrail for method chaining + */ + update(attributes) { + super.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseGeneration = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "generation" + }); + } + update(attributes) { + this.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseEmbedding = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "embedding" + }); + } + /** + * Updates this embedding observation with new attributes. + * + * @param attributes - Embedding attributes to set + * @returns This embedding for method chaining + */ + update(attributes) { + this.updateOtelSpanAttributes(attributes); + return this; + } +}; +var LangfuseEvent = class extends LangfuseBaseObservation { + constructor(params) { + super({ + ...params, + type: "event" + }); + this.otelSpan.end(params.timestamp); + } +}; +function createOtelSpan(params) { + return getLangfuseTracer().startSpan(params.name, { startTime: params.startTime }, createParentContext(params.parentSpanContext)); +} +function createParentContext(parentSpanContext) { + if (!parentSpanContext) return; + return trace.setSpanContext(context.active(), parentSpanContext); +} +function startObservation(name, attributes, options) { + var _a; + const { asType = "span", ...observationOptions } = options || {}; + const otelSpan = createOtelSpan({ + name, + ...observationOptions + }); + switch (asType) { + case "generation": return new LangfuseGeneration({ + otelSpan, + attributes + }); + case "embedding": return new LangfuseEmbedding({ + otelSpan, + attributes + }); + case "agent": return new LangfuseAgent({ + otelSpan, + attributes + }); + case "tool": return new LangfuseTool({ + otelSpan, + attributes + }); + case "chain": return new LangfuseChain({ + otelSpan, + attributes + }); + case "retriever": return new LangfuseRetriever({ + otelSpan, + attributes + }); + case "evaluator": return new LangfuseEvaluator({ + otelSpan, + attributes + }); + case "guardrail": return new LangfuseGuardrail({ + otelSpan, + attributes + }); + case "event": return new LangfuseEvent({ + otelSpan, + attributes, + timestamp: (_a = observationOptions == null ? void 0 : observationOptions.startTime) != null ? _a : /* @__PURE__ */ new Date() + }); + default: return new LangfuseSpan({ + otelSpan, + attributes + }); + } +} +async function createTraceId(seed) { + if (seed) { + const data = new TextEncoder().encode(seed); + const hashBuffer = await crypto.subtle.digest("SHA-256", data); + return uint8ArrayToHex(new Uint8Array(hashBuffer)).slice(0, 32); + } + return uint8ArrayToHex(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))); +} +function uint8ArrayToHex(array) { + return Array.from(array).map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+context-async-hooks@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/context-async-hooks/build/src/AbstractAsyncHooksContextManager.js +var require_AbstractAsyncHooksContextManager = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AbstractAsyncHooksContextManager = void 0; + const events_1 = __require("events"); + const ADD_LISTENER_METHODS = [ + "addListener", + "on", + "once", + "prependListener", + "prependOnceListener" + ]; + var AbstractAsyncHooksContextManager = class { + /** + * Binds a the certain context or the active one to the target function and then returns the target + * @param context A context (span) to be bind to target + * @param target a function or event emitter. When target or one of its callbacks is called, + * the provided context will be used as the active context for the duration of the call. + */ + bind(context, target) { + if (target instanceof events_1.EventEmitter) return this._bindEventEmitter(context, target); + if (typeof target === "function") return this._bindFunction(context, target); + return target; + } + _bindFunction(context, target) { + const manager = this; + const contextWrapper = function(...args) { + return manager.with(context, () => target.apply(this, args)); + }; + Object.defineProperty(contextWrapper, "length", { + enumerable: false, + configurable: true, + writable: false, + value: target.length + }); + /** + * It isn't possible to tell Typescript that contextWrapper is the same as T + * so we forced to cast as any here. + */ + return contextWrapper; + } + /** + * By default, EventEmitter call their callback with their context, which we do + * not want, instead we will bind a specific context to all callbacks that + * go through it. + * @param context the context we want to bind + * @param ee EventEmitter an instance of EventEmitter to patch + */ + _bindEventEmitter(context, ee) { + if (this._getPatchMap(ee) !== void 0) return ee; + this._createPatchMap(ee); + ADD_LISTENER_METHODS.forEach((methodName) => { + if (ee[methodName] === void 0) return; + ee[methodName] = this._patchAddListener(ee, ee[methodName], context); + }); + if (typeof ee.removeListener === "function") ee.removeListener = this._patchRemoveListener(ee, ee.removeListener); + if (typeof ee.off === "function") ee.off = this._patchRemoveListener(ee, ee.off); + if (typeof ee.removeAllListeners === "function") ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners); + return ee; + } + /** + * Patch methods that remove a given listener so that we match the "patched" + * version of that listener (the one that propagate context). + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveListener(ee, original) { + const contextManager = this; + return function(event, listener) { + const events = contextManager._getPatchMap(ee)?.[event]; + if (events === void 0) return original.call(this, event, listener); + const patchedListener = events.get(listener); + return original.call(this, event, patchedListener || listener); + }; + } + /** + * Patch methods that remove all listeners so we remove our + * internal references for a given event. + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveAllListeners(ee, original) { + const contextManager = this; + return function(event) { + const map = contextManager._getPatchMap(ee); + if (map !== void 0) { + if (arguments.length === 0) contextManager._createPatchMap(ee); + else if (map[event] !== void 0) delete map[event]; + } + return original.apply(this, arguments); + }; + } + /** + * Patch methods on an event emitter instance that can add listeners so we + * can force them to propagate a given context. + * @param ee EventEmitter instance + * @param original reference to the patched method + * @param [context] context to propagate when calling listeners + */ + _patchAddListener(ee, original, context) { + const contextManager = this; + return function(event, listener) { + /** + * This check is required to prevent double-wrapping the listener. + * The implementation for ee.once wraps the listener and calls ee.on. + * Without this check, we would wrap that wrapped listener. + * This causes an issue because ee.removeListener depends on the onceWrapper + * to properly remove the listener. If we wrap their wrapper, we break + * that detection. + */ + if (contextManager._wrapped) return original.call(this, event, listener); + let map = contextManager._getPatchMap(ee); + if (map === void 0) map = contextManager._createPatchMap(ee); + let listeners = map[event]; + if (listeners === void 0) { + listeners = /* @__PURE__ */ new WeakMap(); + map[event] = listeners; + } + const patchedListener = contextManager.bind(context, listener); + listeners.set(listener, patchedListener); + /** + * See comment at the start of this function for the explanation of this property. + */ + contextManager._wrapped = true; + try { + return original.call(this, event, patchedListener); + } finally { + contextManager._wrapped = false; + } + }; + } + _createPatchMap(ee) { + const map = Object.create(null); + ee[this._kOtListeners] = map; + return map; + } + _getPatchMap(ee) { + return ee[this._kOtListeners]; + } + _kOtListeners = Symbol("OtListeners"); + _wrapped = false; + }; + exports.AbstractAsyncHooksContextManager = AbstractAsyncHooksContextManager; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+context-async-hooks@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/context-async-hooks/build/src/AsyncHooksContextManager.js +var require_AsyncHooksContextManager = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncHooksContextManager = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const asyncHooks = __require("async_hooks"); + const AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager(); + /** + * @deprecated Use AsyncLocalStorageContextManager instead. + */ + var AsyncHooksContextManager = class extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager { + _asyncHook; + _contexts = /* @__PURE__ */ new Map(); + _stack = []; + constructor() { + super(); + this._asyncHook = asyncHooks.createHook({ + init: this._init.bind(this), + before: this._before.bind(this), + after: this._after.bind(this), + destroy: this._destroy.bind(this), + promiseResolve: this._destroy.bind(this) + }); + } + active() { + return this._stack[this._stack.length - 1] ?? api_1.ROOT_CONTEXT; + } + with(context, fn, thisArg, ...args) { + this._enterContext(context); + try { + return fn.call(thisArg, ...args); + } finally { + this._exitContext(); + } + } + enable() { + this._asyncHook.enable(); + return this; + } + disable() { + this._asyncHook.disable(); + this._contexts.clear(); + this._stack = []; + return this; + } + /** + * Init hook will be called when userland create a async context, setting the + * context as the current one if it exist. + * @param uid id of the async context + * @param type the resource type + */ + _init(uid, type) { + if (type === "TIMERWRAP") return; + const context = this._stack[this._stack.length - 1]; + if (context !== void 0) this._contexts.set(uid, context); + } + /** + * Destroy hook will be called when a given context is no longer used so we can + * remove its attached context. + * @param uid uid of the async context + */ + _destroy(uid) { + this._contexts.delete(uid); + } + /** + * Before hook is called just before executing a async context. + * @param uid uid of the async context + */ + _before(uid) { + const context = this._contexts.get(uid); + if (context !== void 0) this._enterContext(context); + } + /** + * After hook is called just after completing the execution of a async context. + */ + _after() { + this._exitContext(); + } + /** + * Set the given context as active + */ + _enterContext(context) { + this._stack.push(context); + } + /** + * Remove the context at the root of the stack + */ + _exitContext() { + this._stack.pop(); + } + }; + exports.AsyncHooksContextManager = AsyncHooksContextManager; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+context-async-hooks@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/context-async-hooks/build/src/AsyncLocalStorageContextManager.js +var require_AsyncLocalStorageContextManager = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncLocalStorageContextManager = void 0; + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const async_hooks_1 = __require("async_hooks"); + const AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager(); + /** + * Wrapper around a token and _asyncLocalStorage to mirror the behavior of + * a Node.js RunScope + * + * @internal not intended for direct public consumption. Will be removed once + * withScope is available on all supported Node.js versions + */ + var DisposeOnceToken = class { + _isDisposed = false; + _previousContext; + _asyncLocalStorage; + constructor(previousContext, asyncLocalStorage) { + this._previousContext = previousContext; + this._asyncLocalStorage = asyncLocalStorage; + } + dispose() { + if (this._isDisposed) return; + this._asyncLocalStorage.enterWith(this._previousContext); + this._isDisposed = true; + } + }; + var AsyncLocalStorageContextManager = class extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager { + _asyncLocalStorage; + constructor() { + super(); + this._asyncLocalStorage = new async_hooks_1.AsyncLocalStorage(); + } + active() { + return this._asyncLocalStorage.getStore() ?? api_1.ROOT_CONTEXT; + } + with(context, fn, thisArg, ...args) { + const cb = thisArg == null ? fn : fn.bind(thisArg); + return this._asyncLocalStorage.run(context, cb, ...args); + } + enable() { + return this; + } + disable() { + this._asyncLocalStorage.disable(); + return this; + } + /** + * Imperatively sets `context` as active for the current async execution chain + * and operations spawned from it. Returns a {@link ContextManagementToken} whose `dispose()` + * restores the previous context (see {@link ContextManager.attach}). + * + * On Node.js 25.9+, delegates to `AsyncLocalStorage.withScope()` which returns + * a native `RunScope`. On older Node.js versions, falls back to `enterWith()` with + * a manual token. + * + * **Caveat for async functions:** Both `withScope()` and `enterWith()` affect the + * entire current async execution chain. If `attach()` is called inside an async + * function before the first `await`, the context change will leak into the caller's + * context and remain active there until something else restores it. Prefer `with()` + * for async code. + * + * @experimental This API is experimental and may change in minor releases without prior notice. + */ + attach(context) { + const withScope = this._asyncLocalStorage.withScope; + if (withScope) return withScope.call(this._asyncLocalStorage, context); + const previousContext = this.active(); + this._asyncLocalStorage.enterWith(context); + return new DisposeOnceToken(previousContext, this._asyncLocalStorage); + } + }; + exports.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+context-async-hooks@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/context-async-hooks/build/src/index.js +var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncLocalStorageContextManager = exports.AsyncHooksContextManager = void 0; + var AsyncHooksContextManager_1 = require_AsyncHooksContextManager(); + Object.defineProperty(exports, "AsyncHooksContextManager", { + enumerable: true, + get: function() { + return AsyncHooksContextManager_1.AsyncHooksContextManager; + } + }); + var AsyncLocalStorageContextManager_1 = require_AsyncLocalStorageContextManager(); + Object.defineProperty(exports, "AsyncLocalStorageContextManager", { + enumerable: true, + get: function() { + return AsyncLocalStorageContextManager_1.AsyncLocalStorageContextManager; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-node@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-node/build/src/NodeTracerProvider.js +var require_NodeTracerProvider = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NodeTracerProvider = void 0; + const context_async_hooks_1 = require_src$1(); + const sdk_trace_base_1 = require_index_shim(); + const api_1 = (init_esm$2(), __toCommonJS(esm_exports$2)); + const core_1 = require_src$8(); + function setupContextManager(contextManager) { + if (contextManager === null) return; + if (contextManager === void 0) { + const defaultContextManager = new context_async_hooks_1.AsyncLocalStorageContextManager(); + defaultContextManager.enable(); + api_1.context.setGlobalContextManager(defaultContextManager); + return; + } + contextManager.enable(); + api_1.context.setGlobalContextManager(contextManager); + } + function setupPropagator(propagator) { + if (propagator === null) return; + if (propagator === void 0) { + api_1.propagation.setGlobalPropagator(new core_1.CompositePropagator({ propagators: [new core_1.W3CTraceContextPropagator(), new core_1.W3CBaggagePropagator()] })); + return; + } + api_1.propagation.setGlobalPropagator(propagator); + } + /** + * Register this TracerProvider for use with the OpenTelemetry API. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ + var NodeTracerProvider = class extends sdk_trace_base_1.BasicTracerProvider { + constructor(config = {}) { + super(config); + } + /** + * Register this TracerProvider for use with the OpenTelemetry API. + * Undefined values may be replaced with defaults, and + * null values will be skipped. + * + * @param config Configuration object for SDK registration + */ + register(config = {}) { + api_1.trace.setGlobalTracerProvider(this); + setupContextManager(config.contextManager); + setupPropagator(config.propagator); + } + }; + exports.NodeTracerProvider = NodeTracerProvider; +})); + +//#endregion +//#region ../../node_modules/.pnpm/@opentelemetry+sdk-trace-node@2.11.0_@opentelemetry+api@1.9.1/node_modules/@opentelemetry/sdk-trace-node/build/src/index.js +var require_src = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceIdRatioBasedSampler = exports.SimpleSpanProcessor = exports.SamplingDecision = exports.RandomIdGenerator = exports.ParentBasedSampler = exports.NoopSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.BatchSpanProcessor = exports.BasicTracerProvider = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NodeTracerProvider = void 0; + var NodeTracerProvider_1 = require_NodeTracerProvider(); + Object.defineProperty(exports, "NodeTracerProvider", { + enumerable: true, + get: function() { + return NodeTracerProvider_1.NodeTracerProvider; + } + }); + var sdk_trace_base_1 = require_index_shim(); + Object.defineProperty(exports, "AlwaysOffSampler", { + enumerable: true, + get: function() { + return sdk_trace_base_1.AlwaysOffSampler; + } + }); + Object.defineProperty(exports, "AlwaysOnSampler", { + enumerable: true, + get: function() { + return sdk_trace_base_1.AlwaysOnSampler; + } + }); + Object.defineProperty(exports, "BasicTracerProvider", { + enumerable: true, + get: function() { + return sdk_trace_base_1.BasicTracerProvider; + } + }); + Object.defineProperty(exports, "BatchSpanProcessor", { + enumerable: true, + get: function() { + return sdk_trace_base_1.BatchSpanProcessor; + } + }); + Object.defineProperty(exports, "ConsoleSpanExporter", { + enumerable: true, + get: function() { + return sdk_trace_base_1.ConsoleSpanExporter; + } + }); + Object.defineProperty(exports, "InMemorySpanExporter", { + enumerable: true, + get: function() { + return sdk_trace_base_1.InMemorySpanExporter; + } + }); + Object.defineProperty(exports, "NoopSpanProcessor", { + enumerable: true, + get: function() { + return sdk_trace_base_1.NoopSpanProcessor; + } + }); + Object.defineProperty(exports, "ParentBasedSampler", { + enumerable: true, + get: function() { + return sdk_trace_base_1.ParentBasedSampler; + } + }); + Object.defineProperty(exports, "RandomIdGenerator", { + enumerable: true, + get: function() { + return sdk_trace_base_1.RandomIdGenerator; + } + }); + Object.defineProperty(exports, "SamplingDecision", { + enumerable: true, + get: function() { + return sdk_trace_base_1.SamplingDecision; + } + }); + Object.defineProperty(exports, "SimpleSpanProcessor", { + enumerable: true, + get: function() { + return sdk_trace_base_1.SimpleSpanProcessor; + } + }); + Object.defineProperty(exports, "TraceIdRatioBasedSampler", { + enumerable: true, + get: function() { + return sdk_trace_base_1.TraceIdRatioBasedSampler; + } + }); +})); + +//#endregion +//#region src/instrumentation.ts +var import_src = require_src$4(); +var import_src$1 = require_src$6(); +var import_src$2 = require_src(); +const TRACE_ID_HEX_CHARS = 32; +const SPAN_ID_HEX_CHARS = 16; +const LEGACY_UPLOADED = "langfuse.observation.metadata.codex.legacy_uploaded"; +let idSeed; +let idCounter = 0; +function seedIds(seed) { + idSeed = seed; + idCounter = 0; +} +function currentIdSeed() { + return idSeed; +} +function seededId(kind) { + const hexChars = kind === "trace" ? TRACE_ID_HEX_CHARS : SPAN_ID_HEX_CHARS; + if (idSeed === void 0) return randomBytes(hexChars / 2).toString("hex"); + return createHash("sha256").update(`${idSeed}:${kind}:${idCounter++}`).digest("hex").slice(0, hexChars); +} +let activeFlush; +let activeBackpressure; +/** Await at conversion boundaries to keep preparation and delivery bounded. */ +async function flushInstrumentation() { + await activeFlush?.(); +} +/** Wait for preparation, draining only full batches or an existing request. */ +async function backpressureInstrumentation() { + await activeBackpressure?.(); +} +function spanKey(span) { + const { traceId, spanId } = span.spanContext(); + return `${traceId}:${spanId}`; +} +function serialize(spans) { + const encoded = import_src.JsonTraceSerializer.serializeRequest(spans); + if (!encoded) throw new Error("OTLP serialization failed"); + return encoded; +} +/** +* The SDK prepares spans (including masking and media) using its public +* immediate exporter option. This exporter owns batching and acknowledgments: +* a queue admission is never mistaken for successful delivery at shutdown. +*/ +var BoundedSpanExporter = class { + config; + queue = []; + delivered; + received = /* @__PURE__ */ new Set(); + maxBatchBytes; + maxSingleSpanBytes; + maxQueueSpans; + maxQueueBytes; + flushIntervalMillis; + queuedBytes = 0; + inFlightCount = 0; + timer; + draining; + failure; + closed = false; + capacityFlush = false; + constructor(config, options = {}) { + this.config = config; + this.delivered = { ...options.acknowledged }; + this.maxBatchBytes = options.maxBatchBytes ?? 8388608; + this.maxSingleSpanBytes = options.maxSingleSpanBytes ?? 268435456; + this.maxQueueSpans = options.maxQueueSpans ?? 2048; + this.maxQueueBytes = options.maxQueueBytes ?? 67108864; + this.flushIntervalMillis = options.flushIntervalMillis ?? 1e3; + } + acknowledged() { + return { ...this.delivered }; + } + receivedSpan(key) { + return this.received.has(key); + } + export(spans, callback) { + try { + if (this.closed) throw new Error("OTLP exporter is shut down"); + if (this.failure) throw this.failure; + for (const span of spans) { + const key = spanKey(span); + this.received.add(key); + const body = serialize([span]); + const contents = JSON.parse(Buffer.from(body).toString("utf8")).resourceSpans.flatMap((resource) => resource.scopeSpans); + const fingerprint = createHash("sha256").update(JSON.stringify(contents)).digest("hex"); + if (this.delivered[key] === fingerprint) continue; + if (body.byteLength > this.maxSingleSpanBytes) throw new Error(`OTLP observation exceeds ${this.maxSingleSpanBytes} byte limit`); + const empty = this.queue.length === 0 && this.inFlightCount === 0; + if (this.queue.length + this.inFlightCount >= this.maxQueueSpans || !empty && this.queuedBytes + body.byteLength > this.maxQueueBytes) throw new Error("OTLP delivery queue capacity exceeded; observations remain retryable"); + this.queue.push({ + span, + key, + fingerprint, + bytes: body.byteLength + }); + this.queuedBytes += body.byteLength; + } + if (this.queue.length >= 16 || this.queuedBytes >= this.maxBatchBytes) this.drain(); + else if (this.queue.length > 0 && !this.timer && !this.draining) { + this.timer = setTimeout(() => { + this.timer = void 0; + this.drain(); + }, this.flushIntervalMillis); + this.timer.unref(); + } + callback({ code: import_src$3.ExportResultCode.SUCCESS }); + } catch (error) { + this.fail(error); + callback({ + code: import_src$3.ExportResultCode.FAILED, + error: this.failure + }); + } + } + fail(error) { + this.failure ??= error instanceof Error ? error : new Error(String(error)); + } + drain() { + if (this.timer) { + clearTimeout(this.timer); + this.timer = void 0; + } + if (!this.draining) this.draining = this.sendQueued().catch((error) => this.fail(error)).finally(() => { + this.draining = void 0; + }); + return this.draining; + } + async sendQueued() { + while (this.queue.length > 0 && !this.failure) { + const batch = [this.queue[0]]; + let body = serialize(batch.map((entry) => entry.span)); + while (batch.length < 16 && batch.length < this.queue.length) { + const encoded = serialize([...batch, this.queue[batch.length]].map((entry) => entry.span)); + if (encoded.byteLength > this.maxBatchBytes) break; + batch.push(this.queue[batch.length]); + body = encoded; + } + this.queue.splice(0, batch.length); + this.inFlightCount = batch.length; + try { + await this.send(body); + for (const entry of batch) this.delivered[entry.key] = entry.fingerprint; + } finally { + this.queuedBytes -= batch.reduce((total, entry) => total + entry.bytes, 0); + this.inFlightCount = 0; + } + } + } + async send(body) { + for (let attempt = 0; attempt < 2; attempt++) { + const response = await fetch(`${this.config.base_url.replace(/\/$/, "")}/api/public/otel/v1/traces`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Basic ${Buffer.from(`${this.config.public_key}:${this.config.secret_key}`).toString("base64")}`, + "x-langfuse-public-key": this.config.public_key ?? "", + "x-langfuse-sdk-name": "codex-observability-plugin" + }, + body: Buffer.from(body), + signal: AbortSignal.timeout(5e3) + }); + const text = await response.text(); + if (!response.ok) { + if (attempt === 0 && (response.status === 429 || response.status >= 500)) { + await new Promise((resolve) => setTimeout(resolve, 100)); + continue; + } + throw new Error(`OTLP export rejected with HTTP ${response.status}`); + } + const result = text.length === 0 ? {} : JSON.parse(text); + if (result === null || typeof result !== "object" || Array.isArray(result)) throw new Error("Invalid OTLP export acknowledgment"); + const partial = result.partialSuccess; + if (partial?.rejectedSpans !== void 0 && BigInt(partial.rejectedSpans) !== 0n) throw new Error(`OTLP partial success rejected ${partial.rejectedSpans} observation(s)`); + return; + } + } + async forceFlush() { + if (this.failure) throw this.failure; + if (this.capacityFlush && !this.draining && this.queuedBytes < this.maxBatchBytes && this.queue.length < 16) return; + await this.drain(); + if (this.failure) throw this.failure; + } + /** SDK forceFlush waits for preparation; avoid sending tiny batches each time. */ + async withBackpressure(prepare) { + this.capacityFlush = true; + try { + await prepare(); + } finally { + this.capacityFlush = false; + } + } + async shutdown() { + this.closed = true; + await this.forceFlush(); + } +}; +const DEFAULT_SERVICE_NAME = "codex"; +function buildResource() { + return (0, import_src$1.defaultResource)().merge((0, import_src$1.resourceFromAttributes)({ "service.name": DEFAULT_SERVICE_NAME })).merge((0, import_src$1.detectResources)({ detectors: [import_src$1.envDetector] })); +} +/** +* Configure an isolated OpenTelemetry tracer provider wired to Langfuse. +* +* We register a dedicated `NodeTracerProvider` (rather than the full auto- +* instrumenting `NodeSDK`) so the bundle stays small and free of dynamic +* instrumentation loading. Registering the provider also installs the +* AsyncLocalStorage context manager that `propagateAttributes` relies on. +* +* The SDK prepares observations in immediate mode; our acknowledged exporter +* batches the resulting spans by count, exact encoded size, and a short timer. +* Shutdown must succeed before callers persist observation checkpoints. +*/ +function setupInstrumentation(config, options = {}) { + const exporter = new BoundedSpanExporter(config, options); + const ended = /* @__PURE__ */ new Set(); + const spanProcessor = new LangfuseSpanProcessor({ + publicKey: config.public_key, + secretKey: config.secret_key, + baseUrl: config.base_url, + environment: config.environment, + exportMode: "immediate", + exporter, + shouldExportSpan: ({ otelSpan }) => otelSpan.attributes[LEGACY_UPLOADED] !== "true" + }); + const checkedProcessor = { + onStart: (span, context) => spanProcessor.onStart(span, context), + onEnd: (span) => { + if (span.attributes[LEGACY_UPLOADED] !== "true") ended.add(spanKey(span)); + spanProcessor.onEnd(span); + }, + forceFlush: async () => { + await spanProcessor.forceFlush(); + await exporter.forceFlush(); + for (const key of ended) if (!exporter.receivedSpan(key)) throw new Error("Langfuse observation preparation failed before export"); + }, + shutdown: () => spanProcessor.shutdown() + }; + const provider = new import_src$2.NodeTracerProvider({ + resource: buildResource(), + spanProcessors: [checkedProcessor], + idGenerator: { + generateTraceId: () => seededId("trace"), + generateSpanId: () => seededId("span") + } + }); + provider.register(); + setLangfuseTracerProvider(provider); + activeFlush = () => checkedProcessor.forceFlush(); + activeBackpressure = () => exporter.withBackpressure(() => checkedProcessor.forceFlush()); + return { + acknowledged: () => exporter.acknowledged(), + flush: () => checkedProcessor.forceFlush(), + shutdown: async () => { + try { + await checkedProcessor.forceFlush(); + } finally { + try { + await provider.shutdown(); + } finally { + setLangfuseTracerProvider(null); + activeFlush = void 0; + activeBackpressure = void 0; + } + } + } + }; +} + +//#endregion +//#region src/utils.ts +/** Read and JSON-parse the hook payload Codex writes to stdin. */ +function readStdin() { + return new Promise((resolve, reject) => { + let buffer = ""; + process.stdin.setEncoding("utf-8"); + process.stdin.on("data", (chunk) => buffer += chunk); + process.stdin.on("end", () => { + const trimmed = buffer.trim(); + if (!trimmed) { + reject(/* @__PURE__ */ new Error("empty hook stdin")); + return; + } + try { + resolve(JSON.parse(trimmed)); + } catch (error) { + reject(/* @__PURE__ */ new Error(`failed to parse hook stdin: ${error instanceof Error ? error.message : String(error)}`)); + } + }); + process.stdin.once("error", reject); + }); +} +function isPrimitive(value) { + const t = typeof value; + return t === "string" || t === "number" || t === "boolean"; +} +/** Stringify a value for display, leaving strings untouched. */ +function toText(value) { + if (value == null) return ""; + if (typeof value === "string") return value; + if (isPrimitive(value)) return String(value); + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} +let debugEnabled = false; +function setDebug(enabled) { + debugEnabled = enabled; +} +function debugLog(...args) { + if (!debugEnabled) return; + console.error("[langfuse-codex]", ...args); +} + +//#endregion +//#region src/parent-context.ts +init_esm$2(); +const EXTERNAL_TRACEPARENT_ENV_VAR = "LANGFUSE_CODEX_TRACEPARENT"; +const EXTERNAL_PARENT_TRACE_ID_ENV_VAR = "LANGFUSE_CODEX_PARENT_TRACE_ID"; +const EXTERNAL_PARENT_SPAN_ID_ENV_VAR = "LANGFUSE_CODEX_PARENT_SPAN_ID"; +const TRACEPARENT = /^00-(?!0{32})([0-9a-f]{32})-(?!0{16})([0-9a-f]{16})-[0-9a-f]{2}$/; +function parseTraceparent(value) { + const match = TRACEPARENT.exec(value.trim().toLowerCase()); + if (!match) return void 0; + return { + traceId: match[1], + spanId: match[2], + traceFlags: TraceFlags.SAMPLED, + isRemote: true + }; +} +function readEnv(env, name) { + const value = env[name]?.trim(); + return value ? value : void 0; +} +function reject(message, failOnError) { + debugLog(`${message}; falling back to trace_seed or an auto-generated trace`); + if (failOnError) throw new Error(message); +} +function readExternalParentSpanContext(env, failOnError) { + const traceparent = readEnv(env, EXTERNAL_TRACEPARENT_ENV_VAR); + if (traceparent !== void 0) return parseTraceparent(traceparent) ?? reject(`${"LANGFUSE_CODEX_TRACEPARENT"} must be a valid W3C traceparent value`, failOnError); + const traceId = readEnv(env, EXTERNAL_PARENT_TRACE_ID_ENV_VAR); + const spanId = readEnv(env, EXTERNAL_PARENT_SPAN_ID_ENV_VAR); + if (traceId === void 0 && spanId === void 0) return void 0; + return parseTraceparent(`00-${traceId}-${spanId}-01`) ?? reject(`${"LANGFUSE_CODEX_PARENT_TRACE_ID"} and ${"LANGFUSE_CODEX_PARENT_SPAN_ID"} must both be set to valid non-zero hex ids (32 and 16 characters)`, failOnError); +} + +//#endregion +//#region src/sidecar.ts +/** +* The `Stop` hook reads the rollout file again after each Codex turn. +* The sidecar file (`.langfuse`) holds the ids of the sent turns. +* The hook adds an id only after a flush. Retry a turn that has no id. +*/ +async function loadUploadedTurnIds(rolloutFile) { + try { + const data = await fs$1.readFile(`${rolloutFile}.langfuse`, "utf-8"); + return new Set(data.split("\n").filter(Boolean)); + } catch (error) { + if (error.code === "ENOENT") return /* @__PURE__ */ new Set(); + throw error; + } +} +async function markTurnUploaded(rolloutFile, turnId) { + try { + await fs$1.appendFile(`${rolloutFile}.langfuse`, `${turnId}\n`, "utf-8"); + } catch {} +} +/** A separate file keeps old newline turn checkpoints readable during upgrades. */ +async function loadObservationCheckpoint(rolloutFile) { + try { + const state = JSON.parse(await fs$1.readFile(`${rolloutFile}.langfuse-observations`, "utf8")); + if (state.version !== 1 || typeof state.observations !== "object" || state.observations === null) throw new Error("Invalid observation checkpoint"); + return state.observations; + } catch (error) { + if (error.code === "ENOENT") return {}; + throw error; + } +} +async function saveObservationCheckpoint(rolloutFile, observations, hooks = [], turns = {}) { + const temporary = `${rolloutFile}.langfuse-observations.${randomUUID()}`; + await fs$1.writeFile(temporary, JSON.stringify({ + version: 1, + observations, + hooks, + turns, + legacyTurnIds: [...await loadLegacyTurnIds(rolloutFile)] + }), { mode: 384 }); + await fs$1.rename(temporary, `${rolloutFile}.langfuse-observations`); +} +/** Durable inbox: a busy hook exits promptly; its owner drains this on its next pass. */ +async function enqueueHook(rolloutFile, input, persisted) { + const dir = `${rolloutFile}.langfuse-pending`; + await fs$1.mkdir(dir, { + recursive: true, + mode: 448 + }); + const event = persisted ?? { + id: randomUUID(), + timestamp: Date.now(), + input + }; + const temporary = path$1.join(dir, `${event.id}.tmp`); + await fs$1.writeFile(temporary, JSON.stringify(event), { mode: 384 }); + await fs$1.rename(temporary, path$1.join(dir, `${event.id}.json`)); +} +async function pendingHooks(rolloutFile) { + const dir = `${rolloutFile}.langfuse-pending`; + try { + const names = (await fs$1.readdir(dir)).filter((name) => name.endsWith(".json")); + const events = []; + for (const name of names) events.push(JSON.parse(await fs$1.readFile(path$1.join(dir, name), "utf8"))); + return events.sort((a, b) => a.timestamp - b.timestamp || a.id.localeCompare(b.id)); + } catch (error) { + if (error.code === "ENOENT") return []; + throw error; + } +} +async function acknowledgeHooks(rolloutFile, events) { + for (const event of events) await fs$1.unlink(path$1.join(`${rolloutFile}.langfuse-pending`, `${event.id}.json`)); +} +/** Linux kernel lock: one bounded helper, released on EOF or parent death. */ +async function acquireRolloutLock(rolloutFile, waitSeconds = 0) { + const helper = spawn("flock", [ + "--timeout", + Math.max(0, Math.min(10, waitSeconds)).toFixed(3), + "--", + `${rolloutFile}.langfuse-lock`, + process.execPath, + "-e", + ` + const timer = setTimeout(() => {try {process.kill(${process.pid},"SIGTERM");} catch {} process.exit(1);},35000); + process.stdin.resume(); + process.stdin.once("end",()=>{clearTimeout(timer);process.exit(0);}); + process.stdout.write("locked\\n"); + ` + ], { + stdio: [ + "pipe", + "pipe", + "pipe" + ], + env: { + ...process.env, + LC_ALL: "C" + } + }); + let spawnError; + helper.once("error", (error) => { + spawnError = error; + }); + const closed = new Promise((resolve) => helper.once("close", () => resolve())); + if (!await new Promise((resolve) => { + const timeout = setTimeout(() => { + helper.kill("SIGTERM"); + resolve(false); + }, Math.max(0, Math.min(10, waitSeconds)) * 1e3 + 1500); + helper.stdout.once("data", () => { + clearTimeout(timeout); + resolve(true); + }); + helper.once("close", () => { + clearTimeout(timeout); + resolve(false); + }); + })) { + await closed; + if (spawnError) throw spawnError; + return; + } + return async () => { + helper.stdin.end(); + await closed; + }; +} +async function loadHookContext(rolloutFile) { + try { + return JSON.parse(await fs$1.readFile(`${rolloutFile}.langfuse-observations`, "utf8")).hooks ?? []; + } catch (error) { + if (error.code === "ENOENT") return []; + throw error; + } +} +async function loadLegacyTurnIds(rolloutFile) { + try { + const state = JSON.parse(await fs$1.readFile(`${rolloutFile}.langfuse-observations`, "utf8")); + return new Set(state.legacyTurnIds ?? []); + } catch (error) { + if (error.code === "ENOENT") return loadUploadedTurnIds(rolloutFile); + throw error; + } +} +async function loadTurnCheckpoint(rolloutFile) { + try { + return JSON.parse(await fs$1.readFile(`${rolloutFile}.langfuse-observations`, "utf8")).turns ?? {}; + } catch (error) { + if (error.code === "ENOENT") return {}; + throw error; + } +} + +//#endregion +//#region src/skills.ts +const SKILL_ACCESS_TOOLS = /* @__PURE__ */ new Set([ + "exec_command", + "exec", + "shell", + "local_shell", + "bash", + "js", + "read_mcp_resource" +]); +const SKILL_ACCESS_FIELDS = [ + "cmd", + "command", + "code", + "uri" +]; +const SKILL_DOC = /([A-Za-z0-9._@+-]+)\/SKILL\.md\b/g; +const SKILL_SCRIPT = /\bskills\/(?:\.[A-Za-z0-9._-]+\/)?([A-Za-z0-9._@+-]+)\/scripts\//g; +const SKILL_PROMPT_FRAGMENT = /\s*([^<\n]+)<\/name>/g; +const MAX_SKILL_NAME_LENGTH = 64; +function skillAccessText(tc) { + if (!SKILL_ACCESS_TOOLS.has(tc.name)) return void 0; + if (typeof tc.args === "string") return tc.args; + if (tc.args == null || typeof tc.args !== "object") return void 0; + const args = tc.args; + for (const field of SKILL_ACCESS_FIELDS) { + const value = args[field]; + if (typeof value === "string") return value; + if (Array.isArray(value)) return value.map((part) => toText(part)).join(" "); + } +} +function collect(text, patterns) { + const names = []; + for (const pattern of patterns) for (const match of text.matchAll(pattern)) { + const name = match[1].trim(); + if (name.length > 0 && name.length <= MAX_SKILL_NAME_LENGTH && !name.startsWith(".") && !names.includes(name)) names.push(name); + } + return names; +} +/** Skills a tool call picked up by reading a `SKILL.md` or running a skill script. */ +function skillsForToolCall(tc) { + const text = skillAccessText(tc); + return text ? collect(text, [SKILL_DOC, SKILL_SCRIPT]) : []; +} +/** Skills explicitly invoked with the prompt, from Codex's injected `` fragments. */ +function skillsForPrompt(text) { + return text.includes("") ? collect(text, [SKILL_PROMPT_FRAGMENT]) : []; +} +/** Configured tags plus one `skill:` per skill the turn used. */ +function traceTags(config, turn) { + const tags = [...config.tags ?? []]; + if (!config.skill_tags) return tags; + const names = [...turn.promptSkills]; + for (const step of turn.steps) for (const tc of step.toolCalls) for (const name of skillsForToolCall(tc)) if (!names.includes(name)) names.push(name); + for (const name of names) { + const tag = `skill:${name}`; + if (!tags.includes(tag)) tags.push(tag); + } + return tags; +} + +//#endregion +//#region src/parse.ts +function extractImageUris(content) { + if (!Array.isArray(content)) return []; + return content.map((part) => part && typeof part === "object" && typeof part.image_url === "string" ? part.image_url : "").filter(Boolean); +} +function extractMessageText(content) { + if (!Array.isArray(content)) return ""; + return content.map((part) => { + if (!part || typeof part !== "object") return ""; + if (part.type === "input_text" || part.type === "output_text" || part.type === "text") return typeof part.text === "string" ? part.text : ""; + return ""; + }).filter(Boolean).join("\n"); +} +function extractReasoning(item) { + if (typeof item.content === "string") return item.content; + if (Array.isArray(item.content)) return item.content.map((c) => c && typeof c === "object" && "text" in c ? toText(c.text) : toText(c)).filter(Boolean).join("\n"); + if (Array.isArray(item.summary) && item.summary.length > 0) return item.summary.map((s) => toText(s)).filter(Boolean).join("\n"); + return ""; +} +function parseArgs(raw) { + if (typeof raw !== "string") return raw; + try { + return JSON.parse(raw); + } catch { + return raw; + } +} +function extractToolError(payload) { + const explicit = payload.error ?? payload.codex_error_info; + if (explicit != null) return isPrimitive(explicit) ? String(explicit) : JSON.stringify(explicit); + const streams = [payload.stdout, payload.stderr].filter((s) => typeof s === "string" && s.length > 0).join("\n"); + if (typeof payload.aggregated_output === "string" && payload.aggregated_output) return payload.aggregated_output; + if (streams) return streams; + if (typeof payload.exit_code === "number") return `Exit code: ${payload.exit_code}`; +} +const TURN_OPENING_EVENTS = /* @__PURE__ */ new Set([ + "user_message", + "item_completed", + "agent_message" +]); +function newTurn(startTime) { + return { + turnId: void 0, + startTime, + endTime: startTime, + steps: [], + subagentThreadIds: [], + subagentSpawnCallIds: {}, + promptSkills: [], + userImages: [], + toolDefinitions: [], + completed: false, + aborted: false + }; +} +function sessionMetaFrom(line) { + const p = line.payload; + return { + sessionId: typeof p.id === "string" ? p.id : "unknown", + cliVersion: p.cli_version, + modelProvider: p.model_provider ?? void 0, + baseInstructions: p.base_instructions?.text, + isSubagentThread: typeof p.parent_thread_id === "string" || p.thread_source === "subagent", + parentThreadId: p.parent_thread_id ? p.parent_thread_id : void 0 + }; +} +function parseSession(lines) { + const ownHeader = lines.find((line) => line.type === "session_meta"); + const sessionMeta = ownHeader ? sessionMetaFrom(ownHeader) : { sessionId: "unknown" }; + const turns = []; + let turn = null; + let step = null; + let toolCallsById = /* @__PURE__ */ new Map(); + let lastTimestamp = Date.now(); + const developerMessages = []; + const injectedContext = []; + const toolDefinitions = []; + let exportedSegmentCount = 0; + const collect = (into, text) => { + if (!into.includes(text)) into.push(text); + }; + const systemPromptFor = () => { + const base = sessionMeta.baseInstructions; + const segmentCount = (base ? 1 : 0) + developerMessages.length + injectedContext.length; + if (segmentCount === 0) return void 0; + const snapshot = { + baseInstructions: base, + developerMessages: [...developerMessages], + injectedContext: [...injectedContext], + changed: segmentCount !== exportedSegmentCount + }; + exportedSegmentCount = segmentCount; + return snapshot; + }; + function newStep(startTime) { + return { + startTime, + endTime: startTime, + toolCalls: [] + }; + } + const ensureTurn = (ts) => turn ??= newTurn(ts); + const ensureStep = (ts) => step ??= newStep(ts); + const recordSubagentThread = (threadId, spawnCallId) => { + if (!turn.subagentThreadIds.includes(threadId)) turn.subagentThreadIds.push(threadId); + if (spawnCallId) turn.subagentSpawnCallIds[threadId] = spawnCallId; + }; + const closeStep = (ts, usage) => { + if (!step) return; + step.endTime = Math.max(step.endTime, ts); + if (usage) step.usage = usage; + turn.steps.push(step); + step = null; + }; + const finishTurn = (ts, opts) => { + if (!turn) return; + closeStep(ts); + turn.endTime = Math.max(turn.endTime, ts); + turn.completed = opts.completed; + turn.aborted = opts.aborted; + turn.userInput = turn.userInput ?? turn.userInputFallback; + turn.finalOutput = turn.lastAgentMessage ?? turn.steps.filter((s) => s.text).at(-1)?.text; + delete turn.lastAgentMessage; + delete turn.userInputFallback; + if (!(!turn.turnId && turn.userInput == null && turn.finalOutput == null && turn.steps.length === 0 && turn.subagentThreadIds.length === 0)) { + turn.systemPrompt = systemPromptFor(); + turn.toolDefinitions = [...toolDefinitions]; + turns.push(turn); + } + turn = null; + toolCallsById = /* @__PURE__ */ new Map(); + }; + for (const line of lines) { + const ts = Number.isFinite(Date.parse(line.timestamp)) ? Date.parse(line.timestamp) : lastTimestamp; + lastTimestamp = ts; + if (line.type === "turn_context") { + const t = ensureTurn(ts); + const p = line.payload; + t.model = p.model ?? t.model; + const effort = typeof p.effort === "string" ? p.effort : p.reasoning_effort; + if (typeof effort === "string") t.reasoningEffort = effort; + t.invocationParams = line.payload; + continue; + } + if (line.type === "response_item") { + const p = line.payload; + ensureTurn(ts); + if (p.type === "message") { + const msg = p; + const text = extractMessageText(msg.content); + if (msg.role === "user") { + for (const uri of extractImageUris(msg.content)) if (!turn.userImages.includes(uri)) turn.userImages.push(uri); + } + if (msg.role === "assistant") { + const s = ensureStep(ts); + if (text) s.text = s.text ? `${s.text}\n${text}` : text; + } else if (msg.role === "developer" && text) collect(developerMessages, text); + else if (msg.role === "user" && text) { + for (const name of skillsForPrompt(text)) if (!turn.promptSkills.includes(name)) turn.promptSkills.push(name); + if (/<\/?(environment_context|user_instructions|skill)\b/.test(text) || /^# AGENTS\.md instructions for\b/.test(text.trim())) collect(injectedContext, text); + else if (!turn.userInputFallback) turn.userInputFallback = text; + } + } else if (p.type === "function_call") { + const call = p; + const s = ensureStep(ts); + const tc = { + callId: call.call_id, + name: call.name, + args: parseArgs(call.arguments), + startTime: ts + }; + s.toolCalls.push(tc); + toolCallsById.set(tc.callId, tc); + } else if (p.type === "custom_tool_call") { + const call = p; + const s = ensureStep(ts); + const tc = { + callId: call.call_id, + name: call.name, + args: parseArgs(call.input), + startTime: ts + }; + s.toolCalls.push(tc); + toolCallsById.set(tc.callId, tc); + } else if (p.type === "local_shell_call") { + const call = p; + const s = ensureStep(ts); + const tc = { + callId: call.call_id ?? call.id ?? `local_shell_${ts}_${s.toolCalls.length}`, + name: "local_shell", + args: call.action ?? void 0, + startTime: ts + }; + s.toolCalls.push(tc); + toolCallsById.set(tc.callId, tc); + } else if (p.type === "web_search_call") { + const call = p; + const callId = call.id ?? `web_search_${ts}`; + const existing = toolCallsById.get(callId); + if (existing) { + existing.args = existing.args ?? call.action ?? void 0; + existing.endTime = Math.max(existing.endTime ?? ts, ts); + } else { + const s = ensureStep(ts); + const tc = { + callId, + name: "web_search", + args: call.action ?? void 0, + startTime: ts + }; + s.toolCalls.push(tc); + toolCallsById.set(callId, tc); + } + } else if (p.type === "function_call_output" || p.type === "custom_tool_call_output") { + const out = p; + const tc = toolCallsById.get(out.call_id); + if (tc) { + if (tc.output == null) tc.output = out.output; + tc.endTime = Math.max(tc.endTime ?? ts, ts); + if (tc.name === "spawn_agent") { + const spawned = parseArgs(toText(out.output)); + const agentId = spawned !== null && typeof spawned === "object" ? spawned.agent_id : void 0; + if (typeof agentId === "string" && agentId) recordSubagentThread(agentId, tc.callId); + } + } + } else if (p.type === "tool_search_output") { + const namespaces = Array.isArray(p.tools) ? p.tools : []; + for (const ns of namespaces) { + if (!ns || typeof ns !== "object") continue; + const entry = ns; + const nested = Array.isArray(entry.tools) ? entry.tools : [entry]; + for (const raw of nested) { + if (!raw || typeof raw !== "object") continue; + const tool = raw; + if (typeof tool.name !== "string" || !tool.name) continue; + if (toolDefinitions.some((known) => known.name === tool.name)) continue; + toolDefinitions.push({ + name: tool.name, + ...typeof tool.description === "string" ? { description: tool.description } : {}, + ...tool.parameters !== void 0 ? { parameters: tool.parameters } : {} + }); + } + } + } else if (p.type === "reasoning") { + const reasoning = extractReasoning(p); + if (reasoning) { + const s = ensureStep(ts); + s.reasoning = s.reasoning ? `${s.reasoning}\n${reasoning}` : reasoning; + } + } + continue; + } + if (line.type === "event_msg") { + const p = line.payload; + const et = p.type; + if (et === "task_started") { + if (turn) finishTurn(ts, { + completed: false, + aborted: false + }); + turn = newTurn(ts); + turn.turnId = typeof p.turn_id === "string" ? p.turn_id : void 0; + continue; + } + if (TURN_OPENING_EVENTS.has(et)) ensureTurn(ts); + else if (!turn) continue; + if (et === "user_message" && typeof p.message === "string") { + if (!turn.userInput) turn.userInput = p.message; + } else if (et === "item_completed" && p.item?.type === "UserMessage") { + const text = extractMessageText(p.item.content); + if (text && !turn.userInput) turn.userInput = text; + } else if (et === "item_completed" && p.item?.type === "SubAgentActivity") { + if (p.item.kind === "started" && typeof p.item.agent_thread_id === "string") recordSubagentThread(p.item.agent_thread_id, p.item.id); + } else if (et === "agent_message" && typeof p.message === "string") turn.lastAgentMessage = p.message; + else if (et === "token_count") { + if (p.info?.total_token_usage) turn.totalUsage = p.info.total_token_usage; + closeStep(ts, p.info?.last_token_usage ?? void 0); + } else if (et === "task_complete") finishTurn(ts, { + completed: true, + aborted: false + }); + else if (et === "turn_aborted") finishTurn(ts, { + completed: true, + aborted: true + }); + else { + if (et === "collab_agent_spawn_end" && typeof p.new_thread_id === "string") recordSubagentThread(p.new_thread_id, p.call_id); + if (et === "sub_agent_activity" && p.kind === "started" && typeof p.agent_thread_id === "string") recordSubagentThread(p.agent_thread_id, p.event_id); + if ((et === "mcp_tool_call_begin" || et === "mcp_tool_call_end") && typeof p.call_id === "string") { + const tc = toolCallsById.get(p.call_id); + const inv = p.invocation; + if (tc && typeof inv?.server === "string" && typeof inv?.tool === "string") tc.mcp = { + server: inv.server, + tool: inv.tool + }; + } + if (et === "web_search_end" && typeof p.call_id === "string") { + let tc = toolCallsById.get(p.call_id); + if (!tc) { + tc = { + callId: p.call_id, + name: "web_search", + args: void 0, + startTime: ts + }; + ensureStep(ts).toolCalls.push(tc); + toolCallsById.set(tc.callId, tc); + } + tc.args = tc.args ?? p.action ?? (typeof p.query === "string" ? { query: p.query } : void 0); + } + if (typeof p.call_id === "string" && et.endsWith("_end")) { + const tc = toolCallsById.get(p.call_id); + if (tc) { + tc.endTime = Math.max(tc.endTime ?? ts, ts); + if (p.status === "failed" || p.status === "declined") tc.error = extractToolError(p); + if (tc.output == null) tc.output = p.aggregated_output ?? p.stdout ?? p.result; + } + } + } + continue; + } + } + if (turn) finishTurn(lastTimestamp, { + completed: false, + aborted: false + }); + return { + sessionMeta, + turns + }; +} + +//#endregion +//#region src/trace.ts +init_esm$2(); +async function loadSession(file) { + const lines = []; + const input = createReadStream(file, { encoding: "utf-8" }); + for await (const raw of createInterface({ + input, + crlfDelay: Infinity + })) { + const trimmed = raw.trim(); + if (!trimmed) continue; + try { + lines.push(JSON.parse(trimmed)); + } catch {} + } + return lines; +} +async function readSessionMeta(file) { + let handle; + try { + handle = await fs$1.open(file, "r"); + const buffer = Buffer.alloc(65536); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0); + const text = buffer.subarray(0, bytesRead).toString("utf-8"); + const newline = text.indexOf("\n"); + const line = newline === -1 ? text : text.slice(0, newline); + const parsed = JSON.parse(line); + if (parsed.type !== "session_meta") return void 0; + const p = parsed.payload; + if (typeof p.id !== "string") return void 0; + const ts = Date.parse(parsed.timestamp); + const nickname = p.agent_nickname ?? p.source?.subagent?.thread_spawn?.agent_nickname; + return { + threadId: p.id, + parentThreadId: typeof p.parent_thread_id === "string" ? p.parent_thread_id : void 0, + startTime: Number.isFinite(ts) ? ts : 0, + nickname: typeof nickname === "string" && nickname ? nickname : void 0 + }; + } catch { + return; + } finally { + await handle?.close(); + } +} +async function buildSubagentIndex(rolloutFile, options = {}) { + const rolloutDirectory = path$1.dirname(rolloutFile); + const dated = /[\/]\d{4}[\/]\d{2}[\/]\d{2}$/.test(rolloutDirectory); + const root = dated ? path$1.resolve(rolloutDirectory, "../../..") : rolloutDirectory; + const fromDay = path$1.relative(root, path$1.dirname(rolloutFile)); + const bounded = !options.includeEarlierDays && /^\d{4}\/\d{2}\/\d{2}$/.test(fromDay); + const index = { + byParent: /* @__PURE__ */ new Map(), + byThread: /* @__PURE__ */ new Map() + }; + async function walk(dir, rel, recursive = true) { + if (bounded && rel && rel < fromDay.slice(0, rel.length)) return; + let entries; + try { + entries = await fs$1.readdir(dir, { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + const full = path$1.join(dir, entry.name); + if (entry.isDirectory()) { + if (!recursive) continue; + await walk(full, rel ? `${rel}/${entry.name}` : entry.name); + continue; + } + if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue; + const meta = await readSessionMeta(full); + if (!meta) continue; + if (index.byThread.has(meta.threadId)) continue; + const rollout = { + threadId: meta.threadId, + parentThreadId: meta.parentThreadId, + file: full, + startTime: meta.startTime, + nickname: meta.nickname + }; + index.byThread.set(meta.threadId, rollout); + if (!meta.parentThreadId) continue; + index.byParent.set(meta.parentThreadId, [...index.byParent.get(meta.parentThreadId) ?? [], rollout]); + } + } + await walk(root, "", dated); + const codexHome = path$1.resolve(process.env.CODEX_HOME ?? path$1.join(os$1.homedir(), ".codex")); + if (path$1.dirname(path$1.resolve(root)) === codexHome && (path$1.basename(root) === "sessions" || path$1.basename(root) === "archived_sessions")) { + if (path$1.basename(root) !== "sessions") await walk(path$1.join(codexHome, "sessions"), "", true); + if (path$1.basename(root) !== "archived_sessions") await walk(path$1.join(codexHome, "archived_sessions"), "", false); + } + return index; +} +function turnIndexByNickname(turns) { + const byNickname = /* @__PURE__ */ new Map(); + const ambiguous = /* @__PURE__ */ new Set(); + turns.forEach((turn, index) => { + for (const tc of turn.steps.flatMap((s) => s.toolCalls)) { + if (tc.name !== "spawn_agent" || tc.output == null) continue; + const out = parseArgs(toText(tc.output)); + const nickname = out !== null && typeof out === "object" ? out.nickname : void 0; + if (typeof nickname !== "string" || !nickname) continue; + if (byNickname.has(nickname) && byNickname.get(nickname) !== index) ambiguous.add(nickname); + byNickname.set(nickname, index); + } + }); + for (const nickname of ambiguous) byNickname.delete(nickname); + return byNickname; +} +function turnIndexAt(turns, startTime) { + const running = turns.findIndex((t) => startTime >= t.startTime && startTime <= t.endTime); + if (running !== -1) return running; + let last = 0; + for (let i = 0; i < turns.length; i++) if (turns[i].startTime <= startTime) last = i; + return last; +} +/** +* Placeholder parent span id used to pin a deterministic trace id on a root +* span (the pattern the Langfuse SDK documents for custom trace ids). The id +* never exists as a real span, so Langfuse still renders the turn as the +* trace root. +*/ +const SEED_PARENT_SPAN_ID = "0123456789abcdef"; +/** +* Derive the deterministic trace id for a turn from `config.trace_seed`. +* +* Main-thread turn N (1-based, rollout order): createTraceId(`${seed}:${N}`) +* Subagent-thread turn N: createTraceId(`${seed}:${threadId}:${N}`) +* +* The main-thread form deliberately excludes the thread id so external systems +* can precompute trace ids (hex(sha256(seed)).slice(0, 32)) before the Codex +* thread exists. Returns `undefined` (auto-generated ids) when no seed is set +* or derivation fails — the hook must never block an upload. +*/ +async function seededTraceParent(config, sessionMeta, turnNumber) { + if (!config.trace_seed) return void 0; + try { + const seed = sessionMeta.isSubagentThread ? `${config.trace_seed}:${sessionMeta.sessionId}:${turnNumber}` : `${config.trace_seed}:${turnNumber}`; + return { + traceId: await createTraceId(seed), + spanId: SEED_PARENT_SPAN_ID, + traceFlags: TraceFlags.SAMPLED, + isRemote: true + }; + } catch (error) { + debugLog("failed to derive seeded trace id; falling back to auto-generated:", error); + if (config.fail_on_error) throw error; + return; + } +} +function isTokenCount(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +function toUsageDetails(usage) { + if (!usage) return void 0; + const { input_tokens: input, output_tokens: output, total_tokens: total, cached_input_tokens: cached, reasoning_output_tokens: reasoning } = usage; + if (!isTokenCount(input) || !isTokenCount(output) || !isTokenCount(total) || total !== input + output) { + debugLog("dropping usage: missing or inconsistent token counts", usage); + return; + } + if (cached !== void 0 && (!isTokenCount(cached) || cached > input) || reasoning !== void 0 && (!isTokenCount(reasoning) || reasoning > output)) { + debugLog("dropping usage: implausible cached/reasoning details", usage); + return; + } + return { + prompt_tokens: input, + completion_tokens: output, + total_tokens: total, + ...cached !== void 0 ? { prompt_tokens_details: { cached_tokens: cached } } : {}, + ...reasoning !== void 0 ? { completion_tokens_details: { reasoning_tokens: reasoning } } : {} + }; +} +function buildGenerationOutput(step) { + const output = {}; + if (step.text) output.content = step.text; + if (step.reasoning) output.reasoning = step.reasoning; + if (step.toolCalls.length > 0) output.tool_calls = step.toolCalls.map((tc) => ({ + id: tc.callId, + name: tc.name, + arguments: tc.args + })); + return Object.keys(output).length > 0 ? output : void 0; +} +function toolObservationName(tc) { + const skill = skillsForToolCall(tc)[0]; + if (skill) return `skill:${skill}`; + if (tc.mcp) return `${tc.mcp.server}.${tc.mcp.tool}`; + return tc.name || "tool"; +} +function systemPromptText(systemPrompt) { + if (!systemPrompt) return void 0; + const segments = [ + systemPrompt.baseInstructions, + ...systemPrompt.developerMessages, + ...systemPrompt.injectedContext + ].filter((segment) => typeof segment === "string" && segment.length > 0); + return segments.length > 0 ? segments.join("\n\n") : void 0; +} +function systemPromptMetadata(systemPrompt) { + const baseChars = systemPrompt.baseInstructions?.length ?? 0; + const developerChars = systemPrompt.developerMessages.reduce((n, m) => n + m.length, 0); + const injectedChars = systemPrompt.injectedContext.reduce((n, m) => n + m.length, 0); + return { + "codex.system_prompt.total_chars": baseChars + developerChars + injectedChars, + "codex.system_prompt.base_instructions_chars": baseChars, + "codex.system_prompt.developer_chars": developerChars, + "codex.system_prompt.developer_message_count": systemPrompt.developerMessages.length, + "codex.system_prompt.injected_context_chars": injectedChars, + "codex.system_prompt.injected_context_count": systemPrompt.injectedContext.length, + "codex.system_prompt.changed_this_turn": systemPrompt.changed + }; +} +function assistantMessage(step) { + return { + role: "assistant", + ...step.text ? { content: step.text } : {}, + ...step.reasoning ? { thinking: [{ + type: "thinking", + content: step.reasoning + }] } : {}, + ...step.toolCalls.length > 0 ? { tool_calls: step.toolCalls.map((tc) => ({ + id: tc.callId, + type: "function", + function: { + name: toolObservationName(tc), + ...tc.args !== void 0 ? { arguments: toText(tc.args) } : {} + } + })) } : {} + }; +} +function toolMessages(step) { + return step.toolCalls.map((tc) => ({ + role: "tool", + tool_call_id: tc.callId, + name: toolObservationName(tc), + content: tc.output != null ? toText(tc.output) : tc.error ?? "", + ...tc.error ? { is_error: true } : {} + })); +} +function turnHistoryMessages(turn) { + const messages = []; + const user = userMessage(turn); + if (user) messages.push(user); + for (const step of turn.steps) { + messages.push(assistantMessage(step)); + messages.push(...toolMessages(step)); + } + return messages; +} +function generationInput(systemMessage, historyPrefix, turn, stepIndex) { + const messages = []; + if (systemMessage) messages.push({ + role: "system", + content: systemMessage + }); + messages.push(...historyPrefix); + const user = userMessage(turn); + if (user) messages.push(user); + for (let j = 0; j < stepIndex; j++) { + messages.push(assistantMessage(turn.steps[j])); + messages.push(...toolMessages(turn.steps[j])); + } + return messages.length > 0 ? messages : void 0; +} +function toMultimodalContent(text, images) { + if (images.length === 0) return text; + return [...text ? [{ + type: "text", + text + }] : [], ...images.map((url) => ({ + type: "image_url", + image_url: { url } + }))]; +} +function userMessage(turn) { + const content = toMultimodalContent(turn.userInput, turn.userImages); + return content === void 0 ? void 0 : { + role: "user", + content + }; +} +function attachToolDefinitions(input, tools) { + if (!input || tools.length === 0) return input; + const [first, ...rest] = input; + return first ? [{ + ...first, + tools + }, ...rest] : input; +} +function generationEnd(step) { + const firstToolCall = step.toolCalls.reduce((earliest, tc) => earliest === void 0 ? tc.startTime : Math.min(earliest, tc.startTime), void 0); + return Math.max(step.startTime, Math.min(firstToolCall ?? step.endTime, step.endTime)); +} +async function emitTurn(turn, sessionMeta, ctx) { + const isSubagent = sessionMeta.isSubagentThread === true || ctx.parentObservation != null; + const skipPayloads = ctx.legacyUploaded || ctx.unchanged; + const outerSeed = currentIdSeed(); + seedIds(`${sessionMeta.sessionId}:${turn.turnId ?? "no-turn-id"}`); + const root = startObservation(isSubagent ? "Codex Subagent Turn" : "Codex Turn", { + input: skipPayloads ? void 0 : toMultimodalContent(turn.userInput, turn.userImages), + output: skipPayloads ? void 0 : turn.finalOutput, + level: turn.aborted ? "WARNING" : void 0, + statusMessage: turn.aborted ? "Turn interrupted by user" : void 0, + metadata: { + "codex.turn_id": turn.turnId, + "codex.thread_id": sessionMeta.sessionId, + "codex.model": turn.model, + "codex.reasoning_effort": turn.reasoningEffort, + "codex.model_provider": sessionMeta.modelProvider, + "codex.cli_version": sessionMeta.cliVersion, + "codex.aborted": turn.aborted, + ...skipPayloads ? { "codex.legacy_uploaded": true } : {}, + ...ctx.incremental ? { "codex.completed": ctx.final ?? turn.completed } : {}, + "codex.tool_call_count": turn.steps.reduce((n, s) => n + s.toolCalls.length, 0), + ...ctx.attached && ctx.parentSpanContext ? { + "codex.parent_trace_id": ctx.parentSpanContext.traceId, + "codex.parent_span_id": ctx.parentSpanContext.spanId + } : {}, + ...turn.systemPrompt ? systemPromptMetadata(turn.systemPrompt) : {}, + ...turn.userImages.length ? { "codex.image_count": turn.userImages.length } : {}, + ...turn.toolDefinitions.length ? { "codex.tool_definition_count": turn.toolDefinitions.length } : {} + } + }, { + asType: "agent", + startTime: new Date(turn.startTime), + parentSpanContext: ctx.parentObservation?.otelSpan.spanContext() ?? ctx.parentSpanContext + }); + if (ctx.attached) root.otelSpan.setAttribute(LangfuseOtelSpanAttributes.IS_APP_ROOT, false); + let failure; + try { + const systemMessage = skipPayloads ? void 0 : systemPromptText(turn.systemPrompt); + const historyPrefix = ctx.historyPrefix ?? []; + const spawnObservations = /* @__PURE__ */ new Map(); + let pending = 0; + let previousStepFingerprint = createHash("sha256").update(JSON.stringify({ + historyPrefix, + systemPrompt: turn.systemPrompt, + tools: turn.toolDefinitions, + model: turn.model, + userInput: turn.userInput, + userImages: turn.userImages, + config: ctx.config, + parent: root.otelSpan.spanContext() + })).digest("hex"); + for (let i = 0; i < turn.steps.length; i++) { + const step = turn.steps[i]; + const stepFingerprintKey = `${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}:step:${i}`; + const stepFingerprint = createHash("sha256").update(previousStepFingerprint).update(JSON.stringify(step)).digest("hex"); + previousStepFingerprint = stepFingerprint; + const skipStep = skipPayloads || ctx.acknowledgedTurns?.[stepFingerprintKey] === stepFingerprint; + if (ctx.incremental && !ctx.legacyIdMode) seedIds(`${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}:step:${i}`); + const generation = startObservation(isSubagent ? "LLM Subagent" : "LLM", { + input: skipStep ? void 0 : attachToolDefinitions(generationInput(systemMessage, historyPrefix, turn, i), turn.toolDefinitions), + output: skipStep ? void 0 : buildGenerationOutput(step), + model: turn.model, + ...turn.reasoningEffort ? { modelParameters: { reasoning_effort: turn.reasoningEffort } } : {}, + usageDetails: toUsageDetails(step.usage), + metadata: { + "codex.step_index": i, + ...skipStep ? { "codex.legacy_uploaded": true } : {}, + "codex.reasoning_effort": turn.reasoningEffort + } + }, { + asType: "generation", + startTime: new Date(step.startTime), + parentSpanContext: root.otelSpan.spanContext() + }); + for (const tc of step.toolCalls) { + if (ctx.incremental && !ctx.legacyIdMode) seedIds(`${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}:tool:${tc.callId}`); + const observation = emitToolCall(tc, root, step.endTime, ctx.incremental, skipPayloads); + if (tc.name === "spawn_agent") spawnObservations.set(tc.callId, observation); + if (ctx.incremental && !skipStep) await backpressureInstrumentation(); + if (ctx.incremental && !skipStep && ++pending >= 16) { + await flushInstrumentation(); + pending = 0; + } + } + generation.end(new Date(generationEnd(step))); + if (ctx.pendingTurnFingerprints) ctx.pendingTurnFingerprints[stepFingerprintKey] = stepFingerprint; + if (ctx.incremental && !skipStep && ++pending >= 16) { + await flushInstrumentation(); + pending = 0; + } + } + for (const hook of ctx.hookEvents ?? []) if (!hook.replayOnly && hook.input.session_id === sessionMeta.sessionId && hook.input.turn_id === turn.turnId && !ctx.emittedHookIds?.has(hook.id)) { + emitHookObservation(hook, root.otelSpan.spanContext()); + ctx.emittedHookIds?.add(hook.id); + } + const announced = []; + for (const threadId of turn.subagentThreadIds) { + const rollout = ctx.subagentIndex.byThread.get(threadId); + if (!rollout) { + debugLog(`subagent rollout not found for thread ${threadId}`); + continue; + } + announced.push(rollout); + } + for (const sub of [...announced, ...ctx.unannouncedSubagents ?? []]) { + if (ctx.seenThreadIds.has(sub.threadId)) continue; + ctx.seenThreadIds.add(sub.threadId); + const seedBeforeChild = currentIdSeed(); + await convertRollout(sub.file, { + config: ctx.config, + parentObservation: spawnObservations.get(turn.subagentSpawnCallIds[sub.threadId]) ?? root, + subagentIndex: ctx.subagentIndex, + seenThreadIds: ctx.seenThreadIds, + ancestorTurnIds: ctx.inheritableTurnIds, + incremental: ctx.incremental, + hookEvents: ctx.hookEvents, + emittedHookIds: ctx.emittedHookIds, + legacyIdMode: ctx.legacyIdMode, + legacyCutoff: ctx.legacyCutoff, + acknowledgedTurns: ctx.acknowledgedTurns, + pendingTurnFingerprints: ctx.pendingTurnFingerprints + }); + seedIds(seedBeforeChild); + } + } catch (error) { + failure = error; + debugLog(`failed to convert turn ${turn.turnId ?? "(no turn id)"}:`, error); + root.update({ + level: "ERROR", + statusMessage: `Trace conversion failed: ${error instanceof Error ? error.message : String(error)}` + }); + } + root.end(new Date(turn.endTime)); + seedIds(outerSeed); + if (failure && (ctx.incremental || ctx.config.fail_on_error)) throw failure; +} +function emitToolCall(tc, parent, fallbackEnd, incremental, legacyUploaded) { + const tool = startObservation(toolObservationName(tc), { + input: legacyUploaded ? void 0 : tc.args, + output: legacyUploaded ? void 0 : tc.output != null ? toText(tc.output) : void 0, + level: tc.error ? "ERROR" : void 0, + statusMessage: tc.error, + metadata: { + ...legacyUploaded ? { "codex.legacy_uploaded": true } : {}, + "codex.call_id": tc.callId, + "codex.tool_name": tc.name || "tool", + ...incremental ? { "codex.completed": tc.endTime != null } : {} + } + }, { + asType: "tool", + startTime: new Date(tc.startTime), + parentSpanContext: parent.otelSpan.spanContext() + }); + tool.end(new Date(tc.endTime ?? fallbackEnd)); + return tool; +} +function isFinal(turn, stoppedTurnId, supersededByLaterTurn) { + if (turn.turnId == null) return false; + return turn.completed || supersededByLaterTurn || turn.turnId === stoppedTurnId; +} +async function readTurnIds(file) { + const ids = /* @__PURE__ */ new Set(); + for (const line of await loadSession(file)) { + if (line.type !== "event_msg") continue; + const p = line.payload; + if (p.type === "task_started" && typeof p.turn_id === "string") ids.add(p.turn_id); + } + return ids; +} +async function ancestorTurnIdsOf(sessionMeta, index) { + const owned = /* @__PURE__ */ new Set(); + const seen = /* @__PURE__ */ new Set([sessionMeta.sessionId]); + let ancestor = sessionMeta.parentThreadId; + while (ancestor && !seen.has(ancestor)) { + seen.add(ancestor); + const rollout = index.byThread.get(ancestor); + if (rollout) try { + const before = owned.size; + for (const id of await readTurnIds(rollout.file)) owned.add(id); + debugLog(`ancestor ${ancestor} owns ${owned.size - before} turn(s)`); + } catch (error) { + debugLog(`failed to read ancestor ${ancestor}; not skipping its turns:`, error); + break; + } + ancestor = rollout?.parentThreadId; + } + return owned; +} +async function convertRollout(rolloutFile, options) { + const { sessionMeta, turns } = parseSession(await loadSession(rolloutFile)); + const emittedHookIds = options.emittedHookIds ?? /* @__PURE__ */ new Set(); + const legacyTurnIds = options.incremental ? await loadLegacyTurnIds(rolloutFile) : /* @__PURE__ */ new Set(); + const hooks = (options.hookEvents ?? []).filter((hook) => hook.input.session_id === sessionMeta.sessionId); + for (const hook of hooks) { + hook.contextNeeded = false; + const turn = hook.input.turn_id ? turns.find((t) => t.turnId === hook.input.turn_id) : turns.filter((candidate) => candidate.startTime <= hook.timestamp).at(-1); + if (!turn) { + hook.contextNeeded = [ + "PostToolUse", + "Stop", + "SubagentStop", + "Interrupt", + "SessionEnd" + ].includes(hook.input.hook_event_name ?? ""); + continue; + } + hook.input.turn_id ??= turn.turnId; + if (hook.input.hook_event_name === "Stop" || hook.input.hook_event_name === "Interrupt" || hook.input.hook_event_name === "SessionEnd" || hook.input.hook_event_name === "SubagentStop" && (sessionMeta.isSubagentThread || options.parentObservation != null)) { + hook.contextNeeded = !turn.completed; + if (!turn.completed) turn.endTime = Math.max(turn.endTime, hook.timestamp); + turn.completed = true; + turn.aborted ||= hook.input.hook_event_name === "Interrupt"; + if (typeof hook.input.last_assistant_message === "string" && turn.finalOutput !== hook.input.last_assistant_message) { + turn.finalOutput = hook.input.last_assistant_message; + hook.contextNeeded = true; + } + } + const toolId = hook.input.tool_use_id ?? hook.input.tool_call_id; + if (hook.input.hook_event_name === "PostToolUse" && toolId) { + const tool = turn.steps.flatMap((step) => step.toolCalls).find((tc) => tc.callId === toolId); + if (!tool) hook.contextNeeded = true; + if (tool && tool.output == null && hook.input.tool_response !== void 0) { + hook.contextNeeded = true; + tool.output = hook.input.tool_response; + tool.endTime = hook.timestamp; + turn.endTime = Math.max(turn.endTime, hook.timestamp); + } + } + } + const historyPrefixes = []; + const turnFingerprints = turns.map((turn) => createHash("sha256").update(JSON.stringify({ + turn, + config: options.config, + parent: options.parentObservation?.otelSpan.spanContext() ?? options.parentSpanContext + })).digest("hex")); + for (let i = 0; i < turns.length; i++) if (i > 0) turnFingerprints[i] = createHash("sha256").update(`${turnFingerprints[i - 1]}:${turnFingerprints[i]}`).digest("hex"); + { + const seen = []; + for (const turn of turns) { + historyPrefixes.push([...seen]); + seen.push(...turnHistoryMessages(turn)); + } + } + debugLog(`parsed ${turns.length} turn(s) from ${path$1.basename(rolloutFile)}`); + const subagentIndex = options.subagentIndex ?? await buildSubagentIndex(rolloutFile, { includeEarlierDays: sessionMeta.isSubagentThread === true }); + const seenThreadIds = options.seenThreadIds ?? /* @__PURE__ */ new Set(); + seenThreadIds.add(sessionMeta.sessionId); + const announced = new Set(turns.flatMap((t) => t.subagentThreadIds)); + const unannounced = (subagentIndex.byParent.get(sessionMeta.sessionId) ?? []).filter((s) => !announced.has(s.threadId) && !seenThreadIds.has(s.threadId)); + const spawnTurnOf = unannounced.length > 0 ? turnIndexByNickname(turns) : /* @__PURE__ */ new Map(); + const byTurn = /* @__PURE__ */ new Map(); + for (const sub of unannounced) { + const viaNickname = sub.nickname !== void 0 ? spawnTurnOf.get(sub.nickname) : void 0; + const i = viaNickname ?? turnIndexAt(turns, sub.startTime); + debugLog(`recovered unannounced subagent ${sub.threadId} for thread ${sessionMeta.sessionId}: turn ${i + 1} via ${viaNickname !== void 0 ? `nickname ${sub.nickname}` : "start time"}`); + byTurn.set(i, [...byTurn.get(i) ?? [], sub]); + } + const ancestorTurnIds = options.ancestorTurnIds ?? (sessionMeta.isSubagentThread ? await ancestorTurnIdsOf(sessionMeta, subagentIndex) : void 0); + const carriedSubagents = []; + const subagentsFor = (turnIndex) => { + const own = byTurn.get(turnIndex) ?? []; + const all = carriedSubagents.length > 0 ? [...carriedSubagents, ...own] : own; + carriedSubagents.length = 0; + return all.length > 0 ? all : void 0; + }; + const skipInherited = (turn, turnIndex) => { + if (!turn.turnId || !ancestorTurnIds?.has(turn.turnId)) return false; + debugLog(`skipping turn ${turn.turnId}: inherited from an ancestor thread`); + carriedSubagents.push(...byTurn.get(turnIndex) ?? []); + return true; + }; + const inheritableTurnIds = new Set(ancestorTurnIds); + for (const turn of turns) if (turn.turnId) inheritableTurnIds.add(turn.turnId); + if (options.parentObservation) { + for (let turnIndex = 0; turnIndex < turns.length; turnIndex++) { + const turn = turns[turnIndex]; + if (skipInherited(turn, turnIndex)) continue; + const fingerprintKey = `${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}`; + await emitTurn(turn, sessionMeta, { + config: options.config, + rolloutFile, + unchanged: options.acknowledgedTurns?.[fingerprintKey] === turnFingerprints[turnIndex], + acknowledgedTurns: options.acknowledgedTurns, + pendingTurnFingerprints: options.pendingTurnFingerprints, + parentObservation: options.parentObservation, + subagentIndex, + seenThreadIds, + unannouncedSubagents: subagentsFor(turnIndex), + inheritableTurnIds, + historyPrefix: historyPrefixes[turnIndex], + incremental: options.incremental, + hookEvents: options.hookEvents, + emittedHookIds, + legacyIdMode: options.legacyIdMode, + legacyCutoff: options.legacyCutoff, + legacyUploaded: options.legacyIdMode && turn.completed && turn.endTime <= (options.legacyCutoff ?? 0), + final: isFinal(turn, options.stoppedTurnId, turnIndex < turns.length - 1) + }); + if (options.pendingTurnFingerprints) options.pendingTurnFingerprints[fingerprintKey] = turnFingerprints[turnIndex]; + } + return []; + } + const uploaded = await loadUploadedTurnIds(rolloutFile); + const exportedTurnIds = []; + const attached = options.parentSpanContext != null; + for (let turnIndex = 0; turnIndex < turns.length; turnIndex++) { + const turn = turns[turnIndex]; + if (skipInherited(turn, turnIndex)) continue; + const final = isFinal(turn, options.stoppedTurnId, turnIndex < turns.length - 1); + if (!options.incremental && !final) { + debugLog(`skipping turn ${turn.turnId ?? "(no turn id)"}: not final`); + continue; + } + if (!options.incremental && turn.turnId && uploaded.has(turn.turnId)) continue; + const parentSpanContext = options.parentSpanContext ?? await seededTraceParent(options.config, sessionMeta, turnIndex + 1); + const fingerprintKey = `${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}`; + const emit = () => emitTurn(turn, sessionMeta, { + config: options.config, + rolloutFile, + unchanged: options.acknowledgedTurns?.[fingerprintKey] === turnFingerprints[turnIndex], + acknowledgedTurns: options.acknowledgedTurns, + pendingTurnFingerprints: options.pendingTurnFingerprints, + parentSpanContext, + attached, + subagentIndex, + seenThreadIds, + unannouncedSubagents: subagentsFor(turnIndex), + inheritableTurnIds, + historyPrefix: historyPrefixes[turnIndex], + incremental: options.incremental, + hookEvents: options.hookEvents, + emittedHookIds, + legacyIdMode: legacyTurnIds.has(turn.turnId ?? ""), + legacyCutoff: legacyTurnIds.has(turn.turnId ?? "") ? turn.endTime : void 0, + legacyUploaded: legacyTurnIds.has(turn.turnId ?? ""), + final: isFinal(turn, options.stoppedTurnId, turnIndex < turns.length - 1) + }); + if (attached) await emit(); + else { + const tags = traceTags(options.config, turn); + await propagateAttributes({ + sessionId: sessionMeta.sessionId, + traceName: sessionMeta.isSubagentThread ? "Codex Subagent Turn" : "Codex Turn", + ...options.config.user_id ? { userId: options.config.user_id } : {}, + ...tags.length > 0 ? { tags } : {}, + ...options.config.metadata ? { metadata: options.config.metadata } : {} + }, emit); + } + if (options.pendingTurnFingerprints) options.pendingTurnFingerprints[fingerprintKey] = turnFingerprints[turnIndex]; + if (final && turn.turnId && !uploaded.has(turn.turnId)) { + uploaded.add(turn.turnId); + exportedTurnIds.push(turn.turnId); + } + } + if (options.incremental && !options.parentObservation) { + for (const hook of options.hookEvents ?? []) if (!hook.replayOnly && !emittedHookIds.has(hook.id)) { + emitHookObservation(hook); + emittedHookIds.add(hook.id); + } + } + return exportedTurnIds; +} +function emitHookObservation(hook, parentSpanContext) { + const previous = currentIdSeed(); + seedIds(`hook:${hook.id}`); + const emit = () => startObservation(`Codex Hook: ${hook.input.hook_event_name ?? "Unknown"}`, { + input: hook.input, + metadata: { + "codex.hook_event_name": hook.input.hook_event_name, + "codex.thread_id": hook.input.session_id, + "codex.turn_id": hook.input.turn_id + } + }, { + asType: "span", + startTime: new Date(hook.timestamp), + parentSpanContext: hook.standalone ? void 0 : parentSpanContext + }); + const observation = emit(); + observation.otelSpan.setAttribute(LangfuseOtelSpanAttributes.OBSERVATION_TYPE, "event"); + if (hook.input.session_id && (hook.standalone || !parentSpanContext)) { + observation.otelSpan.setAttribute(LangfuseOtelSpanAttributes.TRACE_SESSION_ID, hook.input.session_id); + observation.otelSpan.setAttribute(LangfuseOtelSpanAttributes.TRACE_COMPAT_SESSION_ID, hook.input.session_id); + } + observation.end(new Date(hook.timestamp)); + seedIds(previous); +} +/** Child hooks use the same root checkpoint and parenting as parent hooks. */ +async function resolveRootRollout(rolloutFile) { + const meta = await readSessionMeta(rolloutFile); + const index = await buildSubagentIndex(rolloutFile, { includeEarlierDays: !!meta?.parentThreadId }); + let file = rolloutFile; + let parent = meta?.parentThreadId; + const seen = /* @__PURE__ */ new Set(); + while (parent && !seen.has(parent)) { + seen.add(parent); + const ancestor = index.byThread.get(parent); + if (!ancestor) break; + file = ancestor.file; + parent = ancestor.parentThreadId; + } + return { + file, + index + }; +} + +//#endregion +//#region src/index.ts +let failOnError = process.env.LANGFUSE_CODEX_FAIL_ON_ERROR === "true"; +function spoolFor(sessionId) { + return path$1.join(process.env.CODEX_HOME ?? path$1.join(os$1.homedir(), ".codex"), "langfuse-hooks", createHash("sha256").update(sessionId).digest("hex")); +} +async function importSessionSpool(spool, file, waitSeconds = 0) { + if ((await pendingHooks(spool)).length === 0) return; + const release = await acquireRolloutLock(spool, waitSeconds); + if (!release) return; + try { + for (const event of await pendingHooks(spool)) { + await enqueueHook(file, event.input, event); + await acknowledgeHooks(spool, [event]); + } + } finally { + await release(); + } +} +/** Every hook queues durably before a bounded, serialized incremental upload. */ +async function runHook() { + let hookInput; + try { + hookInput = await readStdin(); + } catch { + return; + } + const config = await getConfig(); + setDebug(config.debug); + failOnError = config.fail_on_error; + if (!config.enabled || !config.public_key || !config.secret_key) return; + const started = Date.now(); + const shortHook = hookInput.hook_event_name === "Interrupt" || hookInput.hook_event_name === "SessionEnd"; + if (hookInput.hook_event_name === "SubagentStop" && hookInput.agent_id) hookInput = { + ...hookInput, + session_id: hookInput.agent_id, + turn_id: hookInput.session_id === hookInput.agent_id ? hookInput.turn_id : void 0 + }; + const sessionSpool = spoolFor(hookInput.session_id ?? "unknown"); + await fs$1.mkdir(path$1.dirname(sessionSpool), { + recursive: true, + mode: 448 + }); + await enqueueHook(sessionSpool, hookInput, { + id: randomUUID(), + timestamp: started, + input: hookInput, + standalone: !hookInput.transcript_path + }); + if (!hookInput.transcript_path) { + const release = await acquireRolloutLock(sessionSpool, shortHook ? Math.max(0, (2500 - Date.now() + started) / 1e3) : 10); + if (!release) return; + try { + const events = await pendingHooks(sessionSpool); + const instrumentation = setupInstrumentation(config, { acknowledged: await loadObservationCheckpoint(sessionSpool) }); + let failure; + try { + for (const event of events) emitHookObservation(event); + } catch (error) { + failure = error; + } + try { + await instrumentation.shutdown(); + } catch (error) { + failure ??= error; + } + await saveObservationCheckpoint(sessionSpool, instrumentation.acknowledged()); + if (failure) { + if (config.fail_on_error) throw failure; + debugLog("early hook remains retryable", failure); + return; + } + await acknowledgeHooks(sessionSpool, events); + } finally { + await release(); + } + return; + } + const requestedFile = hookInput.agent_transcript_path ?? hookInput.transcript_path; + const resolved = await resolveRootRollout(requestedFile); + const file = resolved.file; + let index = resolved.index; + if (shortHook && Date.now() - started >= 2500) return; + const waitBudget = () => shortHook ? Math.max(0, (2500 - Date.now() + started) / 1e3) : 10; + await importSessionSpool(sessionSpool, file, waitBudget()); + const release = await acquireRolloutLock(file, waitBudget()); + if (!release) { + debugLog("uploader busy; hook remains in durable inbox"); + return; + } + try { + const parentSpanContext = readExternalParentSpanContext(process.env, config.fail_on_error); + for (let pass = 0; pass < 4; pass++) { + if (shortHook && Date.now() - started >= 2500) return; + if (pass > 0) index = await buildSubagentIndex(file); + const rootThread = [...index.byThread.values()].find((rollout) => rollout.file === file)?.threadId; + const sessions = /* @__PURE__ */ new Set([hookInput.session_id ?? "unknown", ...rootThread ? [rootThread] : []]); + const parents = rootThread ? [rootThread] : []; + for (let cursor = 0; cursor < parents.length; cursor++) for (const child of index.byParent.get(parents[cursor]) ?? []) if (!sessions.has(child.threadId)) { + sessions.add(child.threadId); + parents.push(child.threadId); + } + for (const session of sessions) await importSessionSpool(spoolFor(session), file, waitBudget()); + const events = await pendingHooks(file); + if (events.length === 0) break; + const contextualEvents = [...await loadHookContext(file), ...events]; + const instrumentation = setupInstrumentation(config, { acknowledged: await loadObservationCheckpoint(file) }); + const acknowledgedTurns = await loadTurnCheckpoint(file); + const pendingTurnFingerprints = {}; + let exportedTurnIds = []; + let failure; + try { + exportedTurnIds = await convertRollout(file, { + config, + parentSpanContext, + subagentIndex: index, + incremental: true, + hookEvents: contextualEvents, + acknowledgedTurns, + pendingTurnFingerprints + }); + } catch (error) { + failure = error; + debugLog("rollout conversion failed", error); + } + try { + await instrumentation.shutdown(); + } catch (error) { + failure ??= error; + } + const retainedByKey = /* @__PURE__ */ new Map(); + for (const event of contextualEvents.filter((event) => event.contextNeeded)) { + const tool = event.input.tool_use_id ?? event.input.tool_call_id; + const key = `${event.input.session_id}:${event.input.turn_id}:${tool ? `tool:${tool}` : "final"}`; + retainedByKey.set(key, { + ...event, + replayOnly: true + }); + } + const retained = [...retainedByKey.values()]; + await saveObservationCheckpoint(file, instrumentation.acknowledged(), retained, failure ? acknowledgedTurns : { + ...acknowledgedTurns, + ...pendingTurnFingerprints + }); + if (failure) { + if (config.fail_on_error) throw failure; + debugLog("export incomplete; durable hooks and observations remain retryable", failure); + return; + } + for (const turnId of exportedTurnIds) await markTurnUploaded(file, turnId); + await acknowledgeHooks(file, events); + } + } finally { + await release(); + } +} +runHook().catch((error) => { + if (process.env.LANGFUSE_CODEX_DEBUG === "true") console.error("[langfuse-codex] fatal:", error); + if (failOnError) process.exitCode = 1; +}); + +//#endregion +export { runHook }; \ No newline at end of file diff --git a/plugins/tracing/hooks/hooks.json b/plugins/tracing/hooks/hooks.json index 02f9566..c8f6fa7 100644 --- a/plugins/tracing/hooks/hooks.json +++ b/plugins/tracing/hooks/hooks.json @@ -1,5 +1,135 @@ { "hooks": { + "PreToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "PermissionRequest": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "PreCompact": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "PostCompact": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 3, + "async": false, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "SubagentStart": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": true, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "SubagentStop": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 30, + "async": false, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], "Stop": [ { "hooks": [ @@ -7,7 +137,21 @@ "type": "command", "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", "timeout": 30, - "statusMessage": "Uploading Codex trace to Langfuse" + "async": false, + "statusMessage": "Uploading Codex activity to Langfuse" + } + ] + } + ], + "Interrupt": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${PLUGIN_ROOT}/dist/index.mjs\"", + "timeout": 3, + "async": false, + "statusMessage": "Uploading Codex activity to Langfuse" } ] } diff --git a/plugins/tracing/package.json b/plugins/tracing/package.json index 4348121..f064ad4 100644 --- a/plugins/tracing/package.json +++ b/plugins/tracing/package.json @@ -1,19 +1,19 @@ { - "name": "@langfuse/codex-observability-plugin", - "version": "0.4.2", + "name": "@donadiosolutions/codex-observability-plugin", + "version": "0.5.0-donadio.2", "description": "Langfuse observability plugin for the OpenAI Codex coding agent for tracing prompts, agent turns, model generations, and tool calls.", "license": "MIT", "author": "Langfuse", "type": "module", "repository": { "type": "git", - "url": "git+https://github.com/langfuse/codex-observability-plugin.git", + "url": "https://github.com/donadiosolutions/codex-observability-plugin.git", "directory": "plugins/tracing" }, "bugs": { - "url": "https://github.com/langfuse/codex-observability-plugin/issues" + "url": "https://github.com/donadiosolutions/codex-observability-plugin/issues" }, - "homepage": "https://github.com/langfuse/codex-observability-plugin#readme", + "homepage": "https://github.com/donadiosolutions/codex-observability-plugin#readme", "keywords": [ "codex", "codex-plugin", diff --git a/plugins/tracing/src/index.ts b/plugins/tracing/src/index.ts index 2d535d8..1d9e599 100644 --- a/plugins/tracing/src/index.ts +++ b/plugins/tracing/src/index.ts @@ -1,95 +1,215 @@ +import { randomUUID, createHash } from "node:crypto"; +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; import { getConfig } from "./config.js"; import { setupInstrumentation } from "./instrumentation.js"; import { readExternalParentSpanContext } from "./parent-context.js"; -import { markTurnUploaded } from "./sidecar.js"; -import { convertRollout } from "./trace.js"; +import { + acquireRolloutLock, + acknowledgeHooks, + enqueueHook, + loadObservationCheckpoint, + loadHookContext, + loadTurnCheckpoint, + markTurnUploaded, + pendingHooks, + saveObservationCheckpoint, +} from "./sidecar.js"; +import { + buildSubagentIndex, + convertRollout, + emitHookObservation, + resolveRootRollout, +} from "./trace.js"; import type { HookInput } from "./types.js"; import { debugLog, readStdin, setDebug } from "./utils.js"; let failOnError = process.env.LANGFUSE_CODEX_FAIL_ON_ERROR === "true"; -/** - * Entry point for the Codex `Stop` hook. - * - * Codex pipes a JSON payload to stdin after every turn. We resolve config, - * bail out unless tracing is explicitly enabled, then convert the rollout - * transcript into Langfuse traces. - * - * The hook fails open: any error is logged (in debug mode) and swallowed so a - * tracing problem never blocks the Codex session. Set - * `LANGFUSE_CODEX_FAIL_ON_ERROR=true` while testing if you want Codex to report - * hook failures instead. - */ +function spoolFor(sessionId: string): string { + return path.join( + process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex"), + "langfuse-hooks", + createHash("sha256").update(sessionId).digest("hex"), + ); +} + +async function importSessionSpool(spool: string, file: string, waitSeconds = 0): Promise { + if ((await pendingHooks(spool)).length === 0) return; + const release = await acquireRolloutLock(spool, waitSeconds); + if (!release) return; + try { + for (const event of await pendingHooks(spool)) { + await enqueueHook(file, event.input, event); + await acknowledgeHooks(spool, [event]); + } + } finally { + await release(); + } +} + +/** Every hook queues durably before a bounded, serialized incremental upload. */ export async function runHook(): Promise { let hookInput: HookInput; try { hookInput = await readStdin(); - } catch (error) { + } catch { return; } - const config = await getConfig(); setDebug(config.debug); failOnError = config.fail_on_error; + if (!config.enabled || !config.public_key || !config.secret_key) return; - if (!config.enabled) { - debugLog("tracing disabled (set TRACE_TO_LANGFUSE=true to enable)"); - return; - } - if (!config.public_key || !config.secret_key) { - debugLog("missing LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY; skipping"); - return; + // Queue before discovering rollouts: native Interrupt/SessionEnd have a 3s cap. + const started = Date.now(); + const shortHook = + hookInput.hook_event_name === "Interrupt" || hookInput.hook_event_name === "SessionEnd"; + if (hookInput.hook_event_name === "SubagentStop" && hookInput.agent_id) { + hookInput = { + ...hookInput, + session_id: hookInput.agent_id, + turn_id: hookInput.session_id === hookInput.agent_id ? hookInput.turn_id : undefined, + }; } + const sessionSpool = spoolFor(hookInput.session_id ?? "unknown"); + await fs.mkdir(path.dirname(sessionSpool), { recursive: true, mode: 0o700 }); + await enqueueHook(sessionSpool, hookInput, { + id: randomUUID(), + timestamp: started, + input: hookInput, + standalone: !hookInput.transcript_path, + }); if (!hookInput.transcript_path) { - debugLog("hook payload missing transcript_path; skipping"); + const release = await acquireRolloutLock( + sessionSpool, + shortHook ? Math.max(0, (2500 - Date.now() + started) / 1000) : 10, + ); + if (!release) return; + try { + const events = await pendingHooks(sessionSpool); + const instrumentation = setupInstrumentation(config, { + acknowledged: await loadObservationCheckpoint(sessionSpool), + }); + let failure: unknown; + try { + for (const event of events) emitHookObservation(event); + } catch (error) { + failure = error; + } + try { + await instrumentation.shutdown(); + } catch (error) { + failure ??= error; + } + await saveObservationCheckpoint(sessionSpool, instrumentation.acknowledged()); + if (failure) { + if (config.fail_on_error) throw failure; + debugLog("early hook remains retryable", failure); + return; + } + await acknowledgeHooks(sessionSpool, events); + } finally { + await release(); + } return; } - const parentSpanContext = readExternalParentSpanContext(process.env, config.fail_on_error); - if (parentSpanContext && config.trace_seed) { - debugLog("trace_seed ignored: an external parent trace context takes precedence"); - } - - const instrumentation = setupInstrumentation(config); - let exportedTurnIds: string[] = []; - let failure: unknown; - - try { - exportedTurnIds = await convertRollout(hookInput.transcript_path, { - config, - parentSpanContext, - stoppedTurnId: hookInput.turn_id ?? undefined, - }); - } catch (error) { - failure = error; - debugLog("failed to convert rollout:", error); - } - - try { - await instrumentation.shutdown(); - } catch (error) { - failure ??= error; - debugLog("error during flush/shutdown:", error); - } - - // Record delivery only after the flush: a turn marked despite a failed export - // is lost silently, while an unmarked one is retried. - if (failure) { - if (config.fail_on_error) throw failure; - debugLog("export incomplete; leaving turns unmarked so they stay retryable"); + const requestedFile = hookInput.agent_transcript_path ?? hookInput.transcript_path; + const resolved = await resolveRootRollout(requestedFile); + const file = resolved.file; + let index = resolved.index; + if (shortHook && Date.now() - started >= 2500) return; + const waitBudget = () => (shortHook ? Math.max(0, (2500 - Date.now() + started) / 1000) : 10); + await importSessionSpool(sessionSpool, file, waitBudget()); + const release = await acquireRolloutLock(file, waitBudget()); + if (!release) { + debugLog("uploader busy; hook remains in durable inbox"); return; } - for (const turnId of exportedTurnIds) { - await markTurnUploaded(hookInput.transcript_path, turnId); + try { + const parentSpanContext = readExternalParentSpanContext(process.env, config.fail_on_error); + // Bounded passes catch hooks queued during export without starting a daemon. + for (let pass = 0; pass < 4; pass++) { + if (shortHook && Date.now() - started >= 2500) return; + if (pass > 0) index = await buildSubagentIndex(file); + const rootThread = [...index.byThread.values()].find( + (rollout) => rollout.file === file, + )?.threadId; + const sessions = new Set([ + hookInput.session_id ?? "unknown", + ...(rootThread ? [rootThread] : []), + ]); + const parents = rootThread ? [rootThread] : []; + for (let cursor = 0; cursor < parents.length; cursor++) { + for (const child of index.byParent.get(parents[cursor]) ?? []) { + if (!sessions.has(child.threadId)) { + sessions.add(child.threadId); + parents.push(child.threadId); + } + } + } + for (const session of sessions) + await importSessionSpool(spoolFor(session), file, waitBudget()); + const events = await pendingHooks(file); + if (events.length === 0) break; + const contextualEvents = [...(await loadHookContext(file)), ...events]; + const instrumentation = setupInstrumentation(config, { + acknowledged: await loadObservationCheckpoint(file), + }); + const acknowledgedTurns = await loadTurnCheckpoint(file); + const pendingTurnFingerprints: Record = {}; + let exportedTurnIds: string[] = []; + let failure: unknown; + try { + exportedTurnIds = await convertRollout(file, { + config, + parentSpanContext, + subagentIndex: index, + incremental: true, + hookEvents: contextualEvents, + acknowledgedTurns, + pendingTurnFingerprints, + }); + } catch (error) { + failure = error; + debugLog("rollout conversion failed", error); + } + try { + await instrumentation.shutdown(); + } catch (error) { + failure ??= error; + } + const retainedByKey = new Map(); + for (const event of contextualEvents.filter((event) => event.contextNeeded)) { + const tool = event.input.tool_use_id ?? event.input.tool_call_id; + const key = `${event.input.session_id}:${event.input.turn_id}:${tool ? `tool:${tool}` : "final"}`; + retainedByKey.set(key, { ...event, replayOnly: true }); + } + const retained = [...retainedByKey.values()]; + // Successful prefix batches remain acknowledged even when a later batch fails. + await saveObservationCheckpoint( + file, + instrumentation.acknowledged(), + retained, + failure ? acknowledgedTurns : { ...acknowledgedTurns, ...pendingTurnFingerprints }, + ); + if (failure) { + if (config.fail_on_error) throw failure; + debugLog("export incomplete; durable hooks and observations remain retryable", failure); + return; + } + for (const turnId of exportedTurnIds) await markTurnUploaded(file, turnId); + await acknowledgeHooks(file, events); + } + } finally { + await release(); } } runHook().catch((error) => { - if (process.env.LANGFUSE_CODEX_DEBUG === "true") { - console.error("[langfuse-codex] fatal:", error); - } - if (failOnError) { - process.exitCode = 1; - } + if (process.env.LANGFUSE_CODEX_DEBUG === "true") console.error("[langfuse-codex] fatal:", error); + if (failOnError) process.exitCode = 1; }); diff --git a/plugins/tracing/src/instrumentation.ts b/plugins/tracing/src/instrumentation.ts index f7a3f05..fc62e00 100644 --- a/plugins/tracing/src/instrumentation.ts +++ b/plugins/tracing/src/instrumentation.ts @@ -2,6 +2,8 @@ import { createHash, randomBytes } from "node:crypto"; import { LangfuseSpanProcessor } from "@langfuse/otel"; import { setLangfuseTracerProvider } from "@langfuse/tracing"; +import { ExportResultCode, type ExportResult } from "@opentelemetry/core"; +import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer"; import { defaultResource, detectResources, @@ -9,11 +11,13 @@ import { resourceFromAttributes, } from "@opentelemetry/resources"; import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node"; +import type { ReadableSpan, SpanExporter, SpanProcessor } from "@opentelemetry/sdk-trace-base"; import type { Config } from "./config.js"; const TRACE_ID_HEX_CHARS = 32; const SPAN_ID_HEX_CHARS = 16; +const LEGACY_UPLOADED = "langfuse.observation.metadata.codex.legacy_uploaded"; let idSeed: string | undefined; let idCounter = 0; @@ -39,8 +43,242 @@ function seededId(kind: "trace" | "span"): string { export type Instrumentation = { /** Flush buffered spans and tear down the tracer provider. */ shutdown: () => Promise; + /** Only server-acknowledged contents are eligible for a durable checkpoint. */ + acknowledged: () => Record; + flush: () => Promise; }; +let activeFlush: (() => Promise) | undefined; +let activeBackpressure: (() => Promise) | undefined; + +/** Await at conversion boundaries to keep preparation and delivery bounded. */ +export async function flushInstrumentation(): Promise { + await activeFlush?.(); +} + +/** Wait for preparation, draining only full batches or an existing request. */ +export async function backpressureInstrumentation(): Promise { + await activeBackpressure?.(); +} + +type DeliveryOptions = { + acknowledged?: Readonly>; + maxBatchBytes?: number; + maxSingleSpanBytes?: number; + maxQueueSpans?: number; + maxQueueBytes?: number; + flushIntervalMillis?: number; +}; + +type PendingSpan = { span: ReadableSpan; key: string; fingerprint: string; bytes: number }; + +function spanKey(span: ReadableSpan): string { + const { traceId, spanId } = span.spanContext(); + return `${traceId}:${spanId}`; +} + +function serialize(spans: ReadableSpan[]): Uint8Array { + const encoded = JsonTraceSerializer.serializeRequest(spans); + if (!encoded) throw new Error("OTLP serialization failed"); + return encoded; +} + +/** + * The SDK prepares spans (including masking and media) using its public + * immediate exporter option. This exporter owns batching and acknowledgments: + * a queue admission is never mistaken for successful delivery at shutdown. + */ +export class BoundedSpanExporter implements SpanExporter { + private readonly queue: PendingSpan[] = []; + private readonly delivered: Record; + private readonly received = new Set(); + private readonly maxBatchBytes: number; + private readonly maxSingleSpanBytes: number; + private readonly maxQueueSpans: number; + private readonly maxQueueBytes: number; + private readonly flushIntervalMillis: number; + private queuedBytes = 0; + private inFlightCount = 0; + private timer?: NodeJS.Timeout; + private draining?: Promise; + private failure?: Error; + private closed = false; + private capacityFlush = false; + + constructor( + private readonly config: Config, + options: DeliveryOptions = {}, + ) { + this.delivered = { ...options.acknowledged }; + this.maxBatchBytes = options.maxBatchBytes ?? 8 * 1024 * 1024; + this.maxSingleSpanBytes = options.maxSingleSpanBytes ?? 256 * 1024 * 1024; + this.maxQueueSpans = options.maxQueueSpans ?? 2048; + this.maxQueueBytes = options.maxQueueBytes ?? 64 * 1024 * 1024; + this.flushIntervalMillis = options.flushIntervalMillis ?? 1000; + } + + acknowledged(): Record { + return { ...this.delivered }; + } + + receivedSpan(key: string): boolean { + return this.received.has(key); + } + + export(spans: ReadableSpan[], callback: (result: ExportResult) => void): void { + try { + if (this.closed) throw new Error("OTLP exporter is shut down"); + if (this.failure) throw this.failure; + for (const span of spans) { + const key = spanKey(span); + this.received.add(key); + const body = serialize([span]); + // Process/resource attributes may change between hook processes. Hash + // observation contents only; timestamps and IDs remain part of the hash. + const request = JSON.parse(Buffer.from(body).toString("utf8")); + const contents = request.resourceSpans.flatMap( + (resource: { scopeSpans: unknown[] }) => resource.scopeSpans, + ); + const fingerprint = createHash("sha256").update(JSON.stringify(contents)).digest("hex"); + if (this.delivered[key] === fingerprint) continue; + if (body.byteLength > this.maxSingleSpanBytes) { + throw new Error(`OTLP observation exceeds ${this.maxSingleSpanBytes} byte limit`); + } + const empty = this.queue.length === 0 && this.inFlightCount === 0; + if ( + this.queue.length + this.inFlightCount >= this.maxQueueSpans || + (!empty && this.queuedBytes + body.byteLength > this.maxQueueBytes) + ) { + throw new Error("OTLP delivery queue capacity exceeded; observations remain retryable"); + } + this.queue.push({ span, key, fingerprint, bytes: body.byteLength }); + this.queuedBytes += body.byteLength; + } + if (this.queue.length >= 16 || this.queuedBytes >= this.maxBatchBytes) { + void this.drain(); + } else if (this.queue.length > 0 && !this.timer && !this.draining) { + this.timer = setTimeout(() => { + this.timer = undefined; + void this.drain(); + }, this.flushIntervalMillis); + this.timer.unref(); + } + callback({ code: ExportResultCode.SUCCESS }); + } catch (error) { + this.fail(error); + callback({ code: ExportResultCode.FAILED, error: this.failure }); + } + } + + private fail(error: unknown): void { + this.failure ??= error instanceof Error ? error : new Error(String(error)); + } + + private drain(): Promise { + if (this.timer) { + clearTimeout(this.timer); + this.timer = undefined; + } + if (!this.draining) { + this.draining = this.sendQueued() + .catch((error) => this.fail(error)) + .finally(() => { + this.draining = undefined; + }); + } + return this.draining; + } + + private async sendQueued(): Promise { + while (this.queue.length > 0 && !this.failure) { + const batch: PendingSpan[] = [this.queue[0]]; + let body = serialize(batch.map((entry) => entry.span)); + while (batch.length < 16 && batch.length < this.queue.length) { + const candidate = [...batch, this.queue[batch.length]]; + const encoded = serialize(candidate.map((entry) => entry.span)); + if (encoded.byteLength > this.maxBatchBytes) break; + batch.push(this.queue[batch.length]); + body = encoded; + } + this.queue.splice(0, batch.length); + this.inFlightCount = batch.length; + try { + await this.send(body); + for (const entry of batch) this.delivered[entry.key] = entry.fingerprint; + } finally { + this.queuedBytes -= batch.reduce((total, entry) => total + entry.bytes, 0); + this.inFlightCount = 0; + } + } + } + + private async send(body: Uint8Array): Promise { + for (let attempt = 0; attempt < 2; attempt++) { + const response = await fetch( + `${this.config.base_url.replace(/\/$/, "")}/api/public/otel/v1/traces`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Basic ${Buffer.from(`${this.config.public_key}:${this.config.secret_key}`).toString("base64")}`, + "x-langfuse-public-key": this.config.public_key ?? "", + "x-langfuse-sdk-name": "codex-observability-plugin", + }, + body: Buffer.from(body), + signal: AbortSignal.timeout(5000), + }, + ); + // Release the response before retrying; every request and retry is bounded. + const text = await response.text(); + if (!response.ok) { + if (attempt === 0 && (response.status === 429 || response.status >= 500)) { + await new Promise((resolve) => setTimeout(resolve, 100)); + continue; + } + throw new Error(`OTLP export rejected with HTTP ${response.status}`); + } + const result: unknown = text.length === 0 ? {} : JSON.parse(text); + if (result === null || typeof result !== "object" || Array.isArray(result)) { + throw new Error("Invalid OTLP export acknowledgment"); + } + const partial = (result as { partialSuccess?: { rejectedSpans?: string | number } }) + .partialSuccess; + if (partial?.rejectedSpans !== undefined && BigInt(partial.rejectedSpans) !== 0n) { + throw new Error(`OTLP partial success rejected ${partial.rejectedSpans} observation(s)`); + } + return; + } + } + + async forceFlush(): Promise { + if (this.failure) throw this.failure; + if ( + this.capacityFlush && + !this.draining && + this.queuedBytes < this.maxBatchBytes && + this.queue.length < 16 + ) + return; + await this.drain(); + if (this.failure) throw this.failure; + } + + /** SDK forceFlush waits for preparation; avoid sending tiny batches each time. */ + async withBackpressure(prepare: () => Promise): Promise { + this.capacityFlush = true; + try { + await prepare(); + } finally { + this.capacityFlush = false; + } + } + + async shutdown(): Promise { + this.closed = true; + await this.forceFlush(); + } +} + const DEFAULT_SERVICE_NAME = "codex"; function buildResource() { @@ -57,24 +295,48 @@ function buildResource() { * instrumentation loading. Registering the provider also installs the * AsyncLocalStorage context manager that `propagateAttributes` relies on. * - * We use `exportMode: "batched"` and flush once at the end: the whole rollout - * is converted in-process, so batching every span into one (or a few) requests - * is far faster than one request per span — important for the hook's timeout - * budget. `shutdown()` below calls `forceFlush()` before the process exits. + * The SDK prepares observations in immediate mode; our acknowledged exporter + * batches the resulting spans by count, exact encoded size, and a short timer. + * Shutdown must succeed before callers persist observation checkpoints. */ -export function setupInstrumentation(config: Config): Instrumentation { +export function setupInstrumentation( + config: Config, + options: DeliveryOptions = {}, +): Instrumentation { + const exporter = new BoundedSpanExporter(config, options); + const ended = new Set(); const spanProcessor = new LangfuseSpanProcessor({ publicKey: config.public_key, secretKey: config.secret_key, baseUrl: config.base_url, environment: config.environment, - exportMode: "batched", - shouldExportSpan: () => true, + exportMode: "immediate", + exporter, + shouldExportSpan: ({ otelSpan }) => otelSpan.attributes[LEGACY_UPLOADED] !== "true", }); + // Langfuse logs and swallows asynchronous preparation failures. Count spans + // before preparation and demand that each reached the acknowledged exporter. + const checkedProcessor: SpanProcessor = { + onStart: (span, context) => spanProcessor.onStart(span, context), + onEnd: (span) => { + if (span.attributes[LEGACY_UPLOADED] !== "true") ended.add(spanKey(span)); + spanProcessor.onEnd(span); + }, + forceFlush: async () => { + await spanProcessor.forceFlush(); + await exporter.forceFlush(); + for (const key of ended) { + if (!exporter.receivedSpan(key)) + throw new Error("Langfuse observation preparation failed before export"); + } + }, + shutdown: () => spanProcessor.shutdown(), + }; + const provider = new NodeTracerProvider({ resource: buildResource(), - spanProcessors: [spanProcessor], + spanProcessors: [checkedProcessor], idGenerator: { generateTraceId: () => seededId("trace"), generateSpanId: () => seededId("span"), @@ -84,12 +346,24 @@ export function setupInstrumentation(config: Config): Instrumentation { // Bind explicitly: the global registry can refuse the registration silently. setLangfuseTracerProvider(provider); + activeFlush = () => checkedProcessor.forceFlush(); + activeBackpressure = () => exporter.withBackpressure(() => checkedProcessor.forceFlush()); return { + acknowledged: () => exporter.acknowledged(), + flush: () => checkedProcessor.forceFlush(), shutdown: async () => { - await spanProcessor.forceFlush(); - await provider.shutdown(); - setLangfuseTracerProvider(null); + try { + await checkedProcessor.forceFlush(); + } finally { + try { + await provider.shutdown(); + } finally { + setLangfuseTracerProvider(null); + activeFlush = undefined; + activeBackpressure = undefined; + } + } }, }; } diff --git a/plugins/tracing/src/sidecar.ts b/plugins/tracing/src/sidecar.ts index c525379..0618d85 100644 --- a/plugins/tracing/src/sidecar.ts +++ b/plugins/tracing/src/sidecar.ts @@ -22,3 +22,170 @@ export async function markTurnUploaded(rolloutFile: string, turnId: string): Pro // Best-effort: a failed write only risks a duplicate upload next time. } } + +import { randomUUID } from "node:crypto"; +import { spawn } from "node:child_process"; +import * as path from "node:path"; +import type { HookEvent, HookInput } from "./types.js"; + +/** A separate file keeps old newline turn checkpoints readable during upgrades. */ +export async function loadObservationCheckpoint( + rolloutFile: string, +): Promise> { + try { + const state = JSON.parse(await fs.readFile(`${rolloutFile}.langfuse-observations`, "utf8")); + if ( + state.version !== 1 || + typeof state.observations !== "object" || + state.observations === null + ) + throw new Error("Invalid observation checkpoint"); + return state.observations; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; + throw error; + } +} + +export async function saveObservationCheckpoint( + rolloutFile: string, + observations: Record, + hooks: HookEvent[] = [], + turns: Record = {}, +): Promise { + const temporary = `${rolloutFile}.langfuse-observations.${randomUUID()}`; + await fs.writeFile( + temporary, + JSON.stringify({ + version: 1, + observations, + hooks, + turns, + legacyTurnIds: [...(await loadLegacyTurnIds(rolloutFile))], + }), + { + mode: 0o600, + }, + ); + await fs.rename(temporary, `${rolloutFile}.langfuse-observations`); +} + +/** Durable inbox: a busy hook exits promptly; its owner drains this on its next pass. */ +export async function enqueueHook( + rolloutFile: string, + input: HookInput, + persisted?: HookEvent, +): Promise { + const dir = `${rolloutFile}.langfuse-pending`; + await fs.mkdir(dir, { recursive: true, mode: 0o700 }); + const event: HookEvent = persisted ?? { id: randomUUID(), timestamp: Date.now(), input }; + const temporary = path.join(dir, `${event.id}.tmp`); + await fs.writeFile(temporary, JSON.stringify(event), { mode: 0o600 }); + await fs.rename(temporary, path.join(dir, `${event.id}.json`)); +} + +export async function pendingHooks(rolloutFile: string): Promise { + const dir = `${rolloutFile}.langfuse-pending`; + try { + const names = (await fs.readdir(dir)).filter((name) => name.endsWith(".json")); + const events: HookEvent[] = []; + for (const name of names) + events.push(JSON.parse(await fs.readFile(path.join(dir, name), "utf8"))); + return events.sort((a, b) => a.timestamp - b.timestamp || a.id.localeCompare(b.id)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } +} + +export async function acknowledgeHooks(rolloutFile: string, events: HookEvent[]): Promise { + for (const event of events) + await fs.unlink(path.join(`${rolloutFile}.langfuse-pending`, `${event.id}.json`)); +} + +/** Linux kernel lock: one bounded helper, released on EOF or parent death. */ +export async function acquireRolloutLock( + rolloutFile: string, + waitSeconds = 0, +): Promise<(() => Promise) | undefined> { + const helper = spawn( + "flock", + [ + "--timeout", + Math.max(0, Math.min(10, waitSeconds)).toFixed(3), + "--", + `${rolloutFile}.langfuse-lock`, + process.execPath, + "-e", + ` + const timer = setTimeout(() => {try {process.kill(${process.pid},"SIGTERM");} catch {} process.exit(1);},35000); + process.stdin.resume(); + process.stdin.once("end",()=>{clearTimeout(timer);process.exit(0);}); + process.stdout.write("locked\\n"); + `, + ], + { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, LC_ALL: "C" } }, + ); + let spawnError: Error | undefined; + helper.once("error", (error) => { + spawnError = error; + }); + const closed = new Promise((resolve) => helper.once("close", () => resolve())); + const acquired = await new Promise((resolve) => { + const timeout = setTimeout( + () => { + helper.kill("SIGTERM"); + resolve(false); + }, + Math.max(0, Math.min(10, waitSeconds)) * 1000 + 1500, + ); + helper.stdout.once("data", () => { + clearTimeout(timeout); + resolve(true); + }); + helper.once("close", () => { + clearTimeout(timeout); + resolve(false); + }); + }); + if (!acquired) { + await closed; + if (spawnError) throw spawnError; + return undefined; + } + return async () => { + helper.stdin.end(); + await closed; + }; +} + +export async function loadHookContext(rolloutFile: string): Promise { + try { + const state = JSON.parse(await fs.readFile(`${rolloutFile}.langfuse-observations`, "utf8")); + return state.hooks ?? []; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } +} + +export async function loadLegacyTurnIds(rolloutFile: string): Promise> { + try { + const state = JSON.parse(await fs.readFile(`${rolloutFile}.langfuse-observations`, "utf8")); + return new Set(state.legacyTurnIds ?? []); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return loadUploadedTurnIds(rolloutFile); + throw error; + } +} + +export async function loadTurnCheckpoint(rolloutFile: string): Promise> { + try { + return ( + JSON.parse(await fs.readFile(`${rolloutFile}.langfuse-observations`, "utf8")).turns ?? {} + ); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; + throw error; + } +} diff --git a/plugins/tracing/src/trace.ts b/plugins/tracing/src/trace.ts index b67396a..f525f9d 100644 --- a/plugins/tracing/src/trace.ts +++ b/plugins/tracing/src/trace.ts @@ -1,6 +1,8 @@ +import { createHash } from "node:crypto"; import { createReadStream, type Dirent } from "node:fs"; import * as fs from "node:fs/promises"; import * as path from "node:path"; +import * as os from "node:os"; import { createInterface } from "node:readline"; import { @@ -14,12 +16,18 @@ import { import { TraceFlags, type SpanContext } from "@opentelemetry/api"; import type { Config } from "./config.js"; -import { currentIdSeed, seedIds } from "./instrumentation.js"; +import { + currentIdSeed, + seedIds, + flushInstrumentation, + backpressureInstrumentation, +} from "./instrumentation.js"; import { parseArgs, parseSession } from "./parse.js"; -import { loadUploadedTurnIds } from "./sidecar.js"; +import { loadUploadedTurnIds, loadLegacyTurnIds } from "./sidecar.js"; import { skillsForToolCall, traceTags } from "./skills.js"; import type { EventMsgPayload, + HookEvent, ModelStep, RolloutLine, SessionMeta, @@ -100,12 +108,14 @@ export async function buildSubagentIndex( rolloutFile: string, options: { includeEarlierDays?: boolean } = {}, ): Promise { - const root = path.resolve(path.dirname(rolloutFile), "../../.."); + const rolloutDirectory = path.dirname(rolloutFile); + const dated = /[\/]\d{4}[\/]\d{2}[\/]\d{2}$/.test(rolloutDirectory); + const root = dated ? path.resolve(rolloutDirectory, "../../..") : rolloutDirectory; const fromDay = path.relative(root, path.dirname(rolloutFile)); const bounded = !options.includeEarlierDays && /^\d{4}\/\d{2}\/\d{2}$/.test(fromDay); const index: SubagentIndex = { byParent: new Map(), byThread: new Map() }; - async function walk(dir: string, rel: string): Promise { + async function walk(dir: string, rel: string, recursive = true): Promise { if (bounded && rel && rel < fromDay.slice(0, rel.length)) return; let entries: Dirent[]; try { @@ -116,6 +126,7 @@ export async function buildSubagentIndex( for (const entry of entries) { const full = path.join(dir, entry.name); if (entry.isDirectory()) { + if (!recursive) continue; await walk(full, rel ? `${rel}/${entry.name}` : entry.name); continue; } @@ -139,7 +150,16 @@ export async function buildSubagentIndex( } } - await walk(root, ""); + await walk(root, "", dated); + const codexHome = path.resolve(process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex")); + if ( + path.dirname(path.resolve(root)) === codexHome && + (path.basename(root) === "sessions" || path.basename(root) === "archived_sessions") + ) { + if (path.basename(root) !== "sessions") await walk(path.join(codexHome, "sessions"), "", true); + if (path.basename(root) !== "archived_sessions") + await walk(path.join(codexHome, "archived_sessions"), "", false); + } return index; } @@ -435,9 +455,20 @@ async function emitTurn( unannouncedSubagents?: SubagentRollout[]; inheritableTurnIds?: ReadonlySet; historyPrefix?: ChatMlMessage[]; + incremental?: boolean; + hookEvents?: HookEvent[]; + final?: boolean; + emittedHookIds?: Set; + legacyIdMode?: boolean; + legacyCutoff?: number; + legacyUploaded?: boolean; + unchanged?: boolean; + acknowledgedTurns?: Readonly>; + pendingTurnFingerprints?: Record; }, ): Promise { const isSubagent = sessionMeta.isSubagentThread === true || ctx.parentObservation != null; + const skipPayloads = ctx.legacyUploaded || ctx.unchanged; const outerSeed = currentIdSeed(); seedIds(`${sessionMeta.sessionId}:${turn.turnId ?? "no-turn-id"}`); @@ -445,8 +476,8 @@ async function emitTurn( const root = startObservation( isSubagent ? "Codex Subagent Turn" : "Codex Turn", { - input: toMultimodalContent(turn.userInput, turn.userImages), - output: turn.finalOutput, + input: skipPayloads ? undefined : toMultimodalContent(turn.userInput, turn.userImages), + output: skipPayloads ? undefined : turn.finalOutput, level: turn.aborted ? "WARNING" : undefined, statusMessage: turn.aborted ? "Turn interrupted by user" : undefined, metadata: { @@ -457,6 +488,8 @@ async function emitTurn( "codex.model_provider": sessionMeta.modelProvider, "codex.cli_version": sessionMeta.cliVersion, "codex.aborted": turn.aborted, + ...(skipPayloads ? { "codex.legacy_uploaded": true } : {}), + ...(ctx.incremental ? { "codex.completed": ctx.final ?? turn.completed } : {}), "codex.tool_call_count": turn.steps.reduce((n, s) => n + s.toolCalls.length, 0), ...(ctx.attached && ctx.parentSpanContext ? { @@ -484,20 +517,47 @@ async function emitTurn( let failure: unknown; try { - const systemMessage = systemPromptText(turn.systemPrompt); + const systemMessage = skipPayloads ? undefined : systemPromptText(turn.systemPrompt); const historyPrefix = ctx.historyPrefix ?? []; const spawnObservations = new Map(); + let pending = 0; + let previousStepFingerprint = createHash("sha256") + .update( + JSON.stringify({ + historyPrefix, + systemPrompt: turn.systemPrompt, + tools: turn.toolDefinitions, + model: turn.model, + userInput: turn.userInput, + userImages: turn.userImages, + config: ctx.config, + parent: root.otelSpan.spanContext(), + }), + ) + .digest("hex"); for (let i = 0; i < turn.steps.length; i++) { const step = turn.steps[i]; + const stepFingerprintKey = `${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}:step:${i}`; + const stepFingerprint = createHash("sha256") + .update(previousStepFingerprint) + .update(JSON.stringify(step)) + .digest("hex"); + previousStepFingerprint = stepFingerprint; + const skipStep = + skipPayloads || ctx.acknowledgedTurns?.[stepFingerprintKey] === stepFingerprint; + if (ctx.incremental && !ctx.legacyIdMode) + seedIds(`${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}:step:${i}`); const generation = startObservation( isSubagent ? "LLM Subagent" : "LLM", { - input: attachToolDefinitions( - generationInput(systemMessage, historyPrefix, turn, i), - turn.toolDefinitions, - ), - output: buildGenerationOutput(step), + input: skipStep + ? undefined + : attachToolDefinitions( + generationInput(systemMessage, historyPrefix, turn, i), + turn.toolDefinitions, + ), + output: skipStep ? undefined : buildGenerationOutput(step), model: turn.model, ...(turn.reasoningEffort ? { modelParameters: { reasoning_effort: turn.reasoningEffort } } @@ -505,6 +565,7 @@ async function emitTurn( usageDetails: toUsageDetails(step.usage), metadata: { "codex.step_index": i, + ...(skipStep ? { "codex.legacy_uploaded": true } : {}), "codex.reasoning_effort": turn.reasoningEffort, }, }, @@ -516,11 +577,36 @@ async function emitTurn( ); for (const tc of step.toolCalls) { - const observation = emitToolCall(tc, root, step.endTime); + if (ctx.incremental && !ctx.legacyIdMode) + seedIds(`${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}:tool:${tc.callId}`); + const observation = emitToolCall(tc, root, step.endTime, ctx.incremental, skipPayloads); if (tc.name === "spawn_agent") spawnObservations.set(tc.callId, observation); + if (ctx.incremental && !skipStep) await backpressureInstrumentation(); + if (ctx.incremental && !skipStep && ++pending >= 16) { + await flushInstrumentation(); + pending = 0; + } } generation.end(new Date(generationEnd(step))); + if (ctx.pendingTurnFingerprints) + ctx.pendingTurnFingerprints[stepFingerprintKey] = stepFingerprint; + if (ctx.incremental && !skipStep && ++pending >= 16) { + await flushInstrumentation(); + pending = 0; + } + } + + for (const hook of ctx.hookEvents ?? []) { + if ( + !hook.replayOnly && + hook.input.session_id === sessionMeta.sessionId && + hook.input.turn_id === turn.turnId && + !ctx.emittedHookIds?.has(hook.id) + ) { + emitHookObservation(hook, root.otelSpan.spanContext()); + ctx.emittedHookIds?.add(hook.id); + } } const announced: SubagentRollout[] = []; @@ -542,6 +628,13 @@ async function emitTurn( subagentIndex: ctx.subagentIndex, seenThreadIds: ctx.seenThreadIds, ancestorTurnIds: ctx.inheritableTurnIds, + incremental: ctx.incremental, + hookEvents: ctx.hookEvents, + emittedHookIds: ctx.emittedHookIds, + legacyIdMode: ctx.legacyIdMode, + legacyCutoff: ctx.legacyCutoff, + acknowledgedTurns: ctx.acknowledgedTurns, + pendingTurnFingerprints: ctx.pendingTurnFingerprints, }); seedIds(seedBeforeChild); } @@ -558,22 +651,29 @@ async function emitTurn( root.end(new Date(turn.endTime)); seedIds(outerSeed); - if (failure && ctx.config.fail_on_error) throw failure; + if (failure && (ctx.incremental || ctx.config.fail_on_error)) throw failure; } function emitToolCall( tc: ToolCall, parent: LangfuseObservation, fallbackEnd: number, + incremental?: boolean, + legacyUploaded?: boolean, ): LangfuseObservation { const tool = startObservation( toolObservationName(tc), { - input: tc.args, - output: tc.output != null ? toText(tc.output) : undefined, + input: legacyUploaded ? undefined : tc.args, + output: legacyUploaded ? undefined : tc.output != null ? toText(tc.output) : undefined, level: tc.error ? "ERROR" : undefined, statusMessage: tc.error, - metadata: { "codex.call_id": tc.callId, "codex.tool_name": tc.name || "tool" }, + metadata: { + ...(legacyUploaded ? { "codex.legacy_uploaded": true } : {}), + "codex.call_id": tc.callId, + "codex.tool_name": tc.name || "tool", + ...(incremental ? { "codex.completed": tc.endTime != null } : {}), + }, }, { asType: "tool", @@ -639,11 +739,93 @@ export async function convertRollout( seenThreadIds?: Set; ancestorTurnIds?: ReadonlySet; stoppedTurnId?: string; + incremental?: boolean; + hookEvents?: HookEvent[]; + emittedHookIds?: Set; + legacyIdMode?: boolean; + legacyCutoff?: number; + legacyUploaded?: boolean; + unchanged?: boolean; + acknowledgedTurns?: Readonly>; + pendingTurnFingerprints?: Record; }, ): Promise { const { sessionMeta, turns } = parseSession(await loadSession(rolloutFile)); + const emittedHookIds = options.emittedHookIds ?? new Set(); + const legacyTurnIds = options.incremental + ? await loadLegacyTurnIds(rolloutFile) + : new Set(); + const hooks = (options.hookEvents ?? []).filter( + (hook) => hook.input.session_id === sessionMeta.sessionId, + ); + for (const hook of hooks) { + hook.contextNeeded = false; + const turn = hook.input.turn_id + ? turns.find((t) => t.turnId === hook.input.turn_id) + : turns.filter((candidate) => candidate.startTime <= hook.timestamp).at(-1); + if (!turn) { + hook.contextNeeded = [ + "PostToolUse", + "Stop", + "SubagentStop", + "Interrupt", + "SessionEnd", + ].includes(hook.input.hook_event_name ?? ""); + continue; + } + hook.input.turn_id ??= turn.turnId; + if ( + hook.input.hook_event_name === "Stop" || + hook.input.hook_event_name === "Interrupt" || + hook.input.hook_event_name === "SessionEnd" || + (hook.input.hook_event_name === "SubagentStop" && + (sessionMeta.isSubagentThread || options.parentObservation != null)) + ) { + hook.contextNeeded = !turn.completed; + if (!turn.completed) turn.endTime = Math.max(turn.endTime, hook.timestamp); + turn.completed = true; + turn.aborted ||= hook.input.hook_event_name === "Interrupt"; + if ( + typeof hook.input.last_assistant_message === "string" && + turn.finalOutput !== hook.input.last_assistant_message + ) { + turn.finalOutput = hook.input.last_assistant_message; + hook.contextNeeded = true; + } + } + // Native hooks run before the rollout writer necessarily flushes tool outputs. + const toolId = hook.input.tool_use_id ?? hook.input.tool_call_id; + if (hook.input.hook_event_name === "PostToolUse" && toolId) { + const tool = turn.steps.flatMap((step) => step.toolCalls).find((tc) => tc.callId === toolId); + if (!tool) hook.contextNeeded = true; + if (tool && tool.output == null && hook.input.tool_response !== undefined) { + hook.contextNeeded = true; + tool.output = hook.input.tool_response; + tool.endTime = hook.timestamp; + turn.endTime = Math.max(turn.endTime, hook.timestamp); + } + } + } const historyPrefixes: ChatMlMessage[][] = []; + const turnFingerprints = turns.map((turn) => + createHash("sha256") + .update( + JSON.stringify({ + turn, + config: options.config, + parent: options.parentObservation?.otelSpan.spanContext() ?? options.parentSpanContext, + }), + ) + .digest("hex"), + ); + for (let i = 0; i < turns.length; i++) { + // Include earlier conversation changes without rebuilding every generation input. + if (i > 0) + turnFingerprints[i] = createHash("sha256") + .update(`${turnFingerprints[i - 1]}:${turnFingerprints[i]}`) + .digest("hex"); + } { const seen: ChatMlMessage[] = []; for (const turn of turns) { @@ -708,16 +890,30 @@ export async function convertRollout( for (let turnIndex = 0; turnIndex < turns.length; turnIndex++) { const turn = turns[turnIndex]; if (skipInherited(turn, turnIndex)) continue; + const fingerprintKey = `${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}`; await emitTurn(turn, sessionMeta, { config: options.config, rolloutFile, + unchanged: options.acknowledgedTurns?.[fingerprintKey] === turnFingerprints[turnIndex], + acknowledgedTurns: options.acknowledgedTurns, + pendingTurnFingerprints: options.pendingTurnFingerprints, parentObservation: options.parentObservation, subagentIndex, seenThreadIds, unannouncedSubagents: subagentsFor(turnIndex), inheritableTurnIds, historyPrefix: historyPrefixes[turnIndex], + incremental: options.incremental, + hookEvents: options.hookEvents, + emittedHookIds, + legacyIdMode: options.legacyIdMode, + legacyCutoff: options.legacyCutoff, + legacyUploaded: + options.legacyIdMode && turn.completed && turn.endTime <= (options.legacyCutoff ?? 0), + final: isFinal(turn, options.stoppedTurnId, turnIndex < turns.length - 1), }); + if (options.pendingTurnFingerprints) + options.pendingTurnFingerprints[fingerprintKey] = turnFingerprints[turnIndex]; } return []; } @@ -731,11 +927,12 @@ export async function convertRollout( if (skipInherited(turn, turnIndex)) continue; - if (!isFinal(turn, options.stoppedTurnId, turnIndex < turns.length - 1)) { + const final = isFinal(turn, options.stoppedTurnId, turnIndex < turns.length - 1); + if (!options.incremental && !final) { debugLog(`skipping turn ${turn.turnId ?? "(no turn id)"}: not final`); continue; } - if (uploaded.has(turn.turnId)) { + if (!options.incremental && turn.turnId && uploaded.has(turn.turnId)) { continue; } @@ -743,10 +940,14 @@ export async function convertRollout( options.parentSpanContext ?? (await seededTraceParent(options.config, sessionMeta, turnIndex + 1)); + const fingerprintKey = `${sessionMeta.sessionId}:${turn.turnId ?? turn.startTime}`; const emit = () => emitTurn(turn, sessionMeta, { config: options.config, rolloutFile, + unchanged: options.acknowledgedTurns?.[fingerprintKey] === turnFingerprints[turnIndex], + acknowledgedTurns: options.acknowledgedTurns, + pendingTurnFingerprints: options.pendingTurnFingerprints, parentSpanContext, attached, subagentIndex, @@ -754,6 +955,13 @@ export async function convertRollout( unannouncedSubagents: subagentsFor(turnIndex), inheritableTurnIds, historyPrefix: historyPrefixes[turnIndex], + incremental: options.incremental, + hookEvents: options.hookEvents, + emittedHookIds, + legacyIdMode: legacyTurnIds.has(turn.turnId ?? ""), + legacyCutoff: legacyTurnIds.has(turn.turnId ?? "") ? turn.endTime : undefined, + legacyUploaded: legacyTurnIds.has(turn.turnId ?? ""), + final: isFinal(turn, options.stoppedTurnId, turnIndex < turns.length - 1), }); if (attached) { @@ -772,9 +980,78 @@ export async function convertRollout( ); } - uploaded.add(turn.turnId); - exportedTurnIds.push(turn.turnId); + if (options.pendingTurnFingerprints) + options.pendingTurnFingerprints[fingerprintKey] = turnFingerprints[turnIndex]; + if (final && turn.turnId && !uploaded.has(turn.turnId)) { + uploaded.add(turn.turnId); + exportedTurnIds.push(turn.turnId); + } } + if (options.incremental && !options.parentObservation) { + for (const hook of options.hookEvents ?? []) { + if (!hook.replayOnly && !emittedHookIds.has(hook.id)) { + emitHookObservation(hook); + emittedHookIds.add(hook.id); + } + } + } return exportedTurnIds; } + +export function emitHookObservation(hook: HookEvent, parentSpanContext?: SpanContext): void { + const previous = currentIdSeed(); + seedIds(`hook:${hook.id}`); + const emit = () => + startObservation( + `Codex Hook: ${hook.input.hook_event_name ?? "Unknown"}`, + { + input: hook.input, + metadata: { + "codex.hook_event_name": hook.input.hook_event_name, + "codex.thread_id": hook.input.session_id, + "codex.turn_id": hook.input.turn_id, + }, + }, + { + asType: "span", + startTime: new Date(hook.timestamp), + parentSpanContext: hook.standalone ? undefined : parentSpanContext, + }, + ); + const observation = emit(); + observation.otelSpan.setAttribute(LangfuseOtelSpanAttributes.OBSERVATION_TYPE, "event"); + if (hook.input.session_id && (hook.standalone || !parentSpanContext)) { + observation.otelSpan.setAttribute( + LangfuseOtelSpanAttributes.TRACE_SESSION_ID, + hook.input.session_id, + ); + observation.otelSpan.setAttribute( + LangfuseOtelSpanAttributes.TRACE_COMPAT_SESSION_ID, + hook.input.session_id, + ); + } + observation.end(new Date(hook.timestamp)); + seedIds(previous); +} + +/** Child hooks use the same root checkpoint and parenting as parent hooks. */ +export async function resolveRootRollout( + rolloutFile: string, +): Promise<{ file: string; index: SubagentIndex }> { + const meta = await readSessionMeta(rolloutFile); + const index = await buildSubagentIndex(rolloutFile, { + includeEarlierDays: !!meta?.parentThreadId, + }); + let file = rolloutFile; + let parent = meta?.parentThreadId; + const seen = new Set(); + while (parent && !seen.has(parent)) { + seen.add(parent); + const ancestor = index.byThread.get(parent); + if (!ancestor) break; + file = ancestor.file; + parent = ancestor.parentThreadId; + } + return { file, index }; +} diff --git a/plugins/tracing/src/types.ts b/plugins/tracing/src/types.ts index 298bcc8..8a48538 100644 --- a/plugins/tracing/src/types.ts +++ b/plugins/tracing/src/types.ts @@ -163,6 +163,15 @@ export type HookInput = { turn_id?: string | null; transcript_path?: string | null; hook_event_name?: string; + agent_transcript_path?: string | null; + agent_id?: string; + tool_use_id?: string; + tool_call_id?: string; + last_assistant_message?: string | null; + tool_name?: string; + tool_input?: unknown; + tool_response?: unknown; + [key: string]: unknown; }; export type SessionMeta = { @@ -227,3 +236,13 @@ export type Turn = { userImages: string[]; toolDefinitions: ToolDefinition[]; }; + +/** Persisted before dispatch so retries keep their observation identity. */ +export type HookEvent = { + id: string; + timestamp: number; + input: HookInput; + standalone?: boolean; + replayOnly?: boolean; + contextNeeded?: boolean; +}; diff --git a/plugins/tracing/test/delivery.test.ts b/plugins/tracing/test/delivery.test.ts new file mode 100644 index 0000000..800fbef --- /dev/null +++ b/plugins/tracing/test/delivery.test.ts @@ -0,0 +1,321 @@ +import * as http from "node:http"; + +import { getLangfuseTracerProvider } from "@langfuse/tracing"; +import { ExportResultCode } from "@opentelemetry/core"; +import { resourceFromAttributes } from "@opentelemetry/resources"; +import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node"; +import type { ReadableSpan } from "@opentelemetry/sdk-trace-base"; +import { afterEach, describe, expect, it } from "vitest"; + +import { emitHookObservation } from "../src/trace.js"; +import type { Config } from "../src/config.js"; +import { + backpressureInstrumentation, + BoundedSpanExporter, + setupInstrumentation, +} from "../src/instrumentation.js"; + +const config: Config = { + enabled: true, + public_key: "pk-test", + secret_key: "sk-test", + base_url: "http://127.0.0.1", + skill_tags: true, + debug: false, + fail_on_error: false, +}; +const servers: http.Server[] = []; +const providers: NodeTracerProvider[] = []; +const exporters: BoundedSpanExporter[] = []; + +async function endpoint( + respond: (request: number, body: Buffer, res: http.ServerResponse) => void, +) { + let requests = 0; + const server = http.createServer(async (req, res) => { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(Buffer.from(chunk)); + respond(++requests, Buffer.concat(chunks), res); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as { port: number }; + return { ...config, base_url: `http://127.0.0.1:${address.port}` }; +} + +function spans(count: number, payload = "x"): ReadableSpan[] { + const captured: ReadableSpan[] = []; + const provider = new NodeTracerProvider({ + resource: resourceFromAttributes({ "service.name": "test" }), + spanProcessors: [ + { + onStart() {}, + onEnd(span) { + captured.push(span); + }, + async forceFlush() {}, + async shutdown() {}, + }, + ], + }); + providers.push(provider); + const tracer = provider.getTracer("test"); + for (let i = 0; i < count; i++) tracer.startSpan(`span-${i}`, { attributes: { payload } }).end(); + return captured; +} + +function enqueue(exporter: BoundedSpanExporter, span: ReadableSpan) { + exporter.export([span], (result) => expect(result.code).toBe(ExportResultCode.SUCCESS)); +} + +function spanCount(body: Buffer): number { + const request = JSON.parse(body.toString()); + return request.resourceSpans.reduce( + (n: number, resource: { scopeSpans: { spans: unknown[] }[] }) => + n + resource.scopeSpans.reduce((m, scope) => m + scope.spans.length, 0), + 0, + ); +} + +afterEach(async () => { + for (const exporter of exporters.splice(0)) await exporter.shutdown().catch(() => {}); + for (const provider of providers.splice(0)) await provider.shutdown(); + await Promise.all( + servers + .splice(0) + .map((server) => new Promise((resolve) => server.close(() => resolve()))), + ); +}); + +describe("bounded acknowledged delivery", () => { + it("does not report success when an automatic batch was rejected with HTTP 413", async () => { + let accepted = 0; + const cfg = await endpoint((request, body, res) => { + if (request === 1) { + res.writeHead(413); + res.end(); + return; + } + accepted += spanCount(body); + res.end("{}"); + }); + const instrumentation = setupInstrumentation(cfg); + const tracer = getLangfuseTracerProvider().getTracer("delivery-test"); + for (let i = 0; i < 600; i++) tracer.startSpan(`span-${i}`).end(); + await expect(instrumentation.shutdown()).rejects.toThrow("413"); + expect(accepted).toBeLessThan(600); + }); + + it("delivers all 600 observations in sequential batches of at most 16", async () => { + const sizes: number[] = []; + let active = 0; + let maximumActive = 0; + const cfg = await endpoint((_request, body, res) => { + active++; + maximumActive = Math.max(active, maximumActive); + sizes.push(spanCount(body)); + setTimeout(() => { + active--; + res.end("{}"); + }, 1); + }); + const exporter = new BoundedSpanExporter(cfg); + exporters.push(exporter); + for (const span of spans(600)) enqueue(exporter, span); + await exporter.forceFlush(); + expect(sizes.reduce((a, b) => a + b, 0)).toBe(600); + expect(Math.max(...sizes)).toBeLessThanOrEqual(16); + expect(maximumActive).toBe(1); + expect(Object.keys(exporter.acknowledged())).toHaveLength(600); + }); + + it("batches by actual JSON bytes including escaping and the OTLP envelope", async () => { + const bytes: number[] = []; + const cfg = await endpoint((_request, body, res) => { + bytes.push(body.length); + res.end("{}"); + }); + const exporter = new BoundedSpanExporter(cfg, { maxBatchBytes: 3000 }); + exporters.push(exporter); + for (const span of spans(8, '\\"'.repeat(150))) enqueue(exporter, span); + await exporter.forceFlush(); + expect(bytes.length).toBeGreaterThan(1); + expect(Math.max(...bytes)).toBeLessThanOrEqual(3000); + expect(Object.keys(exporter.acknowledged())).toHaveLength(8); + }); + + it("permits an untruncated singleton larger than the regular batch target", async () => { + let received: Buffer | undefined; + const cfg = await endpoint((_request, body, res) => { + received = body; + res.end("{}"); + }); + const exporter = new BoundedSpanExporter(cfg, { + maxBatchBytes: 1024, + maxSingleSpanBytes: 8192, + }); + exporters.push(exporter); + enqueue(exporter, spans(1, "x".repeat(2048))[0]); + await exporter.forceFlush(); + expect(received!.length).toBeGreaterThan(1024); + expect(received!.toString()).toContain("x".repeat(2048)); + }); + + it("rejects shutdown after queue overflow without acknowledging lost observations", async () => { + const cfg = await endpoint((_request, _body, res) => res.end("{}")); + const exporter = new BoundedSpanExporter(cfg, { maxQueueSpans: 2 }); + exporters.push(exporter); + for (const span of spans(3)) exporter.export([span], () => {}); + await expect(exporter.shutdown()).rejects.toThrow("queue"); + expect(Object.keys(exporter.acknowledged())).toHaveLength(0); + }); + + it("rejects OTLP partial success and malformed successful responses", async () => { + for (const response of ['{"partialSuccess":{"rejectedSpans":"1"}}', "not-json"]) { + const cfg = await endpoint((_request, _body, res) => res.end(response)); + const exporter = new BoundedSpanExporter(cfg); + exporters.push(exporter); + enqueue(exporter, spans(1)[0]); + await expect(exporter.shutdown()).rejects.toThrow(); + expect(Object.keys(exporter.acknowledged())).toHaveLength(0); + } + }); + + it("flushes a small batch on the interval without waiting for shutdown", async () => { + let received = 0; + const cfg = await endpoint((_request, body, res) => { + received += spanCount(body); + res.end("{}"); + }); + const exporter = new BoundedSpanExporter(cfg, { flushIntervalMillis: 20 }); + exporters.push(exporter); + enqueue(exporter, spans(1)[0]); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(received).toBe(1); + }); + + it("skips acknowledged observations but uploads changed content using the same ID", async () => { + let received = 0; + const cfg = await endpoint((_request, body, res) => { + received += spanCount(body); + res.end("{}"); + }); + const [span] = spans(1); + const first = new BoundedSpanExporter(cfg); + exporters.push(first); + enqueue(first, span); + await first.shutdown(); + const second = new BoundedSpanExporter(cfg, { acknowledged: first.acknowledged() }); + exporters.push(second); + enqueue(second, span); + await second.forceFlush(); + expect(received).toBe(1); + const movedProcess = Object.create(span) as ReadableSpan; + Object.defineProperty(movedProcess, "resource", { + value: resourceFromAttributes({ ...span.resource.attributes, "process.pid": 12345 }), + }); + enqueue(second, movedProcess); + await second.forceFlush(); + expect(received).toBe(1); + const changed = Object.create(span) as ReadableSpan; + Object.defineProperty(changed, "attributes", { value: { payload: "changed" } }); + enqueue(second, changed); + await second.shutdown(); + expect(received).toBe(2); + }); + + it("applies backpressure across a backlog larger than the bounded queue", async () => { + const counts: number[] = []; + const cfg = await endpoint((_request, body, res) => { + counts.push(spanCount(body)); + res.end("{}"); + }); + const instrumentation = setupInstrumentation(cfg, { maxQueueSpans: 32 }); + const tracer = getLangfuseTracerProvider().getTracer("test"); + for (let i = 0; i < 100; i++) { + tracer.startSpan(`span-${i}`).end(); + await backpressureInstrumentation(); + } + await instrumentation.shutdown(); + expect(counts.reduce((a, b) => a + b, 0)).toBe(100); + expect(Math.max(...counts)).toBeLessThanOrEqual(16); + expect(counts.length).toBeLessThan(10); + }); + + it("rejects observations above the singleton limit without sending or acknowledging them", async () => { + let received = 0; + const cfg = await endpoint((_request, _body, res) => { + received++; + res.end("{}"); + }); + const exporter = new BoundedSpanExporter(cfg, { maxSingleSpanBytes: 1024 }); + exporters.push(exporter); + exporter.export(spans(1, "x".repeat(2048)), () => {}); + await expect(exporter.shutdown()).rejects.toThrow("byte limit"); + expect(received).toBe(0); + expect(exporter.acknowledged()).toEqual({}); + }); + + it("retries a transient server rejection once and preserves final failures", async () => { + let requests = 0; + const cfg = await endpoint((_request, _body, res) => { + requests++; + res.writeHead(503); + res.end(); + }); + const exporter = new BoundedSpanExporter(cfg); + exporters.push(exporter); + enqueue(exporter, spans(1)[0]); + await expect(exporter.shutdown()).rejects.toThrow("503"); + expect(requests).toBe(2); + expect(exporter.acknowledged()).toEqual({}); + }); + + it("suppresses explicitly acknowledged legacy spans without treating them as lost preparation", async () => { + let received = 0; + const cfg = await endpoint((_request, body, res) => { + received += spanCount(body); + res.end("{}"); + }); + const instrumentation = setupInstrumentation(cfg); + const tracer = getLangfuseTracerProvider().getTracer("test"); + tracer + .startSpan("legacy", { + attributes: { "langfuse.observation.metadata.codex.legacy_uploaded": "true" }, + }) + .end(); + tracer.startSpan("new").end(); + await instrumentation.shutdown(); + expect(received).toBe(1); + expect(Object.keys(instrumentation.acknowledged())).toHaveLength(1); + }); +}); + +it("exports both session attributes for an auto-ended standalone SessionStart event", async () => { + const attributes: Array<{ key: string; value: { stringValue?: string } }> = []; + const cfg = await endpoint((_request, body, res) => { + const data = JSON.parse(body.toString()) as { + resourceSpans: Array<{ + scopeSpans: Array<{ spans: Array<{ attributes: typeof attributes }> }>; + }>; + }; + for (const resource of data.resourceSpans) + for (const scope of resource.scopeSpans) + for (const span of scope.spans) attributes.push(...span.attributes); + res.end("{}"); + }); + const instrumentation = setupInstrumentation(cfg); + emitHookObservation({ + id: "standalone-session-start", + timestamp: Date.UTC(2026, 5, 3, 12, 0, 0), + standalone: true, + input: { hook_event_name: "SessionStart", session_id: "new-session" }, + }); + await instrumentation.shutdown(); + expect(attributes.find((attribute) => attribute.key === "session.id")?.value.stringValue).toBe( + "new-session", + ); + expect( + attributes.find((attribute) => attribute.key === "langfuse.session.id")?.value.stringValue, + ).toBe("new-session"); +}); diff --git a/plugins/tracing/test/hook-command.test.ts b/plugins/tracing/test/hook-command.test.ts index 221b7e3..a994694 100644 --- a/plugins/tracing/test/hook-command.test.ts +++ b/plugins/tracing/test/hook-command.test.ts @@ -6,6 +6,7 @@ import * as path from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, it } from "vitest"; +import { acquireRolloutLock } from "../src/sidecar.js"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); const hookConfigFile = path.join(repoRoot, "plugins/tracing/hooks/hooks.json"); @@ -67,6 +68,15 @@ afterEach(() => { }); describe("bundled Stop hook command", () => { + it("flushes terminal hooks synchronously before native shutdown cancels async work", () => { + const { hooks } = JSON.parse(fs.readFileSync(hookConfigFile, "utf8")); + const terminal = new Set(["Stop", "SubagentStop", "Interrupt", "SessionEnd"]); + expect(Object.keys(hooks)).toHaveLength(12); + for (const [name, groups] of Object.entries(hooks)) { + const handler = (groups as Array<{ hooks: Array<{ async: boolean }> }>)[0].hooks[0]; + expect(handler.async, name).toBe(!terminal.has(name)); + } + }); it("runs from an arbitrary session cwd via PLUGIN_ROOT instead of a relative repo path", async () => { const codexHome = makeTempDir("lf-codex-home-"); const sessionCwd = makeTempDir("lf-codex-cwd-"); @@ -163,7 +173,7 @@ describe("bundled Stop hook command", () => { } }); - it("re-exports a rollout as a byte-identical payload so Langfuse deduplicates it", async () => { + it("exports only a fresh hook event when observations are unchanged", async () => { const codexHome = makeTempDir("lf-codex-home-"); const sessionCwd = makeTempDir("lf-codex-cwd-"); const sessionsDir = path.join(sessionCwd, "sessions", "2026", "06", "03"); @@ -202,7 +212,6 @@ describe("bundled Stop hook command", () => { try { for (let attempt = 0; attempt < 2; attempt++) { runs.push([]); - fs.rmSync(`${rollout}.langfuse`, { force: true }); const { code } = await runShellCommand(readHookCommand(), { cwd: sessionCwd, env: { @@ -226,7 +235,24 @@ describe("bundled Stop hook command", () => { } expect(runs[0].length).toBeGreaterThan(0); - expect(Buffer.concat(runs[1]).equals(Buffer.concat(runs[0]))).toBe(true); + const spansIn = (requests: Buffer[]) => + requests.flatMap((request) => { + const body = JSON.parse(request.toString("utf8")) as { + resourceSpans: Array<{ + scopeSpans: Array<{ spans: Array<{ name: string; spanId: string }> }>; + }>; + }; + return body.resourceSpans.flatMap((resource) => + resource.scopeSpans.flatMap((scope) => scope.spans), + ); + }); + const first = spansIn(runs[0]); + const second = spansIn(runs[1]); + expect(first.some((span) => span.name === "Codex Turn")).toBe(true); + expect(second.map((span) => span.name)).toEqual(["Codex Hook: Stop"]); + expect(second[0].spanId).not.toBe( + first.find((span) => span.name === "Codex Hook: Stop")!.spanId, + ); } finally { await new Promise((resolve) => server.close(() => resolve())); } @@ -236,3 +262,249 @@ describe("bundled Stop hook command", () => { expect(readHookCommand().replaceAll("${PLUGIN_ROOT}", "")).not.toContain("$"); }); }); + +it("retries a failed SessionStart event after the rollout becomes available", async () => { + const codexHome = makeTempDir("lf-codex-early-home-"); + const sessionCwd = makeTempDir("lf-codex-early-cwd-"); + const day = path.join(sessionCwd, "sessions/2026/06/03"); + fs.mkdirSync(day, { recursive: true }); + const file = path.join(day, "rollout.jsonl"); + const line = (type: string, payload: unknown) => + JSON.stringify({ timestamp: "2026-06-03T12:00:00.000Z", type, payload }); + fs.writeFileSync( + file, + [ + line("session_meta", { id: "early-session" }), + line("event_msg", { type: "task_started", turn_id: "early-turn" }), + line("event_msg", { type: "user_message", message: "work" }), + ].join("\n") + "\n", + ); + let accepting = false; + const delivered: string[] = []; + const server = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + if (accepting) delivered.push(Buffer.concat(chunks).toString("utf8")); + res.writeHead(accepting ? 200 : 503, { "content-type": "application/json" }); + res.end("{}"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + const env = { + ...process.env, + PLUGIN_ROOT: pluginRootDir, + CODEX_HOME: codexHome, + HOME: codexHome, + TRACE_TO_LANGFUSE: "true", + LANGFUSE_PUBLIC_KEY: "pk-lf-test", + LANGFUSE_SECRET_KEY: "sk-lf-test", + LANGFUSE_BASE_URL: `http://127.0.0.1:${port}`, + LANGFUSE_CODEX_FAIL_ON_ERROR: "true", + }; + try { + const failed = await runShellCommand(readHookCommand(), { + cwd: sessionCwd, + env, + input: JSON.stringify({ hook_event_name: "SessionStart", session_id: "early-session" }), + }); + expect(failed.code).toBe(1); + const spoolRoot = path.join(codexHome, "langfuse-hooks"); + const pending = fs.readdirSync(spoolRoot).find((name) => name.endsWith(".langfuse-pending"))!; + expect(fs.readdirSync(path.join(spoolRoot, pending))).toHaveLength(1); + accepting = true; + const recovered = await runShellCommand(readHookCommand(), { + cwd: sessionCwd, + env, + input: JSON.stringify({ + hook_event_name: "PostToolUse", + session_id: "early-session", + turn_id: "early-turn", + transcript_path: file, + }), + }); + expect(recovered.code).toBe(0); + expect(delivered.join("")).toContain("Codex Hook: SessionStart"); + expect(delivered.join("")).toContain("Codex Hook: PostToolUse"); + expect(fs.readdirSync(path.join(spoolRoot, pending))).toHaveLength(0); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +it.each(["native", "legacy"])( + "finalizes the child for %s SubagentStop payloads without finalizing its parent", + async (shape) => { + const codexHome = makeTempDir("lf-codex-child-home-"); + const cwd = makeTempDir("lf-codex-child-cwd-"); + const day = path.join(cwd, "sessions/2026/06/03"); + fs.mkdirSync(day, { recursive: true }); + const parentFile = path.join(day, "rollout-parent.jsonl"); + const childFile = path.join(day, "rollout-child.jsonl"); + const line = (second: number, type: string, payload: unknown) => + JSON.stringify({ + timestamp: new Date(Date.UTC(2026, 5, 3, 12, 0, second)).toISOString(), + type, + payload, + }); + fs.writeFileSync( + parentFile, + [ + line(0, "session_meta", { id: "native-parent" }), + line(1, "event_msg", { type: "task_started", turn_id: "parent-turn" }), + line(2, "event_msg", { type: "user_message", message: "delegate" }), + ].join("\n") + "\n", + ); + fs.writeFileSync( + childFile, + [ + line(3, "session_meta", { id: "native-child", parent_thread_id: "native-parent" }), + line(4, "event_msg", { type: "task_started", turn_id: "child-turn" }), + line(5, "event_msg", { type: "agent_message", message: "child done" }), + ].join("\n") + "\n", + ); + if (shape === "native") { + fs.appendFileSync( + childFile, + [ + line(6, "event_msg", { type: "task_started", turn_id: "child-next-turn" }), + line(7, "event_msg", { + type: "user_message", + message: "child resumed before delayed hook dispatch", + }), + ].join("\n") + "\n", + ); + } + type Span = { + name: string; + spanId: string; + parentSpanId?: string; + attributes: Array<{ key: string; value: { stringValue?: string } }>; + }; + const received: Span[] = []; + const server = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { + resourceSpans: Array<{ scopeSpans: Array<{ spans: Span[] }> }>; + }; + received.push( + ...body.resourceSpans.flatMap((resource) => + resource.scopeSpans.flatMap((scope) => scope.spans), + ), + ); + res.writeHead(200, { "content-type": "application/json" }); + res.end("{}"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + try { + const result = await runShellCommand(readHookCommand(), { + cwd, + env: { + ...process.env, + PLUGIN_ROOT: pluginRootDir, + CODEX_HOME: codexHome, + HOME: codexHome, + TRACE_TO_LANGFUSE: "true", + LANGFUSE_PUBLIC_KEY: "pk-lf-test", + LANGFUSE_SECRET_KEY: "sk-lf-test", + LANGFUSE_BASE_URL: `http://127.0.0.1:${port}`, + LANGFUSE_CODEX_FAIL_ON_ERROR: "true", + }, + input: JSON.stringify({ + hook_event_name: "SubagentStop", + session_id: shape === "native" ? "native-child" : "native-parent", + turn_id: shape === "native" ? "child-turn" : "parent-turn", + transcript_path: parentFile, + agent_id: "native-child", + agent_transcript_path: childFile, + }), + }); + expect(result.code).toBe(0); + const parent = received.find((span) => span.name === "Codex Turn")!; + const child = received.find((span) => span.name === "Codex Subagent Turn")!; + const hook = received.find((span) => span.name === "Codex Hook: SubagentStop")!; + const completed = (span: Span) => + span.attributes.find((attr) => attr.key === "langfuse.observation.metadata.codex.completed") + ?.value.stringValue; + expect(completed(parent)).toBe("false"); + expect(completed(child)).toBe("true"); + expect(hook.parentSpanId).toBe(child.spanId); + expect(fs.existsSync(`${parentFile}.langfuse`)).toBe(false); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }, +); + +it("waits briefly for an active uploader before the final SessionEnd drain", async () => { + const codexHome = makeTempDir("lf-codex-end-home-"); + const cwd = makeTempDir("lf-codex-end-cwd-"); + const day = path.join(cwd, "sessions/2026/06/03"); + fs.mkdirSync(day, { recursive: true }); + const file = path.join(day, "rollout.jsonl"); + const line = (type: string, payload: unknown) => + JSON.stringify({ timestamp: "2026-06-03T12:00:00.000Z", type, payload }); + fs.writeFileSync( + file, + [ + line("session_meta", { id: "end-session" }), + line("event_msg", { type: "task_started", turn_id: "end-turn" }), + line("event_msg", { type: "user_message", message: "work" }), + ].join("\n") + "\n", + ); + const received: string[] = []; + const server = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + received.push(Buffer.concat(chunks).toString("utf8")); + res.writeHead(200, { "content-type": "application/json" }); + res.end("{}"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + const release = await acquireRolloutLock(file); + expect(release).toBeDefined(); + let released = false; + let releasePromise: Promise | undefined; + const timer = setTimeout(() => { + released = true; + releasePromise = release!(); + }, 600); + try { + const result = await runShellCommand(readHookCommand(), { + cwd, + env: { + ...process.env, + PLUGIN_ROOT: pluginRootDir, + CODEX_HOME: codexHome, + HOME: codexHome, + TRACE_TO_LANGFUSE: "true", + LANGFUSE_PUBLIC_KEY: "pk-lf-test", + LANGFUSE_SECRET_KEY: "sk-lf-test", + LANGFUSE_BASE_URL: `http://127.0.0.1:${port}`, + LANGFUSE_CODEX_FAIL_ON_ERROR: "true", + }, + input: JSON.stringify({ + hook_event_name: "SessionEnd", + session_id: "end-session", + transcript_path: file, + }), + }); + expect(result.code).toBe(0); + expect(released).toBe(true); + expect(received.join("")).toContain("Codex Hook: SessionEnd"); + expect(fs.readFileSync(`${file}.langfuse`, "utf8").trim()).toBe("end-turn"); + } finally { + clearTimeout(timer); + if (!released) await release!(); + else await releasePromise; + await new Promise((resolve) => server.close(() => resolve())); + } +}); diff --git a/plugins/tracing/test/incremental.test.ts b/plugins/tracing/test/incremental.test.ts new file mode 100644 index 0000000..ea72753 --- /dev/null +++ b/plugins/tracing/test/incremental.test.ts @@ -0,0 +1,393 @@ +import { createHash } from "node:crypto"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base"; +import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node"; +import { setLangfuseTracerProvider } from "@langfuse/tracing"; +import { afterAll, beforeAll, beforeEach, expect, it, vi } from "vitest"; +import type { Config } from "../src/config.js"; +import { currentIdSeed } from "../src/instrumentation.js"; +import { buildSubagentIndex, convertRollout, resolveRootRollout } from "../src/trace.js"; +import { markTurnUploaded } from "../src/sidecar.js"; + +const exporter = new InMemorySpanExporter(); +const config: Config = { + enabled: true, + public_key: "pk", + secret_key: "sk", + base_url: "http://localhost", + skill_tags: true, + debug: false, + fail_on_error: true, +}; +const id = (kind: string, size: number) => + createHash("sha256").update(`${currentIdSeed()}:${kind}`).digest("hex").slice(0, size); +const provider = new NodeTracerProvider({ + spanProcessors: [new SimpleSpanProcessor(exporter)], + idGenerator: { generateTraceId: () => id("trace", 32), generateSpanId: () => id("span", 16) }, +}); +beforeAll(() => { + provider.register(); + setLangfuseTracerProvider(provider); +}); +afterAll(async () => { + await provider.shutdown(); + setLangfuseTracerProvider(null); +}); +beforeEach(() => exporter.reset()); +const line = (second: number, type: string, payload: unknown) => + JSON.stringify({ + timestamp: new Date(Date.UTC(2026, 5, 3, 12, 0, second)).toISOString(), + type, + payload, + }); +function stage() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lf-incremental-")); + const day = path.join(dir, "sessions/2026/06/03"); + fs.mkdirSync(day, { recursive: true }); + const file = path.join(day, "rollout-parent.jsonl"); + fs.writeFileSync( + file, + [ + line(0, "session_meta", { id: "parent" }), + line(1, "event_msg", { type: "task_started", turn_id: "parent-turn" }), + line(2, "event_msg", { type: "user_message", message: "work" }), + line(3, "response_item", { + type: "function_call", + name: "exec_command", + call_id: "call-1", + arguments: "{}", + }), + ].join("\n") + "\n", + ); + return { file, day }; +} +it("uploads an open turn without finalizing it and updates stable observations", async () => { + const { file } = stage(); + expect(await convertRollout(file, { config, incremental: true })).toEqual([]); + const initial = exporter.getFinishedSpans(); + expect(initial.map((s) => s.name)).toContain("Codex Turn"); + const tool = initial.find((s) => s.name === "exec_command")!; + expect(tool.attributes["langfuse.observation.metadata.codex.completed"]).toBe("false"); + fs.appendFileSync( + file, + line(4, "response_item", { type: "function_call_output", call_id: "call-1", output: "done" }) + + "\n" + + line(5, "event_msg", { type: "task_complete", turn_id: "parent-turn" }) + + "\n", + ); + exporter.reset(); + expect(await convertRollout(file, { config, incremental: true })).toEqual(["parent-turn"]); + const updated = exporter.getFinishedSpans().find((s) => s.name === "exec_command")!; + expect(updated.spanContext()).toEqual(tool.spanContext()); + expect(updated.attributes["langfuse.observation.output"]).toContain("done"); +}); +it("uses PostToolUse payload while transcript output has not been persisted", async () => { + const { file } = stage(); + await convertRollout(file, { + config, + incremental: true, + hookEvents: [ + { + id: "hook-1", + timestamp: Date.UTC(2026, 5, 3, 12, 0, 4), + input: { + hook_event_name: "PostToolUse", + session_id: "parent", + turn_id: "parent-turn", + tool_use_id: "call-1", + tool_response: "from hook", + }, + }, + ], + }); + const spans = exporter.getFinishedSpans(); + expect( + spans.find((s) => s.name === "exec_command")?.attributes["langfuse.observation.output"], + ).toContain("from hook"); + expect(spans.some((s) => s.name === "Codex Hook: PostToolUse")).toBe(true); +}); +it("revisits children after a legacy parent checkpoint", async () => { + const { file, day } = stage(); + fs.appendFileSync( + file, + line(4, "event_msg", { type: "task_complete", turn_id: "parent-turn" }) + "\n", + ); + await markTurnUploaded(file, "parent-turn"); + const child = path.join(day, "rollout-child.jsonl"); + fs.writeFileSync( + child, + [ + line(3, "session_meta", { id: "child", parent_thread_id: "parent" }), + line(4, "event_msg", { type: "task_started", turn_id: "child-turn" }), + line(5, "event_msg", { type: "agent_message", message: "late child" }), + ].join("\n") + "\n", + ); + await convertRollout(file, { config, incremental: true }); + expect(exporter.getFinishedSpans().some((s) => s.name === "Codex Subagent Turn")).toBe(true); +}); + +it("retains hook output and completion until the rollout catches up", async () => { + const { file } = stage(); + const hooks = [ + { + id: "pending-output", + timestamp: Date.UTC(2026, 5, 3, 12, 0, 4), + input: { + hook_event_name: "PostToolUse", + session_id: "parent", + turn_id: "parent-turn", + tool_use_id: "call-1", + tool_response: "not on disk", + }, + }, + { + id: "pending-stop", + timestamp: Date.UTC(2026, 5, 3, 12, 0, 5), + input: { hook_event_name: "Stop", session_id: "parent", turn_id: "parent-turn" }, + }, + ]; + await convertRollout(file, { config, incremental: true, hookEvents: hooks }); + expect(hooks.every((hook) => (hook as { contextNeeded?: boolean }).contextNeeded)).toBe(true); + exporter.reset(); + await convertRollout(file, { + config, + incremental: true, + hookEvents: hooks.map((hook) => ({ ...hook, replayOnly: true })), + }); + const spans = exporter.getFinishedSpans(); + expect( + spans.find((s) => s.name === "exec_command")?.attributes["langfuse.observation.output"], + ).toContain("not on disk"); + expect( + spans.find((s) => s.name === "Codex Turn")?.attributes[ + "langfuse.observation.metadata.codex.completed" + ], + ).toBe("true"); + expect(spans.some((s) => s.name.startsWith("Codex Hook:"))).toBe(false); +}); + +it("keeps tool IDs stable when new tools extend an existing model step", async () => { + const { file } = stage(); + await convertRollout(file, { config, incremental: true }); + const initial = exporter.getFinishedSpans(); + fs.appendFileSync( + file, + line(4, "response_item", { + type: "function_call", + name: "extra", + call_id: "call-2", + arguments: "{}", + }) + "\n", + ); + exporter.reset(); + await convertRollout(file, { config, incremental: true }); + for (const span of initial) { + const updated = exporter.getFinishedSpans().find((s) => s.name === span.name)!; + expect(updated.spanContext()).toEqual(span.spanContext()); + } +}); + +it("retains a native tool_use_id result until its call row appears", async () => { + const { file } = stage(); + fs.writeFileSync( + file, + fs + .readFileSync(file, "utf8") + .split("\n") + .filter((raw) => !raw.includes('"type":"function_call"')) + .join("\n"), + ); + const hook = { + id: "race-tool", + timestamp: Date.UTC(2026, 5, 3, 12, 0, 4), + input: { + session_id: "parent", + turn_id: "parent-turn", + hook_event_name: "PostToolUse", + tool_use_id: "call-1", + tool_response: "raced output", + }, + contextNeeded: false, + }; + await convertRollout(file, { config, incremental: true, hookEvents: [hook] }); + expect(hook.contextNeeded).toBe(true); + fs.appendFileSync( + file, + line(3, "response_item", { + type: "function_call", + name: "exec_command", + call_id: "call-1", + arguments: "{}", + }) + "\n", + ); + exporter.reset(); + await convertRollout(file, { + config, + incremental: true, + hookEvents: [{ ...hook, replayOnly: true }], + }); + expect( + exporter.getFinishedSpans().find((span) => span.name === "exec_command")?.attributes[ + "langfuse.observation.output" + ], + ).toContain("raced output"); +}); + +it("captures the native final assistant message before the rollout writer", async () => { + const { file } = stage(); + const hook = { + id: "race-stop", + timestamp: Date.UTC(2026, 5, 3, 12, 0, 5), + input: { + session_id: "parent", + turn_id: "parent-turn", + hook_event_name: "Stop", + last_assistant_message: "latest final answer", + }, + contextNeeded: false, + }; + await convertRollout(file, { config, incremental: true, hookEvents: [hook] }); + expect( + exporter.getFinishedSpans().find((span) => span.name === "Codex Turn")?.attributes[ + "langfuse.observation.output" + ], + ).toContain("latest final answer"); + expect(hook.contextNeeded).toBe(true); +}); + +it("restricts a flat rollout to its sibling directory and supports configured archives", async () => { + const base = fs.mkdtempSync(path.join(os.tmpdir(), "lf-archive-index-")); + const archive = path.join(base, "archived_sessions"); + fs.mkdirSync(archive); + const file = path.join(archive, "rollout-child.jsonl"); + fs.writeFileSync( + file, + line(0, "session_meta", { id: "archived-child", parent_thread_id: "active-parent" }) + "\n", + ); + fs.writeFileSync( + path.join(base, "unrelated.jsonl"), + line(0, "session_meta", { id: "unrelated" }) + "\n", + ); + const nested = path.join(archive, "unrelated-tree"); + fs.mkdirSync(nested); + fs.writeFileSync( + path.join(nested, "nested.jsonl"), + line(0, "session_meta", { id: "nested-unrelated" }) + "\n", + ); + const flatIndex = await buildSubagentIndex(file); + expect(flatIndex.byThread.has("unrelated")).toBe(false); + expect(flatIndex.byThread.has("nested-unrelated")).toBe(false); + const day = path.join(base, "sessions/2026/06/03"); + fs.mkdirSync(day, { recursive: true }); + const parent = path.join(day, "rollout-parent.jsonl"); + fs.writeFileSync(parent, line(0, "session_meta", { id: "active-parent" }) + "\n"); + vi.stubEnv("CODEX_HOME", base); + try { + const resolved = await resolveRootRollout(file); + expect(resolved.file).toBe(parent); + expect(resolved.index.byThread.has("unrelated")).toBe(false); + } finally { + vi.unstubAllEnvs(); + } +}); + +it("skips unchanged payload preparation but resumes when the transcript grows", async () => { + const { file } = stage(); + const fingerprints: Record = {}; + await convertRollout(file, { config, incremental: true, pendingTurnFingerprints: fingerprints }); + expect(Object.keys(fingerprints)).toContain("parent:parent-turn"); + exporter.reset(); + await convertRollout(file, { config, incremental: true, acknowledgedTurns: fingerprints }); + const cached = exporter.getFinishedSpans(); + expect( + cached.every( + (span) => span.attributes["langfuse.observation.metadata.codex.legacy_uploaded"] === "true", + ), + ).toBe(true); + expect(cached.every((span) => span.attributes["langfuse.observation.input"] === undefined)).toBe( + true, + ); + fs.appendFileSync( + file, + line(4, "response_item", { + type: "function_call_output", + call_id: "call-1", + output: "new activity", + }) + "\n", + ); + exporter.reset(); + await convertRollout(file, { config, incremental: true, acknowledgedTurns: fingerprints }); + const changed = exporter.getFinishedSpans().find((span) => span.name === "exec_command")!; + expect(changed.attributes["langfuse.observation.output"]).toContain("new activity"); + expect(changed.attributes["langfuse.observation.metadata.codex.legacy_uploaded"]).toBeUndefined(); +}); + +it("skips acknowledged earlier steps when a running turn gains a new model step", async () => { + const { file } = stage(); + fs.appendFileSync(file, line(4, "event_msg", { type: "token_count" }) + "\n"); + const fingerprints: Record = {}; + await convertRollout(file, { config, incremental: true, pendingTurnFingerprints: fingerprints }); + fs.appendFileSync( + file, + line(5, "response_item", { + type: "function_call", + name: "new_tool", + call_id: "call-2", + arguments: "{}", + }) + "\n", + ); + exporter.reset(); + await convertRollout(file, { config, incremental: true, acknowledgedTurns: fingerprints }); + const generations = exporter.getFinishedSpans().filter((span) => span.name === "LLM"); + expect(generations).toHaveLength(2); + const first = generations.find( + (span) => span.attributes["langfuse.observation.metadata.codex.step_index"] === "0", + )!; + const second = generations.find( + (span) => span.attributes["langfuse.observation.metadata.codex.step_index"] === "1", + )!; + expect(first.attributes["langfuse.observation.metadata.codex.legacy_uploaded"]).toBe("true"); + expect(first.attributes["langfuse.observation.input"]).toBeUndefined(); + expect(second.attributes["langfuse.observation.metadata.codex.legacy_uploaded"]).toBeUndefined(); + expect(second.attributes["langfuse.observation.input"]).toBeDefined(); +}); + +it("keeps a turn-less hook attached to its original turn when a later turn appears", async () => { + const { file } = stage(); + const persisted = { + id: "delayed-stop", + timestamp: Date.UTC(2026, 5, 3, 12, 0, 4), + input: { session_id: "parent", hook_event_name: "Stop" }, + }; + await convertRollout(file, { + config, + incremental: true, + hookEvents: [structuredClone(persisted)], + }); + const first = exporter.getFinishedSpans().find((span) => span.name === "Codex Hook: Stop")!; + fs.appendFileSync( + file, + line(5, "event_msg", { type: "task_complete", turn_id: "parent-turn" }) + + "\n" + + line(6, "event_msg", { type: "task_started", turn_id: "next-turn" }) + + "\n" + + line(7, "event_msg", { type: "user_message", message: "next request" }) + + "\n", + ); + exporter.reset(); + await convertRollout(file, { + config, + incremental: true, + hookEvents: [structuredClone(persisted)], + }); + const spans = exporter.getFinishedSpans(); + const replay = spans.find((span) => span.name === "Codex Hook: Stop")!; + expect(replay.spanContext()).toEqual(first.spanContext()); + const next = spans.find( + (span) => span.attributes["langfuse.observation.metadata.codex.turn_id"] === "next-turn", + )!; + expect(next.attributes["langfuse.observation.metadata.codex.completed"]).toBe("false"); + expect(replay.parentSpanContext?.spanId).not.toBe(next.spanContext().spanId); +}); diff --git a/plugins/tracing/test/instrumentation.test.ts b/plugins/tracing/test/instrumentation.test.ts index 444335d..e19aa77 100644 --- a/plugins/tracing/test/instrumentation.test.ts +++ b/plugins/tracing/test/instrumentation.test.ts @@ -4,7 +4,7 @@ import * as path from "node:path"; import { fileURLToPath } from "node:url"; import { getLangfuseTracerProvider, setLangfuseTracerProvider } from "@langfuse/tracing"; -import type { ReadableSpan, SpanProcessor } from "@opentelemetry/sdk-trace-base"; +import type { ReadableSpan, SpanExporter, SpanProcessor } from "@opentelemetry/sdk-trace-base"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Config } from "../src/config.js"; @@ -14,15 +14,25 @@ import { convertRollout } from "../src/trace.js"; // Capture the spans the plugin's own span processor receives, so the assertion // needs no network and no Langfuse credentials. const captured: ReadableSpan[] = []; +let dropPreparation = false; vi.mock("@langfuse/otel", () => ({ LangfuseSpanProcessor: class implements SpanProcessor { + private readonly exporter: SpanExporter; + constructor(params: { exporter: SpanExporter }) { + this.exporter = params.exporter; + } onStart(): void {} onEnd(span: ReadableSpan): void { captured.push(span); + if (!dropPreparation) this.exporter.export([span], () => {}); + } + async forceFlush(): Promise { + await this.exporter.forceFlush?.(); + } + async shutdown(): Promise { + await this.exporter.shutdown(); } - async forceFlush(): Promise {} - async shutdown(): Promise {} }, })); @@ -72,6 +82,11 @@ let previousGlobal: unknown; beforeEach(() => { captured.length = 0; + dropPreparation = false; + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response("{}")), + ); previousGlobal = occupyGlobalRegistry(); }); @@ -79,6 +94,7 @@ afterEach(() => { (globalThis as Record)[OTEL_API_KEY] = previousGlobal; setLangfuseTracerProvider(null); vi.unstubAllEnvs(); + vi.unstubAllGlobals(); }); async function resourceAttrsOfExportedSpan(): Promise> { @@ -113,6 +129,15 @@ describe("setupInstrumentation", () => { expect(getLangfuseTracerProvider()).not.toBe(bound); }); + + it("rejects shutdown if the SDK swallowed a preparation failure", async () => { + dropPreparation = true; + const instrumentation = setupInstrumentation(baseConfig); + getLangfuseTracerProvider().getTracer("test").startSpan("lost-before-export").end(); + await expect(instrumentation.shutdown()).rejects.toThrow("preparation failed"); + expect(getLangfuseTracerProvider()).not.toBeUndefined(); + expect(instrumentation.acknowledged()).toEqual({}); + }); }); describe("resource attributes", () => { diff --git a/plugins/tracing/test/sidecar.test.ts b/plugins/tracing/test/sidecar.test.ts new file mode 100644 index 0000000..b09a16b --- /dev/null +++ b/plugins/tracing/test/sidecar.test.ts @@ -0,0 +1,81 @@ +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { expect, it } from "vitest"; +import { + acquireRolloutLock, + acknowledgeHooks, + enqueueHook, + loadHookContext, + loadObservationCheckpoint, + loadUploadedTurnIds, + markTurnUploaded, + pendingHooks, + saveObservationCheckpoint, +} from "../src/sidecar.js"; + +it("keeps concurrent hooks durable while serializing one uploader", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "lf-sidecar-")); + const file = path.join(dir, "rollout.jsonl"); + await enqueueHook(file, { session_id: "session", hook_event_name: "PostToolUse" }); + const release = await acquireRolloutLock(file); + expect(release).toBeDefined(); + await enqueueHook(file, { session_id: "session", hook_event_name: "Stop" }); + expect(await acquireRolloutLock(file)).toBeUndefined(); + const events = await pendingHooks(file); + expect(events).toHaveLength(2); + expect(new Set(events.map((event) => event.id)).size).toBe(2); + await saveObservationCheckpoint(file, { "trace:span": "fingerprint" }, [ + { ...events[0], replayOnly: true }, + ]); + expect(await loadObservationCheckpoint(file)).toEqual({ "trace:span": "fingerprint" }); + expect(await loadHookContext(file)).toHaveLength(1); + await acknowledgeHooks(file, [events[0]]); + expect(await pendingHooks(file)).toHaveLength(1); + await release!(); + const nextRelease = await acquireRolloutLock(file); + expect(nextRelease).toBeDefined(); + await nextRelease!(); +}); +it("keeps legacy newline checkpoint compatibility", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "lf-sidecar-")); + const file = path.join(dir, "rollout.jsonl"); + await markTurnUploaded(file, "old-turn"); + expect(await loadUploadedTurnIds(file)).toEqual(new Set(["old-turn"])); + expect(await loadObservationCheckpoint(file)).toEqual({}); + await saveObservationCheckpoint(file, { "new:observation": "new-content" }); + expect(await loadUploadedTurnIds(file)).toEqual(new Set(["old-turn"])); +}); + +it("ignores stale lock-file contents because ownership belongs to the kernel", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "lf-sidecar-kernel-")); + const file = path.join(dir, "rollout.jsonl"); + await fs.writeFile(`${file}.langfuse-lock`, "dead uploader 999999\n"); + const release = await acquireRolloutLock(file); + expect(release).toBeDefined(); + await release!(); + const acquiredAgain = await acquireRolloutLock(file); + expect(acquiredAgain).toBeDefined(); + await acquiredAgain!(); +}); + +it("lets an already queued contender drain after the owner releases without another hook", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "lf-sidecar-handoff-")); + const file = path.join(dir, "rollout.jsonl"); + const release = await acquireRolloutLock(file); + expect(release).toBeDefined(); + expect(await pendingHooks(file)).toHaveLength(0); + await enqueueHook(file, { hook_event_name: "PostToolUse", session_id: "handoff-session" }); + const waiting = acquireRolloutLock(file, 1); + await release!(); + const contenderRelease = await waiting; + expect(contenderRelease).toBeDefined(); + try { + const events = await pendingHooks(file); + expect(events).toHaveLength(1); + await acknowledgeHooks(file, events); + expect(await pendingHooks(file)).toHaveLength(0); + } finally { + await contenderRelease!(); + } +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cbe75e5..a4ec263 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,6 +23,9 @@ importers: '@opentelemetry/exporter-trace-otlp-http': specifier: ^0.222.0 version: 0.222.0(@opentelemetry/api@1.9.1) + '@opentelemetry/otlp-transformer': + specifier: 0.222.0 + version: 0.222.0(@opentelemetry/api@1.9.1) '@opentelemetry/resources': specifier: ^2.11.0 version: 2.11.0(@opentelemetry/api@1.9.1)