// Force strict mode and setup for ESM
"use strict";
import {
  require_aspromise,
  require_index_minimal,
  require_minimal,
  require_minimal2,
  require_reader,
  require_roots,
  require_rpc,
  require_umd,
  require_writer
} from "./chunk-E6US47KI.js";
import {
  require_hasown
} from "./chunk-UWCTAVOD.js";
import {
  DEFAULT_QWEN_MODEL,
  MAINLINE_CODER_MODEL
} from "./chunk-OFEVLU4C.js";
import {
  Mutex
} from "./chunk-OMX7CUOE.js";
import {
  isAnyAutoMemPath
} from "./chunk-MOUXUCXQ.js";
import {
  InstallationManager
} from "./chunk-BZHLWC6T.js";
import {
  STRUCTURED_OUTPUT_REDACTED_ARGS
} from "./chunk-RZORUN6X.js";
import {
  BaseDeclarativeTool,
  BaseToolInvocation,
  ToolDisplayNames,
  ToolNames
} from "./chunk-MJKMIQMK.js";
import {
  atomicWriteFile,
  atomicWriteFileSync
} from "./chunk-T42ACHFI.js";
import {
  convertSchema,
  runtimeDiagnostics,
  safeJsonParse
} from "./chunk-YPCPZSZB.js";
import {
  require_lib
} from "./chunk-IRJWHZWU.js";
import {
  FinishReason,
  GenerateContentResponse
} from "./chunk-55ZMG67I.js";
import {
  FatalConfigError,
  Storage,
  createDebugLogger,
  formatTraceparent,
  getActiveSpanTraceContext,
  getCurrentSessionId,
  getErrorMessage,
  getErrorStatus,
  getErrorType,
  isAbortError,
  isNodeError,
  isSubpaths,
  makeRelative,
  setSessionContext,
  setShellTracePropagation,
  shortenPath,
  unescapePath
} from "./chunk-AVQDCKNF.js";
import {
  require_dist
} from "./chunk-ZERZSAZL.js";
import {
  require_src
} from "./chunk-QN5NZ3UQ.js";
import {
  DiagLogLevel,
  ROOT_CONTEXT,
  SpanKind,
  SpanStatusCode,
  TraceFlags,
  ValueType,
  context,
  diag,
  esm_exports,
  init_esm,
  isSpanContextValid,
  metrics,
  propagation,
  trace
} from "./chunk-Z2Z3GUXZ.js";
import {
  __qwen_dirname,
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __commonJS,
  __esm,
  __export,
  __name,
  __require,
  __toCommonJS,
  __toESM
} from "./chunk-J2S4EL5Y.js";

// node_modules/chardet/lib/fs/node.js
var require_node = __commonJS({
  "node_modules/chardet/lib/fs/node.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    var fsModule;
    exports.default = () => {
      if (typeof module === "object" && typeof module.exports === "object") {
        fsModule = fsModule ? fsModule : __require("fs");
        return fsModule;
      }
      throw new Error("File system is not available");
    };
  }
});

// node_modules/chardet/lib/match.js
var require_match = __commonJS({
  "node_modules/chardet/lib/match.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = (ctx, rec, confidence) => ({
      confidence,
      name: rec.name(ctx),
      lang: rec.language ? rec.language() : void 0
    });
  }
});

// node_modules/chardet/lib/encoding/ascii.js
var require_ascii = __commonJS({
  "node_modules/chardet/lib/encoding/ascii.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    var match_1 = __importDefault(require_match());
    var Ascii = class {
      static {
        __name(this, "Ascii");
      }
      name() {
        return "ASCII";
      }
      match(det) {
        const input = det.rawInput;
        for (let i = 0; i < det.rawLen; i++) {
          const b = input[i];
          if (b < 32 || b > 126) {
            return (0, match_1.default)(det, this, 0);
          }
        }
        return (0, match_1.default)(det, this, 100);
      }
    };
    exports.default = Ascii;
  }
});

// node_modules/chardet/lib/encoding/utf8.js
var require_utf8 = __commonJS({
  "node_modules/chardet/lib/encoding/utf8.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    var match_1 = __importDefault(require_match());
    var Utf8 = class {
      static {
        __name(this, "Utf8");
      }
      name() {
        return "UTF-8";
      }
      match(det) {
        let hasBOM = false, numValid = 0, numInvalid = 0, trailBytes = 0, confidence;
        const input = det.rawInput;
        if (det.rawLen >= 3 && (input[0] & 255) == 239 && (input[1] & 255) == 187 && (input[2] & 255) == 191) {
          hasBOM = true;
        }
        for (let i = 0; i < det.rawLen; i++) {
          const b = input[i];
          if ((b & 128) == 0)
            continue;
          if ((b & 224) == 192) {
            trailBytes = 1;
          } else if ((b & 240) == 224) {
            trailBytes = 2;
          } else if ((b & 248) == 240) {
            trailBytes = 3;
          } else {
            numInvalid++;
            if (numInvalid > 5)
              break;
            trailBytes = 0;
          }
          for (; ; ) {
            i++;
            if (i >= det.rawLen)
              break;
            if ((input[i] & 192) != 128) {
              numInvalid++;
              break;
            }
            if (--trailBytes == 0) {
              numValid++;
              break;
            }
          }
        }
        confidence = 0;
        if (hasBOM && numInvalid == 0)
          confidence = 100;
        else if (hasBOM && numValid > numInvalid * 10)
          confidence = 80;
        else if (numValid > 3 && numInvalid == 0)
          confidence = 100;
        else if (numValid > 0 && numInvalid == 0)
          confidence = 80;
        else if (numValid == 0 && numInvalid == 0)
          confidence = 10;
        else if (numValid > numInvalid * 10)
          confidence = 25;
        else
          return null;
        return (0, match_1.default)(det, this, confidence);
      }
    };
    exports.default = Utf8;
  }
});

// node_modules/chardet/lib/encoding/unicode.js
var require_unicode = __commonJS({
  "node_modules/chardet/lib/encoding/unicode.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UTF_32LE = exports.UTF_32BE = exports.UTF_16LE = exports.UTF_16BE = void 0;
    var match_1 = __importDefault(require_match());
    var UTF_16BE = class {
      static {
        __name(this, "UTF_16BE");
      }
      name() {
        return "UTF-16BE";
      }
      match(det) {
        const input = det.rawInput;
        if (input.length >= 2 && (input[0] & 255) == 254 && (input[1] & 255) == 255) {
          return (0, match_1.default)(det, this, 100);
        }
        return null;
      }
    };
    exports.UTF_16BE = UTF_16BE;
    var UTF_16LE = class {
      static {
        __name(this, "UTF_16LE");
      }
      name() {
        return "UTF-16LE";
      }
      match(det) {
        const input = det.rawInput;
        if (input.length >= 2 && (input[0] & 255) == 255 && (input[1] & 255) == 254) {
          if (input.length >= 4 && input[2] == 0 && input[3] == 0) {
            return null;
          }
          return (0, match_1.default)(det, this, 100);
        }
        return null;
      }
    };
    exports.UTF_16LE = UTF_16LE;
    var UTF_32 = class {
      static {
        __name(this, "UTF_32");
      }
      name() {
        return "UTF-32";
      }
      getChar(_input, _index) {
        return -1;
      }
      match(det) {
        let numValid = 0, numInvalid = 0, hasBOM = false, confidence = 0;
        const limit = det.rawLen / 4 * 4;
        const input = det.rawInput;
        if (limit == 0) {
          return null;
        }
        if (this.getChar(input, 0) == 65279) {
          hasBOM = true;
        }
        for (let i = 0; i < limit; i += 4) {
          const ch = this.getChar(input, i);
          if (ch < 0 || ch >= 1114111 || ch >= 55296 && ch <= 57343) {
            numInvalid += 1;
          } else {
            numValid += 1;
          }
        }
        if (hasBOM && numInvalid == 0) {
          confidence = 100;
        } else if (hasBOM && numValid > numInvalid * 10) {
          confidence = 80;
        } else if (numValid > 3 && numInvalid == 0) {
          confidence = 100;
        } else if (numValid > 0 && numInvalid == 0) {
          confidence = 80;
        } else if (numValid > numInvalid * 10) {
          confidence = 25;
        }
        return confidence == 0 ? null : (0, match_1.default)(det, this, confidence);
      }
    };
    var UTF_32BE = class extends UTF_32 {
      static {
        __name(this, "UTF_32BE");
      }
      name() {
        return "UTF-32BE";
      }
      getChar(input, index) {
        return (input[index + 0] & 255) << 24 | (input[index + 1] & 255) << 16 | (input[index + 2] & 255) << 8 | input[index + 3] & 255;
      }
    };
    exports.UTF_32BE = UTF_32BE;
    var UTF_32LE = class extends UTF_32 {
      static {
        __name(this, "UTF_32LE");
      }
      name() {
        return "UTF-32LE";
      }
      getChar(input, index) {
        return (input[index + 3] & 255) << 24 | (input[index + 2] & 255) << 16 | (input[index + 1] & 255) << 8 | input[index + 0] & 255;
      }
    };
    exports.UTF_32LE = UTF_32LE;
  }
});

// node_modules/chardet/lib/encoding/mbcs.js
var require_mbcs = __commonJS({
  "node_modules/chardet/lib/encoding/mbcs.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.gb_18030 = exports.euc_kr = exports.euc_jp = exports.big5 = exports.sjis = void 0;
    var match_1 = __importDefault(require_match());
    function binarySearch(arr, searchValue) {
      const find = /* @__PURE__ */ __name((arr2, searchValue2, left, right) => {
        if (right < left)
          return -1;
        const mid = Math.floor(left + right >>> 1);
        if (searchValue2 > arr2[mid])
          return find(arr2, searchValue2, mid + 1, right);
        if (searchValue2 < arr2[mid])
          return find(arr2, searchValue2, left, mid - 1);
        return mid;
      }, "find");
      return find(arr, searchValue, 0, arr.length - 1);
    }
    __name(binarySearch, "binarySearch");
    var IteratedChar = class {
      static {
        __name(this, "IteratedChar");
      }
      constructor() {
        this.charValue = 0;
        this.index = 0;
        this.nextIndex = 0;
        this.error = false;
        this.done = false;
      }
      reset() {
        this.charValue = 0;
        this.index = -1;
        this.nextIndex = 0;
        this.error = false;
        this.done = false;
      }
      nextByte(det) {
        if (this.nextIndex >= det.rawLen) {
          this.done = true;
          return -1;
        }
        const byteValue = det.rawInput[this.nextIndex++] & 255;
        return byteValue;
      }
    };
    var mbcs = class {
      static {
        __name(this, "mbcs");
      }
      constructor() {
        this.commonChars = [];
      }
      name() {
        return "mbcs";
      }
      match(det) {
        let doubleByteCharCount = 0, commonCharCount = 0, badCharCount = 0, totalCharCount = 0, confidence = 0;
        const iter = new IteratedChar();
        detectBlock: {
          for (iter.reset(); this.nextChar(iter, det); ) {
            totalCharCount++;
            if (iter.error) {
              badCharCount++;
            } else {
              const cv = iter.charValue & 4294967295;
              if (cv > 255) {
                doubleByteCharCount++;
                if (this.commonChars != null) {
                  if (binarySearch(this.commonChars, cv) >= 0) {
                    commonCharCount++;
                  }
                }
              }
            }
            if (badCharCount >= 2 && badCharCount * 5 >= doubleByteCharCount) {
              break detectBlock;
            }
          }
          if (doubleByteCharCount <= 10 && badCharCount == 0) {
            if (doubleByteCharCount == 0 && totalCharCount < 10) {
              confidence = 0;
            } else {
              confidence = 10;
            }
            break detectBlock;
          }
          if (doubleByteCharCount < 20 * badCharCount) {
            confidence = 0;
            break detectBlock;
          }
          if (this.commonChars == null) {
            confidence = 30 + doubleByteCharCount - 20 * badCharCount;
            if (confidence > 100) {
              confidence = 100;
            }
          } else {
            const maxVal = Math.log(doubleByteCharCount / 4);
            const scaleFactor = 90 / maxVal;
            confidence = Math.floor(Math.log(commonCharCount + 1) * scaleFactor + 10);
            confidence = Math.min(confidence, 100);
          }
        }
        return confidence == 0 ? null : (0, match_1.default)(det, this, confidence);
      }
      nextChar(_iter, _det) {
        return true;
      }
    };
    var sjis = class extends mbcs {
      static {
        __name(this, "sjis");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          33088,
          33089,
          33090,
          33093,
          33115,
          33129,
          33130,
          33141,
          33142,
          33440,
          33442,
          33444,
          33449,
          33450,
          33451,
          33453,
          33455,
          33457,
          33459,
          33461,
          33463,
          33469,
          33470,
          33473,
          33476,
          33477,
          33478,
          33480,
          33481,
          33484,
          33485,
          33500,
          33504,
          33511,
          33512,
          33513,
          33514,
          33520,
          33521,
          33601,
          33603,
          33614,
          33615,
          33624,
          33630,
          33634,
          33639,
          33653,
          33654,
          33673,
          33674,
          33675,
          33677,
          33683,
          36502,
          37882,
          38314
        ];
      }
      name() {
        return "Shift_JIS";
      }
      language() {
        return "ja";
      }
      nextChar(iter, det) {
        iter.index = iter.nextIndex;
        iter.error = false;
        const firstByte = iter.charValue = iter.nextByte(det);
        if (firstByte < 0)
          return false;
        if (firstByte <= 127 || firstByte > 160 && firstByte <= 223)
          return true;
        const secondByte = iter.nextByte(det);
        if (secondByte < 0)
          return false;
        iter.charValue = firstByte << 8 | secondByte;
        if (!(secondByte >= 64 && secondByte <= 127 || secondByte >= 128 && secondByte <= 255)) {
          iter.error = true;
        }
        return true;
      }
    };
    exports.sjis = sjis;
    var big5 = class extends mbcs {
      static {
        __name(this, "big5");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          41280,
          41281,
          41282,
          41283,
          41287,
          41289,
          41333,
          41334,
          42048,
          42054,
          42055,
          42056,
          42065,
          42068,
          42071,
          42084,
          42090,
          42092,
          42103,
          42147,
          42148,
          42151,
          42177,
          42190,
          42193,
          42207,
          42216,
          42237,
          42304,
          42312,
          42328,
          42345,
          42445,
          42471,
          42583,
          42593,
          42594,
          42600,
          42608,
          42664,
          42675,
          42681,
          42707,
          42715,
          42726,
          42738,
          42816,
          42833,
          42841,
          42970,
          43171,
          43173,
          43181,
          43217,
          43219,
          43236,
          43260,
          43456,
          43474,
          43507,
          43627,
          43706,
          43710,
          43724,
          43772,
          44103,
          44111,
          44208,
          44242,
          44377,
          44745,
          45024,
          45290,
          45423,
          45747,
          45764,
          45935,
          46156,
          46158,
          46412,
          46501,
          46525,
          46544,
          46552,
          46705,
          47085,
          47207,
          47428,
          47832,
          47940,
          48033,
          48593,
          49860,
          50105,
          50240,
          50271
        ];
      }
      name() {
        return "Big5";
      }
      language() {
        return "zh";
      }
      nextChar(iter, det) {
        iter.index = iter.nextIndex;
        iter.error = false;
        const firstByte = iter.charValue = iter.nextByte(det);
        if (firstByte < 0)
          return false;
        if (firstByte <= 127 || firstByte == 255)
          return true;
        const secondByte = iter.nextByte(det);
        if (secondByte < 0)
          return false;
        iter.charValue = iter.charValue << 8 | secondByte;
        if (secondByte < 64 || secondByte == 127 || secondByte == 255)
          iter.error = true;
        return true;
      }
    };
    exports.big5 = big5;
    function eucNextChar(iter, det) {
      iter.index = iter.nextIndex;
      iter.error = false;
      let firstByte = 0;
      let secondByte = 0;
      let thirdByte = 0;
      buildChar: {
        firstByte = iter.charValue = iter.nextByte(det);
        if (firstByte < 0) {
          iter.done = true;
          break buildChar;
        }
        if (firstByte <= 141) {
          break buildChar;
        }
        secondByte = iter.nextByte(det);
        iter.charValue = iter.charValue << 8 | secondByte;
        if (firstByte >= 161 && firstByte <= 254) {
          if (secondByte < 161) {
            iter.error = true;
          }
          break buildChar;
        }
        if (firstByte == 142) {
          if (secondByte < 161) {
            iter.error = true;
          }
          break buildChar;
        }
        if (firstByte == 143) {
          thirdByte = iter.nextByte(det);
          iter.charValue = iter.charValue << 8 | thirdByte;
          if (thirdByte < 161) {
            iter.error = true;
          }
        }
      }
      return iter.done == false;
    }
    __name(eucNextChar, "eucNextChar");
    var euc_jp = class extends mbcs {
      static {
        __name(this, "euc_jp");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          41377,
          41378,
          41379,
          41382,
          41404,
          41418,
          41419,
          41430,
          41431,
          42146,
          42148,
          42150,
          42152,
          42154,
          42155,
          42156,
          42157,
          42159,
          42161,
          42163,
          42165,
          42167,
          42169,
          42171,
          42173,
          42175,
          42176,
          42177,
          42179,
          42180,
          42182,
          42183,
          42184,
          42185,
          42186,
          42187,
          42190,
          42191,
          42192,
          42206,
          42207,
          42209,
          42210,
          42212,
          42216,
          42217,
          42218,
          42219,
          42220,
          42223,
          42226,
          42227,
          42402,
          42403,
          42404,
          42406,
          42407,
          42410,
          42413,
          42415,
          42416,
          42419,
          42421,
          42423,
          42424,
          42425,
          42431,
          42435,
          42438,
          42439,
          42440,
          42441,
          42443,
          42448,
          42453,
          42454,
          42455,
          42462,
          42464,
          42465,
          42469,
          42473,
          42474,
          42475,
          42476,
          42477,
          42483,
          47273,
          47572,
          47854,
          48072,
          48880,
          49079,
          50410,
          50940,
          51133,
          51896,
          51955,
          52188,
          52689
        ];
        this.nextChar = eucNextChar;
      }
      name() {
        return "EUC-JP";
      }
      language() {
        return "ja";
      }
    };
    exports.euc_jp = euc_jp;
    var euc_kr = class extends mbcs {
      static {
        __name(this, "euc_kr");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          45217,
          45235,
          45253,
          45261,
          45268,
          45286,
          45293,
          45304,
          45306,
          45308,
          45496,
          45497,
          45511,
          45527,
          45538,
          45994,
          46011,
          46274,
          46287,
          46297,
          46315,
          46501,
          46517,
          46527,
          46535,
          46569,
          46835,
          47023,
          47042,
          47054,
          47270,
          47278,
          47286,
          47288,
          47291,
          47337,
          47531,
          47534,
          47564,
          47566,
          47613,
          47800,
          47822,
          47824,
          47857,
          48103,
          48115,
          48125,
          48301,
          48314,
          48338,
          48374,
          48570,
          48576,
          48579,
          48581,
          48838,
          48840,
          48863,
          48878,
          48888,
          48890,
          49057,
          49065,
          49088,
          49124,
          49131,
          49132,
          49144,
          49319,
          49327,
          49336,
          49338,
          49339,
          49341,
          49351,
          49356,
          49358,
          49359,
          49366,
          49370,
          49381,
          49403,
          49404,
          49572,
          49574,
          49590,
          49622,
          49631,
          49654,
          49656,
          50337,
          50637,
          50862,
          51151,
          51153,
          51154,
          51160,
          51173,
          51373
        ];
        this.nextChar = eucNextChar;
      }
      name() {
        return "EUC-KR";
      }
      language() {
        return "ko";
      }
    };
    exports.euc_kr = euc_kr;
    var gb_18030 = class extends mbcs {
      static {
        __name(this, "gb_18030");
      }
      constructor() {
        super(...arguments);
        this.commonChars = [
          41377,
          41378,
          41379,
          41380,
          41392,
          41393,
          41457,
          41459,
          41889,
          41900,
          41914,
          45480,
          45496,
          45502,
          45755,
          46025,
          46070,
          46323,
          46525,
          46532,
          46563,
          46767,
          46804,
          46816,
          47010,
          47016,
          47037,
          47062,
          47069,
          47284,
          47327,
          47350,
          47531,
          47561,
          47576,
          47610,
          47613,
          47821,
          48039,
          48086,
          48097,
          48122,
          48316,
          48347,
          48382,
          48588,
          48845,
          48861,
          49076,
          49094,
          49097,
          49332,
          49389,
          49611,
          49883,
          50119,
          50396,
          50410,
          50636,
          50935,
          51192,
          51371,
          51403,
          51413,
          51431,
          51663,
          51706,
          51889,
          51893,
          51911,
          51920,
          51926,
          51957,
          51965,
          52460,
          52728,
          52906,
          52932,
          52946,
          52965,
          53173,
          53186,
          53206,
          53442,
          53445,
          53456,
          53460,
          53671,
          53930,
          53938,
          53941,
          53947,
          53972,
          54211,
          54224,
          54269,
          54466,
          54490,
          54754,
          54992
        ];
      }
      name() {
        return "GB18030";
      }
      language() {
        return "zh";
      }
      nextChar(iter, det) {
        iter.index = iter.nextIndex;
        iter.error = false;
        let firstByte = 0;
        let secondByte = 0;
        let thirdByte = 0;
        let fourthByte = 0;
        buildChar: {
          firstByte = iter.charValue = iter.nextByte(det);
          if (firstByte < 0) {
            iter.done = true;
            break buildChar;
          }
          if (firstByte <= 128) {
            break buildChar;
          }
          secondByte = iter.nextByte(det);
          iter.charValue = iter.charValue << 8 | secondByte;
          if (firstByte >= 129 && firstByte <= 254) {
            if (secondByte >= 64 && secondByte <= 126 || secondByte >= 80 && secondByte <= 254) {
              break buildChar;
            }
            if (secondByte >= 48 && secondByte <= 57) {
              thirdByte = iter.nextByte(det);
              if (thirdByte >= 129 && thirdByte <= 254) {
                fourthByte = iter.nextByte(det);
                if (fourthByte >= 48 && fourthByte <= 57) {
                  iter.charValue = iter.charValue << 16 | thirdByte << 8 | fourthByte;
                  break buildChar;
                }
              }
            }
            iter.error = true;
            break buildChar;
          }
        }
        return iter.done == false;
      }
    };
    exports.gb_18030 = gb_18030;
  }
});

// node_modules/chardet/lib/encoding/sbcs.js
var require_sbcs = __commonJS({
  "node_modules/chardet/lib/encoding/sbcs.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KOI8_R = exports.windows_1256 = exports.windows_1251 = exports.ISO_8859_9 = exports.ISO_8859_8 = exports.ISO_8859_7 = exports.ISO_8859_6 = exports.ISO_8859_5 = exports.ISO_8859_2 = exports.ISO_8859_1 = void 0;
    var match_1 = __importDefault(require_match());
    var N_GRAM_MASK = 16777215;
    var NGramParser = class {
      static {
        __name(this, "NGramParser");
      }
      constructor(theNgramList, theByteMap) {
        this.byteIndex = 0;
        this.ngram = 0;
        this.ngramCount = 0;
        this.hitCount = 0;
        this.spaceChar = 32;
        this.ngramList = theNgramList;
        this.byteMap = theByteMap;
      }
      search(table, value) {
        let index = 0;
        if (table[index + 32] <= value)
          index += 32;
        if (table[index + 16] <= value)
          index += 16;
        if (table[index + 8] <= value)
          index += 8;
        if (table[index + 4] <= value)
          index += 4;
        if (table[index + 2] <= value)
          index += 2;
        if (table[index + 1] <= value)
          index += 1;
        if (table[index] > value)
          index -= 1;
        if (index < 0 || table[index] != value)
          return -1;
        return index;
      }
      lookup(thisNgram) {
        this.ngramCount += 1;
        if (this.search(this.ngramList, thisNgram) >= 0) {
          this.hitCount += 1;
        }
      }
      addByte(b) {
        this.ngram = (this.ngram << 8) + (b & 255) & N_GRAM_MASK;
        this.lookup(this.ngram);
      }
      nextByte(det) {
        if (this.byteIndex >= det.inputLen)
          return -1;
        return det.inputBytes[this.byteIndex++] & 255;
      }
      parse(det, spaceCh) {
        let b, ignoreSpace = false;
        this.spaceChar = spaceCh;
        while ((b = this.nextByte(det)) >= 0) {
          const mb = this.byteMap[b];
          if (mb != 0) {
            if (!(mb == this.spaceChar && ignoreSpace)) {
              this.addByte(mb);
            }
            ignoreSpace = mb == this.spaceChar;
          }
        }
        this.addByte(this.spaceChar);
        const rawPercent = this.hitCount / this.ngramCount;
        if (rawPercent > 0.33)
          return 98;
        return Math.floor(rawPercent * 300);
      }
    };
    var NGramsPlusLang = class {
      static {
        __name(this, "NGramsPlusLang");
      }
      constructor(la, ng) {
        this.fLang = la;
        this.fNGrams = ng;
      }
    };
    var isFlatNgrams = /* @__PURE__ */ __name((val) => Array.isArray(val) && isFinite(val[0]), "isFlatNgrams");
    var sbcs = class {
      static {
        __name(this, "sbcs");
      }
      constructor() {
        this.spaceChar = 32;
        this.nGramLang = void 0;
      }
      ngrams() {
        return [];
      }
      byteMap() {
        return [];
      }
      name(_input) {
        return "sbcs";
      }
      language() {
        return this.nGramLang;
      }
      match(det) {
        this.nGramLang = void 0;
        const ngrams = this.ngrams();
        if (isFlatNgrams(ngrams)) {
          const parser = new NGramParser(ngrams, this.byteMap());
          const confidence = parser.parse(det, this.spaceChar);
          return confidence <= 0 ? null : (0, match_1.default)(det, this, confidence);
        }
        let bestConfidence = -1;
        for (let i = ngrams.length - 1; i >= 0; i--) {
          const ngl = ngrams[i];
          const parser = new NGramParser(ngl.fNGrams, this.byteMap());
          const confidence = parser.parse(det, this.spaceChar);
          if (confidence > bestConfidence) {
            bestConfidence = confidence;
            this.nGramLang = ngl.fLang;
          }
        }
        return bestConfidence <= 0 ? null : (0, match_1.default)(det, this, bestConfidence);
      }
    };
    var ISO_8859_1 = class extends sbcs {
      static {
        __name(this, "ISO_8859_1");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          170,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          186,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255
        ];
      }
      ngrams() {
        return [
          new NGramsPlusLang("da", [
            2122086,
            2122100,
            2122853,
            2123118,
            2123122,
            2123375,
            2123873,
            2124064,
            2125157,
            2125671,
            2126053,
            2126697,
            2126708,
            2126953,
            2127465,
            6383136,
            6385184,
            6385252,
            6386208,
            6386720,
            6579488,
            6579566,
            6579570,
            6579572,
            6627443,
            6644768,
            6644837,
            6647328,
            6647396,
            6648352,
            6648421,
            6648608,
            6648864,
            6713202,
            6776096,
            6776174,
            6776178,
            6907749,
            6908960,
            6909543,
            7038240,
            7039845,
            7103858,
            7104871,
            7105637,
            7169380,
            7234661,
            7234848,
            7235360,
            7235429,
            7300896,
            7302432,
            7303712,
            7398688,
            7479396,
            7479397,
            7479411,
            7496992,
            7566437,
            7610483,
            7628064,
            7628146,
            7629164,
            7759218
          ]),
          new NGramsPlusLang("de", [
            2122094,
            2122101,
            2122341,
            2122849,
            2122853,
            2122857,
            2123113,
            2123621,
            2123873,
            2124142,
            2125161,
            2126691,
            2126693,
            2127214,
            2127461,
            2127471,
            2127717,
            2128501,
            6448498,
            6514720,
            6514789,
            6514804,
            6578547,
            6579566,
            6579570,
            6580581,
            6627428,
            6627443,
            6646126,
            6646132,
            6647328,
            6648352,
            6648608,
            6776174,
            6841710,
            6845472,
            6906728,
            6907168,
            6909472,
            6909541,
            6911008,
            7104867,
            7105637,
            7217249,
            7217252,
            7217267,
            7234592,
            7234661,
            7234848,
            7235360,
            7235429,
            7238757,
            7479396,
            7496805,
            7497065,
            7562088,
            7566437,
            7610468,
            7628064,
            7628142,
            7628146,
            7695972,
            7695975,
            7759218
          ]),
          new NGramsPlusLang("en", [
            2122016,
            2122094,
            2122341,
            2122607,
            2123375,
            2123873,
            2123877,
            2124142,
            2125153,
            2125670,
            2125938,
            2126437,
            2126689,
            2126708,
            2126952,
            2126959,
            2127720,
            6383972,
            6384672,
            6385184,
            6385252,
            6386464,
            6386720,
            6386789,
            6386793,
            6561889,
            6561908,
            6627425,
            6627443,
            6627444,
            6644768,
            6647412,
            6648352,
            6648608,
            6713202,
            6840692,
            6841632,
            6841714,
            6906912,
            6909472,
            6909543,
            6909806,
            6910752,
            7217249,
            7217268,
            7234592,
            7235360,
            7238688,
            7300640,
            7302688,
            7303712,
            7496992,
            7500576,
            7544929,
            7544948,
            7561577,
            7566368,
            7610484,
            7628146,
            7628897,
            7628901,
            7629167,
            7630624,
            7631648
          ]),
          new NGramsPlusLang("es", [
            2122016,
            2122593,
            2122607,
            2122853,
            2123116,
            2123118,
            2123123,
            2124142,
            2124897,
            2124911,
            2125921,
            2125935,
            2125938,
            2126197,
            2126437,
            2126693,
            2127214,
            2128160,
            6365283,
            6365284,
            6365285,
            6365292,
            6365296,
            6382441,
            6382703,
            6384672,
            6386208,
            6386464,
            6515187,
            6516590,
            6579488,
            6579564,
            6582048,
            6627428,
            6627429,
            6627436,
            6646816,
            6647328,
            6647412,
            6648608,
            6648692,
            6907246,
            6943598,
            7102752,
            7106419,
            7217253,
            7238757,
            7282788,
            7282789,
            7302688,
            7303712,
            7303968,
            7364978,
            7435621,
            7495968,
            7497075,
            7544932,
            7544933,
            7544944,
            7562528,
            7628064,
            7630624,
            7693600,
            15953440
          ]),
          new NGramsPlusLang("fr", [
            2122101,
            2122607,
            2122849,
            2122853,
            2122869,
            2123118,
            2123124,
            2124897,
            2124901,
            2125921,
            2125935,
            2125938,
            2126197,
            2126693,
            2126703,
            2127214,
            2154528,
            6385268,
            6386793,
            6513952,
            6516590,
            6579488,
            6579571,
            6583584,
            6627425,
            6627427,
            6627428,
            6627429,
            6627436,
            6627440,
            6627443,
            6647328,
            6647412,
            6648352,
            6648608,
            6648864,
            6649202,
            6909806,
            6910752,
            6911008,
            7102752,
            7103776,
            7103859,
            7169390,
            7217252,
            7234848,
            7238432,
            7238688,
            7302688,
            7302772,
            7304562,
            7435621,
            7479404,
            7496992,
            7544929,
            7544932,
            7544933,
            7544940,
            7544944,
            7610468,
            7628064,
            7629167,
            7693600,
            7696928
          ]),
          new NGramsPlusLang("it", [
            2122092,
            2122600,
            2122607,
            2122853,
            2122857,
            2123040,
            2124140,
            2124142,
            2124897,
            2125925,
            2125938,
            2127214,
            6365283,
            6365284,
            6365296,
            6365299,
            6386799,
            6514789,
            6516590,
            6579564,
            6580512,
            6627425,
            6627427,
            6627428,
            6627433,
            6627436,
            6627440,
            6627443,
            6646816,
            6646892,
            6647412,
            6648352,
            6841632,
            6889569,
            6889571,
            6889572,
            6889587,
            6906144,
            6908960,
            6909472,
            6909806,
            7102752,
            7103776,
            7104800,
            7105633,
            7234848,
            7235872,
            7237408,
            7238757,
            7282785,
            7282788,
            7282793,
            7282803,
            7302688,
            7302757,
            7366002,
            7495968,
            7496992,
            7563552,
            7627040,
            7628064,
            7629088,
            7630624,
            8022383
          ]),
          new NGramsPlusLang("nl", [
            2122092,
            2122341,
            2122849,
            2122853,
            2122857,
            2123109,
            2123118,
            2123621,
            2123877,
            2124142,
            2125153,
            2125157,
            2125680,
            2126949,
            2127457,
            2127461,
            2127471,
            2127717,
            2128489,
            6381934,
            6381938,
            6385184,
            6385252,
            6386208,
            6386720,
            6514804,
            6579488,
            6579566,
            6579570,
            6627426,
            6627446,
            6645102,
            6645106,
            6647328,
            6648352,
            6648435,
            6648864,
            6776174,
            6841716,
            6907168,
            6909472,
            6909543,
            6910752,
            7217250,
            7217252,
            7217253,
            7217256,
            7217263,
            7217270,
            7234661,
            7235360,
            7302756,
            7303026,
            7303200,
            7303712,
            7562088,
            7566437,
            7610468,
            7628064,
            7628142,
            7628146,
            7758190,
            7759218,
            7761775
          ]),
          new NGramsPlusLang("no", [
            2122100,
            2122102,
            2122853,
            2123118,
            2123122,
            2123375,
            2123873,
            2124064,
            2125157,
            2125671,
            2126053,
            2126693,
            2126699,
            2126703,
            2126708,
            2126953,
            2127465,
            2155808,
            6385252,
            6386208,
            6386720,
            6579488,
            6579566,
            6579572,
            6627443,
            6644768,
            6647328,
            6647397,
            6648352,
            6648421,
            6648864,
            6648948,
            6713202,
            6776174,
            6908779,
            6908960,
            6909543,
            7038240,
            7039845,
            7103776,
            7105637,
            7169380,
            7169390,
            7217267,
            7234848,
            7235360,
            7235429,
            7237221,
            7300896,
            7302432,
            7303712,
            7398688,
            7479411,
            7496992,
            7565165,
            7566437,
            7610483,
            7628064,
            7628142,
            7628146,
            7629164,
            7631904,
            7631973,
            7759218
          ]),
          new NGramsPlusLang("pt", [
            2122016,
            2122607,
            2122849,
            2122853,
            2122863,
            2123040,
            2123123,
            2125153,
            2125423,
            2125600,
            2125921,
            2125935,
            2125938,
            2126197,
            2126437,
            2126693,
            2127213,
            6365281,
            6365283,
            6365284,
            6365296,
            6382693,
            6382703,
            6384672,
            6386208,
            6386273,
            6386464,
            6516589,
            6516590,
            6578464,
            6579488,
            6582048,
            6582131,
            6627425,
            6627428,
            6647072,
            6647412,
            6648608,
            6648692,
            6906144,
            6906721,
            7169390,
            7238757,
            7238767,
            7282785,
            7282787,
            7282788,
            7282789,
            7282800,
            7303968,
            7364978,
            7435621,
            7495968,
            7497075,
            7544929,
            7544932,
            7544933,
            7544944,
            7566433,
            7628064,
            7630624,
            7693600,
            14905120,
            15197039
          ]),
          new NGramsPlusLang("sv", [
            2122100,
            2122102,
            2122853,
            2123118,
            2123510,
            2123873,
            2124064,
            2124142,
            2124655,
            2125157,
            2125667,
            2126053,
            2126699,
            2126703,
            2126708,
            2126953,
            2127457,
            2127465,
            2155634,
            6382693,
            6385184,
            6385252,
            6386208,
            6386804,
            6514720,
            6579488,
            6579566,
            6579570,
            6579572,
            6644768,
            6647328,
            6648352,
            6648864,
            6747762,
            6776174,
            6909036,
            6909543,
            7037216,
            7105568,
            7169380,
            7217267,
            7233824,
            7234661,
            7235360,
            7235429,
            7235950,
            7299944,
            7302432,
            7302688,
            7398688,
            7479393,
            7479411,
            7495968,
            7564129,
            7565165,
            7610483,
            7627040,
            7628064,
            7628146,
            7629164,
            7631904,
            7758194,
            14971424,
            16151072
          ])
        ];
      }
      name(input) {
        return input && input.c1Bytes ? "windows-1252" : "ISO-8859-1";
      }
    };
    exports.ISO_8859_1 = ISO_8859_1;
    var ISO_8859_2 = class extends sbcs {
      static {
        __name(this, "ISO_8859_2");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          177,
          32,
          179,
          32,
          181,
          182,
          32,
          32,
          185,
          186,
          187,
          188,
          32,
          190,
          191,
          32,
          177,
          32,
          179,
          32,
          181,
          182,
          183,
          32,
          185,
          186,
          187,
          188,
          32,
          190,
          191,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          32
        ];
      }
      ngrams() {
        return [
          new NGramsPlusLang("cs", [
            2122016,
            2122361,
            2122863,
            2124389,
            2125409,
            2125413,
            2125600,
            2125668,
            2125935,
            2125938,
            2126072,
            2126447,
            2126693,
            2126703,
            2126708,
            2126959,
            2127392,
            2127481,
            2128481,
            6365296,
            6513952,
            6514720,
            6627440,
            6627443,
            6627446,
            6647072,
            6647533,
            6844192,
            6844260,
            6910836,
            6972704,
            7042149,
            7103776,
            7104800,
            7233824,
            7268640,
            7269408,
            7269664,
            7282800,
            7300206,
            7301737,
            7304052,
            7304480,
            7304801,
            7368548,
            7368554,
            7369327,
            7403621,
            7562528,
            7565173,
            7566433,
            7566441,
            7566446,
            7628146,
            7630573,
            7630624,
            7676016,
            12477728,
            14773997,
            15296623,
            15540336,
            15540339,
            15559968,
            16278884
          ]),
          new NGramsPlusLang("hu", [
            2122016,
            2122106,
            2122341,
            2123111,
            2123116,
            2123365,
            2123873,
            2123887,
            2124147,
            2124645,
            2124649,
            2124790,
            2124901,
            2125153,
            2125157,
            2125161,
            2125413,
            2126714,
            2126949,
            2156915,
            6365281,
            6365291,
            6365293,
            6365299,
            6384416,
            6385184,
            6388256,
            6447470,
            6448494,
            6645625,
            6646560,
            6646816,
            6646885,
            6647072,
            6647328,
            6648421,
            6648864,
            6648933,
            6648948,
            6781216,
            6844263,
            6909556,
            6910752,
            7020641,
            7075450,
            7169383,
            7170414,
            7217249,
            7233899,
            7234923,
            7234925,
            7238688,
            7300985,
            7544929,
            7567973,
            7567988,
            7568097,
            7596391,
            7610465,
            7631904,
            7659891,
            8021362,
            14773792,
            15299360
          ]),
          new NGramsPlusLang("pl", [
            2122618,
            2122863,
            2124064,
            2124389,
            2124655,
            2125153,
            2125161,
            2125409,
            2125417,
            2125668,
            2125935,
            2125938,
            2126697,
            2127648,
            2127721,
            2127737,
            2128416,
            2128481,
            6365296,
            6365303,
            6385257,
            6514720,
            6519397,
            6519417,
            6582048,
            6584937,
            6627440,
            6627443,
            6627447,
            6627450,
            6645615,
            6646304,
            6647072,
            6647401,
            6778656,
            6906144,
            6907168,
            6907242,
            7037216,
            7039264,
            7039333,
            7170405,
            7233824,
            7235937,
            7235941,
            7282800,
            7305057,
            7305065,
            7368556,
            7369313,
            7369327,
            7369338,
            7502437,
            7502457,
            7563754,
            7564137,
            7566433,
            7825765,
            7955304,
            7957792,
            8021280,
            8022373,
            8026400,
            15955744
          ]),
          new NGramsPlusLang("ro", [
            2122016,
            2122083,
            2122593,
            2122597,
            2122607,
            2122613,
            2122853,
            2122857,
            2124897,
            2125153,
            2125925,
            2125938,
            2126693,
            2126819,
            2127214,
            2144873,
            2158190,
            6365283,
            6365284,
            6386277,
            6386720,
            6386789,
            6386976,
            6513010,
            6516590,
            6518048,
            6546208,
            6579488,
            6627425,
            6627427,
            6627428,
            6627440,
            6627443,
            6644e3,
            6646048,
            6646885,
            6647412,
            6648692,
            6889569,
            6889571,
            6889572,
            6889584,
            6907168,
            6908192,
            6909472,
            7102752,
            7103776,
            7106418,
            7107945,
            7234848,
            7238770,
            7303712,
            7365998,
            7496992,
            7497057,
            7501088,
            7594784,
            7628064,
            7631477,
            7660320,
            7694624,
            7695392,
            12216608,
            15625760
          ])
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1250" : "ISO-8859-2";
      }
    };
    exports.ISO_8859_2 = ISO_8859_2;
    var ISO_8859_5 = class extends sbcs {
      static {
        __name(this, "ISO_8859_5");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          32,
          254,
          255,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          32,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          32,
          254,
          255
        ];
      }
      ngrams() {
        return [
          2150944,
          2151134,
          2151646,
          2152400,
          2152480,
          2153168,
          2153182,
          2153936,
          2153941,
          2154193,
          2154462,
          2154464,
          2154704,
          2154974,
          2154978,
          2155230,
          2156514,
          2158050,
          13688280,
          13689580,
          13884960,
          14015468,
          14015960,
          14016994,
          14017056,
          14164191,
          14210336,
          14211104,
          14216992,
          14407133,
          14407712,
          14413021,
          14536736,
          14538016,
          14538965,
          14538991,
          14540320,
          14540498,
          14557394,
          14557407,
          14557409,
          14602784,
          14602960,
          14603230,
          14604576,
          14605292,
          14605344,
          14606818,
          14671579,
          14672085,
          14672088,
          14672094,
          14733522,
          14734804,
          14803664,
          14803666,
          14803672,
          14806816,
          14865883,
          14868e3,
          14868192,
          14871584,
          15196894,
          15459616
        ];
      }
      name() {
        return "ISO-8859-5";
      }
      language() {
        return "ru";
      }
    };
    exports.ISO_8859_5 = ISO_8859_5;
    var ISO_8859_6 = class extends sbcs {
      static {
        __name(this, "ISO_8859_6");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32
        ];
      }
      ngrams() {
        return [
          2148324,
          2148326,
          2148551,
          2152932,
          2154986,
          2155748,
          2156006,
          2156743,
          13050055,
          13091104,
          13093408,
          13095200,
          13100064,
          13100227,
          13100231,
          13100232,
          13100234,
          13100236,
          13100237,
          13100239,
          13100243,
          13100249,
          13100258,
          13100261,
          13100264,
          13100266,
          13100320,
          13100576,
          13100746,
          13115591,
          13181127,
          13181153,
          13181156,
          13181157,
          13181160,
          13246663,
          13574343,
          13617440,
          13705415,
          13748512,
          13836487,
          14229703,
          14279913,
          14805536,
          14950599,
          14993696,
          15001888,
          15002144,
          15016135,
          15058720,
          15059232,
          15066656,
          15081671,
          15147207,
          15189792,
          15255524,
          15263264,
          15278279,
          15343815,
          15343845,
          15343848,
          15386912,
          15388960,
          15394336
        ];
      }
      name() {
        return "ISO-8859-6";
      }
      language() {
        return "ar";
      }
    };
    exports.ISO_8859_6 = ISO_8859_6;
    var ISO_8859_7 = class extends sbcs {
      static {
        __name(this, "ISO_8859_7");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          161,
          162,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          220,
          32,
          221,
          222,
          223,
          32,
          252,
          32,
          253,
          254,
          192,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          32,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          32
        ];
      }
      ngrams() {
        return [
          2154989,
          2154992,
          2155497,
          2155753,
          2156016,
          2156320,
          2157281,
          2157797,
          2158049,
          2158368,
          2158817,
          2158831,
          2158833,
          2159604,
          2159605,
          2159847,
          2159855,
          14672160,
          14754017,
          14754036,
          14805280,
          14806304,
          14807292,
          14807584,
          14936545,
          15067424,
          15069728,
          15147252,
          15199520,
          15200800,
          15278324,
          15327520,
          15330014,
          15331872,
          15393257,
          15393268,
          15525152,
          15540449,
          15540453,
          15540464,
          15589664,
          15725088,
          15725856,
          15790069,
          15790575,
          15793184,
          15868129,
          15868133,
          15868138,
          15868144,
          15868148,
          15983904,
          15984416,
          15987951,
          16048416,
          16048617,
          16050157,
          16050162,
          16050666,
          16052e3,
          16052213,
          16054765,
          16379168,
          16706848
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1253" : "ISO-8859-7";
      }
      language() {
        return "el";
      }
    };
    exports.ISO_8859_7 = ISO_8859_7;
    var ISO_8859_8 = class extends sbcs {
      static {
        __name(this, "ISO_8859_8");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          32,
          32,
          32,
          32,
          32
        ];
      }
      ngrams() {
        return [
          new NGramsPlusLang("he", [
            2154725,
            2154727,
            2154729,
            2154746,
            2154985,
            2154990,
            2155744,
            2155749,
            2155753,
            2155758,
            2155762,
            2155769,
            2155770,
            2157792,
            2157796,
            2158304,
            2159340,
            2161132,
            14744096,
            14950624,
            14950625,
            14950628,
            14950636,
            14950638,
            14950649,
            15001056,
            15065120,
            15068448,
            15068960,
            15071264,
            15071776,
            15278308,
            15328288,
            15328762,
            15329773,
            15330592,
            15331104,
            15333408,
            15333920,
            15474912,
            15474916,
            15523872,
            15524896,
            15540448,
            15540449,
            15540452,
            15540460,
            15540462,
            15540473,
            15655968,
            15671524,
            15787040,
            15788320,
            15788525,
            15920160,
            16261348,
            16312813,
            16378912,
            16392416,
            16392417,
            16392420,
            16392428,
            16392430,
            16392441
          ]),
          new NGramsPlusLang("he", [
            2154725,
            2154732,
            2155753,
            2155756,
            2155758,
            2155760,
            2157040,
            2157810,
            2157817,
            2158053,
            2158057,
            2158565,
            2158569,
            2160869,
            2160873,
            2161376,
            2161381,
            2161385,
            14688484,
            14688492,
            14688493,
            14688506,
            14738464,
            14738916,
            14740512,
            14741024,
            14754020,
            14754029,
            14754042,
            14950628,
            14950633,
            14950636,
            14950637,
            14950639,
            14950648,
            14950650,
            15002656,
            15065120,
            15066144,
            15196192,
            15327264,
            15327520,
            15328288,
            15474916,
            15474925,
            15474938,
            15528480,
            15530272,
            15591913,
            15591920,
            15591928,
            15605988,
            15605997,
            15606010,
            15655200,
            15655968,
            15918112,
            16326884,
            16326893,
            16326906,
            16376864,
            16441376,
            16442400,
            16442857
          ])
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1255" : "ISO-8859-8";
      }
      language() {
        return "he";
      }
    };
    exports.ISO_8859_8 = ISO_8859_8;
    var ISO_8859_9 = class extends sbcs {
      static {
        __name(this, "ISO_8859_9");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          170,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          186,
          32,
          32,
          32,
          32,
          32,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          105,
          254,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          32,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255
        ];
      }
      ngrams() {
        return [
          2122337,
          2122345,
          2122357,
          2122849,
          2122853,
          2123621,
          2123873,
          2124140,
          2124641,
          2124655,
          2125153,
          2125676,
          2126689,
          2126945,
          2127461,
          2128225,
          6365282,
          6384416,
          6384737,
          6384993,
          6385184,
          6385405,
          6386208,
          6386273,
          6386429,
          6386685,
          6388065,
          6449522,
          6578464,
          6579488,
          6580512,
          6627426,
          6627435,
          6644841,
          6647328,
          6648352,
          6648425,
          6648681,
          6909029,
          6909472,
          6909545,
          6910496,
          7102830,
          7102834,
          7103776,
          7103858,
          7217249,
          7217250,
          7217259,
          7234657,
          7234661,
          7234848,
          7235872,
          7235950,
          7273760,
          7498094,
          7535982,
          7759136,
          7954720,
          7958386,
          16608800,
          16608868,
          16609021,
          16642301
        ];
      }
      name(det) {
        return det && det.c1Bytes ? "windows-1254" : "ISO-8859-9";
      }
      language() {
        return "tr";
      }
    };
    exports.ISO_8859_9 = ISO_8859_9;
    var windows_1251 = class extends sbcs {
      static {
        __name(this, "windows_1251");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          144,
          131,
          32,
          131,
          32,
          32,
          32,
          32,
          32,
          32,
          154,
          32,
          156,
          157,
          158,
          159,
          144,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          154,
          32,
          156,
          157,
          158,
          159,
          32,
          162,
          162,
          188,
          32,
          180,
          32,
          32,
          184,
          32,
          186,
          32,
          32,
          32,
          32,
          191,
          32,
          32,
          179,
          179,
          180,
          181,
          32,
          32,
          184,
          32,
          186,
          32,
          188,
          190,
          190,
          191,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          240,
          241,
          242,
          243,
          244,
          245,
          246,
          247,
          248,
          249,
          250,
          251,
          252,
          253,
          254,
          255
        ];
      }
      ngrams() {
        return [
          2155040,
          2155246,
          2155758,
          2156512,
          2156576,
          2157280,
          2157294,
          2158048,
          2158053,
          2158305,
          2158574,
          2158576,
          2158816,
          2159086,
          2159090,
          2159342,
          2160626,
          2162162,
          14740968,
          14742268,
          14937632,
          15068156,
          15068648,
          15069682,
          15069728,
          15212783,
          15263008,
          15263776,
          15269664,
          15459821,
          15460384,
          15465709,
          15589408,
          15590688,
          15591653,
          15591679,
          15592992,
          15593186,
          15605986,
          15605999,
          15606001,
          15655456,
          15655648,
          15655918,
          15657248,
          15657980,
          15658016,
          15659506,
          15724267,
          15724773,
          15724776,
          15724782,
          15786210,
          15787492,
          15856352,
          15856354,
          15856360,
          15859488,
          15918571,
          15920672,
          15920880,
          15924256,
          16249582,
          16512288
        ];
      }
      name() {
        return "windows-1251";
      }
      language() {
        return "ru";
      }
    };
    exports.windows_1251 = windows_1251;
    var windows_1256 = class extends sbcs {
      static {
        __name(this, "windows_1256");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          129,
          32,
          131,
          32,
          32,
          32,
          32,
          136,
          32,
          138,
          32,
          156,
          141,
          142,
          143,
          144,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          152,
          32,
          154,
          32,
          156,
          32,
          32,
          159,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          170,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          181,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          192,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          32,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          224,
          225,
          226,
          227,
          228,
          229,
          230,
          231,
          232,
          233,
          234,
          235,
          236,
          237,
          238,
          239,
          32,
          32,
          32,
          32,
          244,
          32,
          32,
          32,
          32,
          249,
          32,
          251,
          252,
          32,
          32,
          255
        ];
      }
      ngrams() {
        return [
          2148321,
          2148324,
          2148551,
          2153185,
          2153965,
          2154977,
          2155492,
          2156231,
          13050055,
          13091104,
          13093408,
          13095200,
          13099296,
          13099459,
          13099463,
          13099464,
          13099466,
          13099468,
          13099469,
          13099471,
          13099475,
          13099482,
          13099486,
          13099491,
          13099494,
          13099501,
          13099808,
          13100064,
          13100234,
          13115591,
          13181127,
          13181149,
          13181153,
          13181155,
          13181158,
          13246663,
          13574343,
          13617440,
          13705415,
          13748512,
          13836487,
          14295239,
          14344684,
          14544160,
          14753991,
          14797088,
          14806048,
          14806304,
          14885063,
          14927648,
          14928160,
          14935072,
          14950599,
          15016135,
          15058720,
          15124449,
          15131680,
          15474887,
          15540423,
          15540451,
          15540454,
          15583520,
          15585568,
          15590432
        ];
      }
      name() {
        return "windows-1256";
      }
      language() {
        return "ar";
      }
    };
    exports.windows_1256 = windows_1256;
    var KOI8_R = class extends sbcs {
      static {
        __name(this, "KOI8_R");
      }
      byteMap() {
        return [
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          0,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          97,
          98,
          99,
          100,
          101,
          102,
          103,
          104,
          105,
          106,
          107,
          108,
          109,
          110,
          111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120,
          121,
          122,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          163,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          163,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          32,
          192,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223,
          192,
          193,
          194,
          195,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          210,
          211,
          212,
          213,
          214,
          215,
          216,
          217,
          218,
          219,
          220,
          221,
          222,
          223
        ];
      }
      ngrams() {
        return [
          2147535,
          2148640,
          2149313,
          2149327,
          2150081,
          2150085,
          2150338,
          2150607,
          2150610,
          2151105,
          2151375,
          2151380,
          2151631,
          2152224,
          2152399,
          2153153,
          2153684,
          2154196,
          12701385,
          12702936,
          12963032,
          12963529,
          12964820,
          12964896,
          13094688,
          13181136,
          13223200,
          13224224,
          13226272,
          13419982,
          13420832,
          13424846,
          13549856,
          13550880,
          13552069,
          13552081,
          13553440,
          13553623,
          13574352,
          13574355,
          13574359,
          13617103,
          13617696,
          13618392,
          13618464,
          13620180,
          13621024,
          13621185,
          13684684,
          13685445,
          13685449,
          13685455,
          13812183,
          13813188,
          13881632,
          13882561,
          13882569,
          13882583,
          13944268,
          13946656,
          13946834,
          13948960,
          14272544,
          14603471
        ];
      }
      name() {
        return "KOI8-R";
      }
      language() {
        return "ru";
      }
    };
    exports.KOI8_R = KOI8_R;
  }
});

// node_modules/chardet/lib/encoding/iso2022.js
var require_iso2022 = __commonJS({
  "node_modules/chardet/lib/encoding/iso2022.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ISO_2022_CN = exports.ISO_2022_KR = exports.ISO_2022_JP = void 0;
    var match_1 = __importDefault(require_match());
    var ISO_2022 = class {
      static {
        __name(this, "ISO_2022");
      }
      constructor() {
        this.escapeSequences = [];
      }
      name() {
        return "ISO_2022";
      }
      match(det) {
        let i, j;
        let escN;
        let hits = 0;
        let misses = 0;
        let shifts = 0;
        let confidence;
        const text = det.inputBytes;
        const textLen = det.inputLen;
        scanInput: for (i = 0; i < textLen; i++) {
          if (text[i] == 27) {
            checkEscapes: for (escN = 0; escN < this.escapeSequences.length; escN++) {
              const seq = this.escapeSequences[escN];
              if (textLen - i < seq.length)
                continue checkEscapes;
              for (j = 1; j < seq.length; j++)
                if (seq[j] != text[i + j])
                  continue checkEscapes;
              hits++;
              i += seq.length - 1;
              continue scanInput;
            }
            misses++;
          }
          if (text[i] == 14 || text[i] == 15)
            shifts++;
        }
        if (hits == 0)
          return null;
        confidence = (100 * hits - 100 * misses) / (hits + misses);
        if (hits + shifts < 5)
          confidence -= (5 - (hits + shifts)) * 10;
        return confidence <= 0 ? null : (0, match_1.default)(det, this, confidence);
      }
    };
    var ISO_2022_JP = class extends ISO_2022 {
      static {
        __name(this, "ISO_2022_JP");
      }
      constructor() {
        super(...arguments);
        this.escapeSequences = [
          [27, 36, 40, 67],
          [27, 36, 40, 68],
          [27, 36, 64],
          [27, 36, 65],
          [27, 36, 66],
          [27, 38, 64],
          [27, 40, 66],
          [27, 40, 72],
          [27, 40, 73],
          [27, 40, 74],
          [27, 46, 65],
          [27, 46, 70]
        ];
      }
      name() {
        return "ISO-2022-JP";
      }
      language() {
        return "ja";
      }
    };
    exports.ISO_2022_JP = ISO_2022_JP;
    var ISO_2022_KR = class extends ISO_2022 {
      static {
        __name(this, "ISO_2022_KR");
      }
      constructor() {
        super(...arguments);
        this.escapeSequences = [[27, 36, 41, 67]];
      }
      name() {
        return "ISO-2022-KR";
      }
      language() {
        return "kr";
      }
    };
    exports.ISO_2022_KR = ISO_2022_KR;
    var ISO_2022_CN = class extends ISO_2022 {
      static {
        __name(this, "ISO_2022_CN");
      }
      constructor() {
        super(...arguments);
        this.escapeSequences = [
          [27, 36, 41, 65],
          [27, 36, 41, 71],
          [27, 36, 42, 72],
          [27, 36, 41, 69],
          [27, 36, 43, 73],
          [27, 36, 43, 74],
          [27, 36, 43, 75],
          [27, 36, 43, 76],
          [27, 36, 43, 77],
          [27, 78],
          [27, 79]
        ];
      }
      name() {
        return "ISO-2022-CN";
      }
      language() {
        return "zh";
      }
    };
    exports.ISO_2022_CN = ISO_2022_CN;
  }
});

// node_modules/chardet/lib/utils.js
var require_utils = __commonJS({
  "node_modules/chardet/lib/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isByteArray = void 0;
    var isByteArray = /* @__PURE__ */ __name((input) => {
      if (input == null || typeof input != "object")
        return false;
      return isFinite(input.length) && input.length >= 0;
    }, "isByteArray");
    exports.isByteArray = isByteArray;
  }
});

// node_modules/chardet/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/chardet/lib/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
      var ownKeys = /* @__PURE__ */ __name(function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      }, "ownKeys");
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    }();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.detectFileSync = exports.detectFile = exports.analyse = exports.detect = void 0;
    var node_1 = __importDefault(require_node());
    var ascii_1 = __importDefault(require_ascii());
    var utf8_1 = __importDefault(require_utf8());
    var unicode = __importStar(require_unicode());
    var mbcs = __importStar(require_mbcs());
    var sbcs = __importStar(require_sbcs());
    var iso2022 = __importStar(require_iso2022());
    var utils_1 = require_utils();
    var recognisers = [
      new utf8_1.default(),
      new unicode.UTF_16BE(),
      new unicode.UTF_16LE(),
      new unicode.UTF_32BE(),
      new unicode.UTF_32LE(),
      new mbcs.sjis(),
      new mbcs.big5(),
      new mbcs.euc_jp(),
      new mbcs.euc_kr(),
      new mbcs.gb_18030(),
      new iso2022.ISO_2022_JP(),
      new iso2022.ISO_2022_KR(),
      new iso2022.ISO_2022_CN(),
      new sbcs.ISO_8859_1(),
      new sbcs.ISO_8859_2(),
      new sbcs.ISO_8859_5(),
      new sbcs.ISO_8859_6(),
      new sbcs.ISO_8859_7(),
      new sbcs.ISO_8859_8(),
      new sbcs.ISO_8859_9(),
      new sbcs.windows_1251(),
      new sbcs.windows_1256(),
      new sbcs.KOI8_R(),
      new ascii_1.default()
    ];
    var detect = /* @__PURE__ */ __name((buffer) => {
      const matches = (0, exports.analyse)(buffer);
      return matches.length > 0 ? matches[0].name : null;
    }, "detect");
    exports.detect = detect;
    var analyse = /* @__PURE__ */ __name((buffer) => {
      if (!(0, utils_1.isByteArray)(buffer)) {
        throw new Error("Input must be a byte array, e.g. Buffer or Uint8Array");
      }
      const byteStats = [];
      for (let i = 0; i < 256; i++)
        byteStats[i] = 0;
      for (let i = buffer.length - 1; i >= 0; i--)
        byteStats[buffer[i] & 255]++;
      let c1Bytes = false;
      for (let i = 128; i <= 159; i += 1) {
        if (byteStats[i] !== 0) {
          c1Bytes = true;
          break;
        }
      }
      const context2 = {
        byteStats,
        c1Bytes,
        rawInput: buffer,
        rawLen: buffer.length,
        inputBytes: buffer,
        inputLen: buffer.length
      };
      const matches = recognisers.map((rec) => {
        return rec.match(context2);
      }).filter((match) => {
        return !!match;
      }).sort((a, b) => {
        return b.confidence - a.confidence;
      });
      return matches;
    }, "analyse");
    exports.analyse = analyse;
    var detectFile = /* @__PURE__ */ __name((filepath, opts = {}) => new Promise((resolve2, reject) => {
      let fd;
      const fs9 = (0, node_1.default)();
      const handler = /* @__PURE__ */ __name((err, buffer) => {
        if (fd) {
          fs9.closeSync(fd);
        }
        if (err) {
          reject(err);
        } else {
          resolve2((0, exports.detect)(buffer));
        }
      }, "handler");
      if (opts && opts.sampleSize) {
        fd = fs9.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs9.read(fd, sample, 0, opts.sampleSize, opts.offset, (err) => {
          handler(err, sample);
        });
        return;
      }
      fs9.readFile(filepath, handler);
    }), "detectFile");
    exports.detectFile = detectFile;
    var detectFileSync = /* @__PURE__ */ __name((filepath, opts = {}) => {
      const fs9 = (0, node_1.default)();
      if (opts && opts.sampleSize) {
        const fd = fs9.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs9.readSync(fd, sample, 0, opts.sampleSize, opts.offset);
        fs9.closeSync(fd);
        return (0, exports.detect)(sample);
      }
      return (0, exports.detect)(fs9.readFileSync(filepath));
    }, "detectFileSync");
    exports.detectFileSync = detectFileSync;
    exports.default = {
      analyse: exports.analyse,
      detect: exports.detect,
      detectFileSync: exports.detectFileSync,
      detectFile: exports.detectFile
    };
  }
});

// node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js
var require_LogRecord = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SeverityNumber = void 0;
    var SeverityNumber;
    (function(SeverityNumber2) {
      SeverityNumber2[SeverityNumber2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
      SeverityNumber2[SeverityNumber2["TRACE"] = 1] = "TRACE";
      SeverityNumber2[SeverityNumber2["TRACE2"] = 2] = "TRACE2";
      SeverityNumber2[SeverityNumber2["TRACE3"] = 3] = "TRACE3";
      SeverityNumber2[SeverityNumber2["TRACE4"] = 4] = "TRACE4";
      SeverityNumber2[SeverityNumber2["DEBUG"] = 5] = "DEBUG";
      SeverityNumber2[SeverityNumber2["DEBUG2"] = 6] = "DEBUG2";
      SeverityNumber2[SeverityNumber2["DEBUG3"] = 7] = "DEBUG3";
      SeverityNumber2[SeverityNumber2["DEBUG4"] = 8] = "DEBUG4";
      SeverityNumber2[SeverityNumber2["INFO"] = 9] = "INFO";
      SeverityNumber2[SeverityNumber2["INFO2"] = 10] = "INFO2";
      SeverityNumber2[SeverityNumber2["INFO3"] = 11] = "INFO3";
      SeverityNumber2[SeverityNumber2["INFO4"] = 12] = "INFO4";
      SeverityNumber2[SeverityNumber2["WARN"] = 13] = "WARN";
      SeverityNumber2[SeverityNumber2["WARN2"] = 14] = "WARN2";
      SeverityNumber2[SeverityNumber2["WARN3"] = 15] = "WARN3";
      SeverityNumber2[SeverityNumber2["WARN4"] = 16] = "WARN4";
      SeverityNumber2[SeverityNumber2["ERROR"] = 17] = "ERROR";
      SeverityNumber2[SeverityNumber2["ERROR2"] = 18] = "ERROR2";
      SeverityNumber2[SeverityNumber2["ERROR3"] = 19] = "ERROR3";
      SeverityNumber2[SeverityNumber2["ERROR4"] = 20] = "ERROR4";
      SeverityNumber2[SeverityNumber2["FATAL"] = 21] = "FATAL";
      SeverityNumber2[SeverityNumber2["FATAL2"] = 22] = "FATAL2";
      SeverityNumber2[SeverityNumber2["FATAL3"] = 23] = "FATAL3";
      SeverityNumber2[SeverityNumber2["FATAL4"] = 24] = "FATAL4";
    })(SeverityNumber = exports.SeverityNumber || (exports.SeverityNumber = {}));
  }
});

// node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js
var require_NoopLogger = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NOOP_LOGGER = exports.NoopLogger = void 0;
    var NoopLogger = class {
      static {
        __name(this, "NoopLogger");
      }
      emit(_logRecord) {
      }
    };
    exports.NoopLogger = NoopLogger;
    exports.NOOP_LOGGER = new NoopLogger();
  }
});

// node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js
var require_NoopLoggerProvider = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NOOP_LOGGER_PROVIDER = exports.NoopLoggerProvider = void 0;
    var NoopLogger_1 = require_NoopLogger();
    var NoopLoggerProvider = class {
      static {
        __name(this, "NoopLoggerProvider");
      }
      getLogger(_name, _version, _options) {
        return new NoopLogger_1.NoopLogger();
      }
    };
    exports.NoopLoggerProvider = NoopLoggerProvider;
    exports.NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();
  }
});

// node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js
var require_ProxyLogger = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProxyLogger = void 0;
    var NoopLogger_1 = require_NoopLogger();
    var ProxyLogger = class {
      static {
        __name(this, "ProxyLogger");
      }
      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);
      }
      /**
       * 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;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js
var require_ProxyLoggerProvider = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProxyLoggerProvider = void 0;
    var NoopLoggerProvider_1 = require_NoopLoggerProvider();
    var ProxyLogger_1 = require_ProxyLogger();
    var ProxyLoggerProvider = class {
      static {
        __name(this, "ProxyLoggerProvider");
      }
      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);
      }
      getDelegate() {
        var _a;
        return (_a = this._delegate) !== null && _a !== void 0 ? _a : NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER;
      }
      /**
       * Set the delegate logger provider
       */
      setDelegate(delegate) {
        this._delegate = delegate;
      }
      getDelegateLogger(name, version, options) {
        var _a;
        return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getLogger(name, version, options);
      }
    };
    exports.ProxyLoggerProvider = ProxyLoggerProvider;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js
var require_globalThis = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports._globalThis = void 0;
    exports._globalThis = typeof globalThis === "object" ? globalThis : globalThis;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js
var require_node2 = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports._globalThis = void 0;
    var globalThis_1 = require_globalThis();
    Object.defineProperty(exports, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return globalThis_1._globalThis;
    }, "get") });
  }
});

// node_modules/@opentelemetry/api-logs/build/src/platform/index.js
var require_platform = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports._globalThis = void 0;
    var node_1 = require_node2();
    Object.defineProperty(exports, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1._globalThis;
    }, "get") });
  }
});

// node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js
var require_global_utils = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.API_BACKWARDS_COMPATIBILITY_VERSION = exports.makeGetter = exports._global = exports.GLOBAL_LOGS_API_KEY = void 0;
    var platform_1 = require_platform();
    exports.GLOBAL_LOGS_API_KEY = Symbol.for("io.opentelemetry.js.api.logs");
    exports._global = platform_1._globalThis;
    function makeGetter(requiredVersion, instance, fallback) {
      return (version) => version === requiredVersion ? instance : fallback;
    }
    __name(makeGetter, "makeGetter");
    exports.makeGetter = makeGetter;
    exports.API_BACKWARDS_COMPATIBILITY_VERSION = 1;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/api/logs.js
var require_logs = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/api/logs.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LogsAPI = void 0;
    var global_utils_1 = require_global_utils();
    var NoopLoggerProvider_1 = require_NoopLoggerProvider();
    var ProxyLoggerProvider_1 = require_ProxyLoggerProvider();
    var LogsAPI = class _LogsAPI {
      static {
        __name(this, "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 from the global logger provider.
       *
       * @returns 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;
  }
});

// node_modules/@opentelemetry/api-logs/build/src/index.js
var require_src2 = __commonJS({
  "node_modules/@opentelemetry/api-logs/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.logs = exports.ProxyLoggerProvider = exports.ProxyLogger = exports.NoopLoggerProvider = exports.NOOP_LOGGER_PROVIDER = exports.NoopLogger = exports.NOOP_LOGGER = exports.SeverityNumber = void 0;
    var LogRecord_1 = require_LogRecord();
    Object.defineProperty(exports, "SeverityNumber", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LogRecord_1.SeverityNumber;
    }, "get") });
    var NoopLogger_1 = require_NoopLogger();
    Object.defineProperty(exports, "NOOP_LOGGER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLogger_1.NOOP_LOGGER;
    }, "get") });
    Object.defineProperty(exports, "NoopLogger", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLogger_1.NoopLogger;
    }, "get") });
    var NoopLoggerProvider_1 = require_NoopLoggerProvider();
    Object.defineProperty(exports, "NOOP_LOGGER_PROVIDER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER;
    }, "get") });
    Object.defineProperty(exports, "NoopLoggerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLoggerProvider_1.NoopLoggerProvider;
    }, "get") });
    var ProxyLogger_1 = require_ProxyLogger();
    Object.defineProperty(exports, "ProxyLogger", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ProxyLogger_1.ProxyLogger;
    }, "get") });
    var ProxyLoggerProvider_1 = require_ProxyLoggerProvider();
    Object.defineProperty(exports, "ProxyLoggerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ProxyLoggerProvider_1.ProxyLoggerProvider;
    }, "get") });
    var logs_1 = require_logs();
    exports.logs = logs_1.LogsAPI.getInstance();
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.js
// @__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 = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.js"() {
    init_esbuild_shims();
    __name(createConstMap, "createConstMap");
  }
});

// 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 = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js"() {
    init_esbuild_shims();
    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
    ]);
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js
var init_trace = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js"() {
    init_esbuild_shims();
    init_SemanticAttributes();
  }
});

// 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 = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js"() {
    init_esbuild_shims();
    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
    ]);
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js
var init_resource = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js"() {
    init_esbuild_shims();
    init_SemanticResourceAttributes();
  }
});

// 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_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_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_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, 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, 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_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_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, ATTR_SERVER_PORT, ATTR_SERVICE_NAME, 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_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_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 = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js"() {
    init_esbuild_shims();
    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_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_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_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 = "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 = /* @__PURE__ */ __name((key) => `http.request.header.${key}`, "ATTR_HTTP_REQUEST_HEADER");
    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 = /* @__PURE__ */ __name((key) => `http.response.header.${key}`, "ATTR_HTTP_RESPONSE_HEADER");
    ATTR_HTTP_RESPONSE_STATUS_CODE = "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_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_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 = "server.address";
    ATTR_SERVER_PORT = "server.port";
    ATTR_SERVICE_NAME = "service.name";
    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_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_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";
  }
});

// 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 = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.js"() {
    init_esbuild_shims();
    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";
  }
});

// node_modules/@opentelemetry/semantic-conventions/build/esm/index.js
var esm_exports2 = {};
__export(esm_exports2, {
  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_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_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_DOTNET_GC_HEAP_GENERATION: () => ATTR_DOTNET_GC_HEAP_GENERATION,
  ATTR_ERROR_TYPE: () => ATTR_ERROR_TYPE,
  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,
  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_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_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,
  ATTR_SERVER_PORT: () => ATTR_SERVER_PORT,
  ATTR_SERVICE_NAME: () => ATTR_SERVICE_NAME,
  ATTR_SERVICE_VERSION: () => ATTR_SERVICE_VERSION,
  ATTR_SIGNALR_CONNECTION_STATUS: () => ATTR_SIGNALR_CONNECTION_STATUS,
  ATTR_SIGNALR_TRANSPORT: () => ATTR_SIGNALR_TRANSPORT,
  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: () => AWSECSLAUNCHTYPEVALUES_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: () => CLOUDPROVIDERVALUES_AWS,
  CLOUDPROVIDERVALUES_AZURE: () => CLOUDPROVIDERVALUES_AZURE,
  CLOUDPROVIDERVALUES_GCP: () => CLOUDPROVIDERVALUES_GCP,
  CloudPlatformValues: () => CloudPlatformValues,
  CloudProviderValues: () => CloudProviderValues,
  DBCASSANDRACONSISTENCYLEVELVALUES_ALL: () => DBCASSANDRACONSISTENCYLEVELVALUES_ALL,
  DBCASSANDRACONSISTENCYLEVELVALUES_ANY: () => DBCASSANDRACONSISTENCYLEVELVALUES_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: () => DBCASSANDRACONSISTENCYLEVELVALUES_ONE,
  DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM: () => DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,
  DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL: () => DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,
  DBCASSANDRACONSISTENCYLEVELVALUES_THREE: () => DBCASSANDRACONSISTENCYLEVELVALUES_THREE,
  DBCASSANDRACONSISTENCYLEVELVALUES_TWO: () => DBCASSANDRACONSISTENCYLEVELVALUES_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: () => DBSYSTEMVALUES_DB2,
  DBSYSTEMVALUES_DERBY: () => DBSYSTEMVALUES_DERBY,
  DBSYSTEMVALUES_DYNAMODB: () => DBSYSTEMVALUES_DYNAMODB,
  DBSYSTEMVALUES_EDB: () => DBSYSTEMVALUES_EDB,
  DBSYSTEMVALUES_ELASTICSEARCH: () => DBSYSTEMVALUES_ELASTICSEARCH,
  DBSYSTEMVALUES_FILEMAKER: () => DBSYSTEMVALUES_FILEMAKER,
  DBSYSTEMVALUES_FIREBIRD: () => DBSYSTEMVALUES_FIREBIRD,
  DBSYSTEMVALUES_FIRSTSQL: () => DBSYSTEMVALUES_FIRSTSQL,
  DBSYSTEMVALUES_GEODE: () => DBSYSTEMVALUES_GEODE,
  DBSYSTEMVALUES_H2: () => DBSYSTEMVALUES_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,
  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: () => DOTNET_GC_HEAP_GENERATION_VALUE_LOH,
  DOTNET_GC_HEAP_GENERATION_VALUE_POH: () => DOTNET_GC_HEAP_GENERATION_VALUE_POH,
  DbCassandraConsistencyLevelValues: () => DbCassandraConsistencyLevelValues,
  DbSystemValues: () => DbSystemValues,
  ERROR_TYPE_VALUE_OTHER: () => ERROR_TYPE_VALUE_OTHER,
  FAASDOCUMENTOPERATIONVALUES_DELETE: () => FAASDOCUMENTOPERATIONVALUES_DELETE,
  FAASDOCUMENTOPERATIONVALUES_EDIT: () => FAASDOCUMENTOPERATIONVALUES_EDIT,
  FAASDOCUMENTOPERATIONVALUES_INSERT: () => FAASDOCUMENTOPERATIONVALUES_INSERT,
  FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD: () => FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,
  FAASINVOKEDPROVIDERVALUES_AWS: () => FAASINVOKEDPROVIDERVALUES_AWS,
  FAASINVOKEDPROVIDERVALUES_AZURE: () => FAASINVOKEDPROVIDERVALUES_AZURE,
  FAASINVOKEDPROVIDERVALUES_GCP: () => FAASINVOKEDPROVIDERVALUES_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: () => HOSTARCHVALUES_X86,
  HTTPFLAVORVALUES_HTTP_1_0: () => HTTPFLAVORVALUES_HTTP_1_0,
  HTTPFLAVORVALUES_HTTP_1_1: () => HTTPFLAVORVALUES_HTTP_1_1,
  HTTPFLAVORVALUES_HTTP_2_0: () => HTTPFLAVORVALUES_HTTP_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: () => HTTP_REQUEST_METHOD_VALUE_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: () => HTTP_REQUEST_METHOD_VALUE_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: () => JVM_THREAD_STATE_VALUE_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: () => NETHOSTCONNECTIONSUBTYPEVALUES_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: () => NETHOSTCONNECTIONSUBTYPEVALUES_LTE,
  NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA: () => NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,
  NETHOSTCONNECTIONSUBTYPEVALUES_NR: () => NETHOSTCONNECTIONSUBTYPEVALUES_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: () => NETTRANSPORTVALUES_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: () => NETWORK_TRANSPORT_VALUE_TCP,
  NETWORK_TRANSPORT_VALUE_UDP: () => NETWORK_TRANSPORT_VALUE_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: () => OSTYPEVALUES_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: () => OTEL_STATUS_CODE_VALUE_OK,
  OsTypeValues: () => OsTypeValues,
  RPCGRPCSTATUSCODEVALUES_ABORTED: () => RPCGRPCSTATUSCODEVALUES_ABORTED,
  RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS: () => RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,
  RPCGRPCSTATUSCODEVALUES_CANCELLED: () => RPCGRPCSTATUSCODEVALUES_CANCELLED,
  RPCGRPCSTATUSCODEVALUES_DATA_LOSS: () => RPCGRPCSTATUSCODEVALUES_DATA_LOSS,
  RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED: () => RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,
  RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION: () => RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,
  RPCGRPCSTATUSCODEVALUES_INTERNAL: () => RPCGRPCSTATUSCODEVALUES_INTERNAL,
  RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT: () => RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,
  RPCGRPCSTATUSCODEVALUES_NOT_FOUND: () => RPCGRPCSTATUSCODEVALUES_NOT_FOUND,
  RPCGRPCSTATUSCODEVALUES_OK: () => RPCGRPCSTATUSCODEVALUES_OK,
  RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE: () => RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,
  RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED: () => RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,
  RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED: () => RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,
  RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED: () => RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,
  RPCGRPCSTATUSCODEVALUES_UNAVAILABLE: () => RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,
  RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED: () => RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,
  RPCGRPCSTATUSCODEVALUES_UNKNOWN: () => RPCGRPCSTATUSCODEVALUES_UNKNOWN,
  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: () => TELEMETRYSDKLANGUAGEVALUES_CPP,
  TELEMETRYSDKLANGUAGEVALUES_DOTNET: () => TELEMETRYSDKLANGUAGEVALUES_DOTNET,
  TELEMETRYSDKLANGUAGEVALUES_ERLANG: () => TELEMETRYSDKLANGUAGEVALUES_ERLANG,
  TELEMETRYSDKLANGUAGEVALUES_GO: () => TELEMETRYSDKLANGUAGEVALUES_GO,
  TELEMETRYSDKLANGUAGEVALUES_JAVA: () => TELEMETRYSDKLANGUAGEVALUES_JAVA,
  TELEMETRYSDKLANGUAGEVALUES_NODEJS: () => TELEMETRYSDKLANGUAGEVALUES_NODEJS,
  TELEMETRYSDKLANGUAGEVALUES_PHP: () => TELEMETRYSDKLANGUAGEVALUES_PHP,
  TELEMETRYSDKLANGUAGEVALUES_PYTHON: () => TELEMETRYSDKLANGUAGEVALUES_PYTHON,
  TELEMETRYSDKLANGUAGEVALUES_RUBY: () => TELEMETRYSDKLANGUAGEVALUES_RUBY,
  TELEMETRYSDKLANGUAGEVALUES_WEBJS: () => TELEMETRYSDKLANGUAGEVALUES_WEBJS,
  TELEMETRY_SDK_LANGUAGE_VALUE_CPP: () => TELEMETRY_SDK_LANGUAGE_VALUE_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: () => TELEMETRY_SDK_LANGUAGE_VALUE_GO,
  TELEMETRY_SDK_LANGUAGE_VALUE_JAVA: () => TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,
  TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS: () => TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
  TELEMETRY_SDK_LANGUAGE_VALUE_PHP: () => TELEMETRY_SDK_LANGUAGE_VALUE_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_esm2 = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/index.js"() {
    init_esbuild_shims();
    init_trace();
    init_resource();
    init_stable_attributes();
    init_stable_metrics();
  }
});

// node_modules/mnemonist/utils/comparators.js
var require_comparators = __commonJS({
  "node_modules/mnemonist/utils/comparators.js"(exports) {
    init_esbuild_shims();
    var DEFAULT_COMPARATOR = /* @__PURE__ */ __name(function(a, b) {
      if (a < b)
        return -1;
      if (a > b)
        return 1;
      return 0;
    }, "DEFAULT_COMPARATOR");
    var DEFAULT_REVERSE_COMPARATOR = /* @__PURE__ */ __name(function(a, b) {
      if (a < b)
        return 1;
      if (a > b)
        return -1;
      return 0;
    }, "DEFAULT_REVERSE_COMPARATOR");
    function reverseComparator(comparator) {
      return function(a, b) {
        return comparator(b, a);
      };
    }
    __name(reverseComparator, "reverseComparator");
    function createTupleComparator(size) {
      if (size === 2) {
        return function(a, b) {
          if (a[0] < b[0])
            return -1;
          if (a[0] > b[0])
            return 1;
          if (a[1] < b[1])
            return -1;
          if (a[1] > b[1])
            return 1;
          return 0;
        };
      }
      return function(a, b) {
        var i = 0;
        while (i < size) {
          if (a[i] < b[i])
            return -1;
          if (a[i] > b[i])
            return 1;
          i++;
        }
        return 0;
      };
    }
    __name(createTupleComparator, "createTupleComparator");
    exports.DEFAULT_COMPARATOR = DEFAULT_COMPARATOR;
    exports.DEFAULT_REVERSE_COMPARATOR = DEFAULT_REVERSE_COMPARATOR;
    exports.reverseComparator = reverseComparator;
    exports.createTupleComparator = createTupleComparator;
  }
});

// node_modules/obliterator/support.js
var require_support = __commonJS({
  "node_modules/obliterator/support.js"(exports) {
    init_esbuild_shims();
    exports.ARRAY_BUFFER_SUPPORT = typeof ArrayBuffer !== "undefined";
    exports.SYMBOL_SUPPORT = typeof Symbol !== "undefined";
  }
});

// node_modules/obliterator/foreach.js
var require_foreach = __commonJS({
  "node_modules/obliterator/foreach.js"(exports, module) {
    init_esbuild_shims();
    var support = require_support();
    var ARRAY_BUFFER_SUPPORT = support.ARRAY_BUFFER_SUPPORT;
    var SYMBOL_SUPPORT = support.SYMBOL_SUPPORT;
    module.exports = /* @__PURE__ */ __name(function forEach(iterable, callback) {
      var iterator, k, i, l, s;
      if (!iterable) throw new Error("obliterator/forEach: invalid iterable.");
      if (typeof callback !== "function")
        throw new Error("obliterator/forEach: expecting a callback.");
      if (Array.isArray(iterable) || ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable) || typeof iterable === "string" || iterable.toString() === "[object Arguments]") {
        for (i = 0, l = iterable.length; i < l; i++) callback(iterable[i], i);
        return;
      }
      if (typeof iterable.forEach === "function") {
        iterable.forEach(callback);
        return;
      }
      if (SYMBOL_SUPPORT && Symbol.iterator in iterable && typeof iterable.next !== "function") {
        iterable = iterable[Symbol.iterator]();
      }
      if (typeof iterable.next === "function") {
        iterator = iterable;
        i = 0;
        while (s = iterator.next(), s.done !== true) {
          callback(s.value, i);
          i++;
        }
        return;
      }
      for (k in iterable) {
        if (iterable.hasOwnProperty(k)) {
          callback(iterable[k], k);
        }
      }
      return;
    }, "forEach");
  }
});

// node_modules/mnemonist/fibonacci-heap.js
var require_fibonacci_heap = __commonJS({
  "node_modules/mnemonist/fibonacci-heap.js"(exports, module) {
    init_esbuild_shims();
    var comparators = require_comparators();
    var forEach = require_foreach();
    var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR;
    var reverseComparator = comparators.reverseComparator;
    function FibonacciHeap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/FibonacciHeap.constructor: given comparator should be a function.");
    }
    __name(FibonacciHeap2, "FibonacciHeap");
    FibonacciHeap2.prototype.clear = function() {
      this.root = null;
      this.min = null;
      this.size = 0;
    };
    function createNode(item) {
      return {
        item,
        degree: 0
      };
    }
    __name(createNode, "createNode");
    function mergeWithRoot(heap, node) {
      if (!heap.root) {
        heap.root = node;
      } else {
        node.right = heap.root.right;
        node.left = heap.root;
        heap.root.right.left = node;
        heap.root.right = node;
      }
    }
    __name(mergeWithRoot, "mergeWithRoot");
    FibonacciHeap2.prototype.push = function(item) {
      var node = createNode(item);
      node.left = node;
      node.right = node;
      mergeWithRoot(this, node);
      if (!this.min || this.comparator(node.item, this.min.item) <= 0)
        this.min = node;
      return ++this.size;
    };
    FibonacciHeap2.prototype.peek = function() {
      return this.min ? this.min.item : void 0;
    };
    function consumeLinkedList(head) {
      var nodes = [], node = head, flag = false;
      while (true) {
        if (node === head && flag)
          break;
        else if (node === head)
          flag = true;
        nodes.push(node);
        node = node.right;
      }
      return nodes;
    }
    __name(consumeLinkedList, "consumeLinkedList");
    function removeFromRoot(heap, node) {
      if (heap.root === node)
        heap.root = node.right;
      node.left.right = node.right;
      node.right.left = node.left;
    }
    __name(removeFromRoot, "removeFromRoot");
    function mergeWithChild(parent, node) {
      if (!parent.child) {
        parent.child = node;
      } else {
        node.right = parent.child.right;
        node.left = parent.child;
        parent.child.right.left = node;
        parent.child.right = node;
      }
    }
    __name(mergeWithChild, "mergeWithChild");
    function link(heap, y, x) {
      removeFromRoot(heap, y);
      y.left = y;
      y.right = y;
      mergeWithChild(x, y);
      x.degree++;
      y.parent = x;
    }
    __name(link, "link");
    function consolidate(heap) {
      var A = new Array(heap.size), nodes = consumeLinkedList(heap.root), i, l, x, y, d, t;
      for (i = 0, l = nodes.length; i < l; i++) {
        x = nodes[i];
        d = x.degree;
        while (A[d]) {
          y = A[d];
          if (heap.comparator(x.item, y.item) > 0) {
            t = x;
            x = y;
            y = t;
          }
          link(heap, y, x);
          A[d] = null;
          d++;
        }
        A[d] = x;
      }
      for (i = 0; i < heap.size; i++) {
        if (A[i] && heap.comparator(A[i].item, heap.min.item) <= 0)
          heap.min = A[i];
      }
    }
    __name(consolidate, "consolidate");
    FibonacciHeap2.prototype.pop = function() {
      if (!this.size)
        return void 0;
      var z = this.min;
      if (z.child) {
        var nodes = consumeLinkedList(z.child), node, i, l;
        for (i = 0, l = nodes.length; i < l; i++) {
          node = nodes[i];
          mergeWithRoot(this, node);
          delete node.parent;
        }
      }
      removeFromRoot(this, z);
      if (z === z.right) {
        this.min = null;
        this.root = null;
      } else {
        this.min = z.right;
        consolidate(this);
      }
      this.size--;
      return z.item;
    };
    FibonacciHeap2.prototype.inspect = function() {
      var proxy = {
        size: this.size
      };
      if (this.min && "item" in this.min)
        proxy.top = this.min.item;
      Object.defineProperty(proxy, "constructor", {
        value: FibonacciHeap2,
        enumerable: false
      });
      return proxy;
    };
    if (typeof Symbol !== "undefined")
      FibonacciHeap2.prototype[Symbol.for("nodejs.util.inspect.custom")] = FibonacciHeap2.prototype.inspect;
    function MaxFibonacciHeap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/FibonacciHeap.constructor: given comparator should be a function.");
      this.comparator = reverseComparator(this.comparator);
    }
    __name(MaxFibonacciHeap2, "MaxFibonacciHeap");
    MaxFibonacciHeap2.prototype = FibonacciHeap2.prototype;
    FibonacciHeap2.from = function(iterable, comparator) {
      var heap = new FibonacciHeap2(comparator);
      forEach(iterable, function(value) {
        heap.push(value);
      });
      return heap;
    };
    MaxFibonacciHeap2.from = function(iterable, comparator) {
      var heap = new MaxFibonacciHeap2(comparator);
      forEach(iterable, function(value) {
        heap.push(value);
      });
      return heap;
    };
    FibonacciHeap2.MinFibonacciHeap = FibonacciHeap2;
    FibonacciHeap2.MaxFibonacciHeap = MaxFibonacciHeap2;
    module.exports = FibonacciHeap2;
  }
});

// node_modules/mnemonist/utils/typed-arrays.js
var require_typed_arrays = __commonJS({
  "node_modules/mnemonist/utils/typed-arrays.js"(exports) {
    init_esbuild_shims();
    var MAX_8BIT_INTEGER = Math.pow(2, 8) - 1;
    var MAX_16BIT_INTEGER = Math.pow(2, 16) - 1;
    var MAX_32BIT_INTEGER = Math.pow(2, 32) - 1;
    var MAX_SIGNED_8BIT_INTEGER = Math.pow(2, 7) - 1;
    var MAX_SIGNED_16BIT_INTEGER = Math.pow(2, 15) - 1;
    var MAX_SIGNED_32BIT_INTEGER = Math.pow(2, 31) - 1;
    exports.getPointerArray = function(size) {
      var maxIndex = size - 1;
      if (maxIndex <= MAX_8BIT_INTEGER)
        return Uint8Array;
      if (maxIndex <= MAX_16BIT_INTEGER)
        return Uint16Array;
      if (maxIndex <= MAX_32BIT_INTEGER)
        return Uint32Array;
      throw new Error("mnemonist: Pointer Array of size > 4294967295 is not supported.");
    };
    exports.getSignedPointerArray = function(size) {
      var maxIndex = size - 1;
      if (maxIndex <= MAX_SIGNED_8BIT_INTEGER)
        return Int8Array;
      if (maxIndex <= MAX_SIGNED_16BIT_INTEGER)
        return Int16Array;
      if (maxIndex <= MAX_SIGNED_32BIT_INTEGER)
        return Int32Array;
      return Float64Array;
    };
    exports.getNumberType = function(value) {
      if (value === (value | 0)) {
        if (Math.sign(value) === -1) {
          if (value <= 127 && value >= -128)
            return Int8Array;
          if (value <= 32767 && value >= -32768)
            return Int16Array;
          return Int32Array;
        } else {
          if (value <= 255)
            return Uint8Array;
          if (value <= 65535)
            return Uint16Array;
          return Uint32Array;
        }
      }
      return Float64Array;
    };
    var TYPE_PRIORITY = {
      Uint8Array: 1,
      Int8Array: 2,
      Uint16Array: 3,
      Int16Array: 4,
      Uint32Array: 5,
      Int32Array: 6,
      Float32Array: 7,
      Float64Array: 8
    };
    exports.getMinimalRepresentation = function(array, getter) {
      var maxType = null, maxPriority = 0, p, t, v, i, l;
      for (i = 0, l = array.length; i < l; i++) {
        v = getter ? getter(array[i]) : array[i];
        t = exports.getNumberType(v);
        p = TYPE_PRIORITY[t.name];
        if (p > maxPriority) {
          maxPriority = p;
          maxType = t;
        }
      }
      return maxType;
    };
    exports.isTypedArray = function(value) {
      return typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(value);
    };
    exports.concat = function() {
      var length = 0, i, o, l;
      for (i = 0, l = arguments.length; i < l; i++)
        length += arguments[i].length;
      var array = new arguments[0].constructor(length);
      for (i = 0, o = 0; i < l; i++) {
        array.set(arguments[i], o);
        o += arguments[i].length;
      }
      return array;
    };
    exports.indices = function(length) {
      var PointerArray = exports.getPointerArray(length);
      var array = new PointerArray(length);
      for (var i = 0; i < length; i++)
        array[i] = i;
      return array;
    };
  }
});

// node_modules/mnemonist/utils/iterables.js
var require_iterables = __commonJS({
  "node_modules/mnemonist/utils/iterables.js"(exports) {
    init_esbuild_shims();
    var forEach = require_foreach();
    var typed = require_typed_arrays();
    function isArrayLike(target) {
      return Array.isArray(target) || typed.isTypedArray(target);
    }
    __name(isArrayLike, "isArrayLike");
    function guessLength(target) {
      if (typeof target.length === "number")
        return target.length;
      if (typeof target.size === "number")
        return target.size;
      return;
    }
    __name(guessLength, "guessLength");
    function toArray(target) {
      var l = guessLength(target);
      var array = typeof l === "number" ? new Array(l) : [];
      var i = 0;
      forEach(target, function(value) {
        array[i++] = value;
      });
      return array;
    }
    __name(toArray, "toArray");
    function toArrayWithIndices(target) {
      var l = guessLength(target);
      var IndexArray = typeof l === "number" ? typed.getPointerArray(l) : Array;
      var array = typeof l === "number" ? new Array(l) : [];
      var indices = typeof l === "number" ? new IndexArray(l) : [];
      var i = 0;
      forEach(target, function(value) {
        array[i] = value;
        indices[i] = i++;
      });
      return [array, indices];
    }
    __name(toArrayWithIndices, "toArrayWithIndices");
    exports.isArrayLike = isArrayLike;
    exports.guessLength = guessLength;
    exports.toArray = toArray;
    exports.toArrayWithIndices = toArrayWithIndices;
  }
});

// node_modules/mnemonist/heap.js
var require_heap = __commonJS({
  "node_modules/mnemonist/heap.js"(exports, module) {
    init_esbuild_shims();
    var forEach = require_foreach();
    var comparators = require_comparators();
    var iterables = require_iterables();
    var DEFAULT_COMPARATOR = comparators.DEFAULT_COMPARATOR;
    var reverseComparator = comparators.reverseComparator;
    function siftDown(compare, heap, startIndex, i) {
      var item = heap[i], parentIndex, parent;
      while (i > startIndex) {
        parentIndex = i - 1 >> 1;
        parent = heap[parentIndex];
        if (compare(item, parent) < 0) {
          heap[i] = parent;
          i = parentIndex;
          continue;
        }
        break;
      }
      heap[i] = item;
    }
    __name(siftDown, "siftDown");
    function siftUp(compare, heap, i) {
      var endIndex = heap.length, startIndex = i, item = heap[i], childIndex = 2 * i + 1, rightIndex;
      while (childIndex < endIndex) {
        rightIndex = childIndex + 1;
        if (rightIndex < endIndex && compare(heap[childIndex], heap[rightIndex]) >= 0) {
          childIndex = rightIndex;
        }
        heap[i] = heap[childIndex];
        i = childIndex;
        childIndex = 2 * i + 1;
      }
      heap[i] = item;
      siftDown(compare, heap, startIndex, i);
    }
    __name(siftUp, "siftUp");
    function push(compare, heap, item) {
      heap.push(item);
      siftDown(compare, heap, 0, heap.length - 1);
    }
    __name(push, "push");
    function pop(compare, heap) {
      var lastItem = heap.pop();
      if (heap.length !== 0) {
        var item = heap[0];
        heap[0] = lastItem;
        siftUp(compare, heap, 0);
        return item;
      }
      return lastItem;
    }
    __name(pop, "pop");
    function replace(compare, heap, item) {
      if (heap.length === 0)
        throw new Error("mnemonist/heap.replace: cannot pop an empty heap.");
      var popped = heap[0];
      heap[0] = item;
      siftUp(compare, heap, 0);
      return popped;
    }
    __name(replace, "replace");
    function pushpop(compare, heap, item) {
      var tmp;
      if (heap.length !== 0 && compare(heap[0], item) < 0) {
        tmp = heap[0];
        heap[0] = item;
        item = tmp;
        siftUp(compare, heap, 0);
      }
      return item;
    }
    __name(pushpop, "pushpop");
    function heapify(compare, array) {
      var n = array.length, l = n >> 1, i = l;
      while (--i >= 0)
        siftUp(compare, array, i);
    }
    __name(heapify, "heapify");
    function consume(compare, heap) {
      var l = heap.length, i = 0;
      var array = new Array(l);
      while (i < l)
        array[i++] = pop(compare, heap);
      return array;
    }
    __name(consume, "consume");
    function nsmallest(compare, n, iterable) {
      if (arguments.length === 2) {
        iterable = n;
        n = compare;
        compare = DEFAULT_COMPARATOR;
      }
      var reverseCompare = reverseComparator(compare);
      var i, l, v;
      var min = Infinity;
      var result;
      if (n === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i = 0, l = iterable.length; i < l; i++) {
            v = iterable[i];
            if (min === Infinity || compare(v, min) < 0)
              min = v;
          }
          result = new iterable.constructor(1);
          result[0] = min;
          return result;
        }
        forEach(iterable, function(value) {
          if (min === Infinity || compare(value, min) < 0)
            min = value;
        });
        return [min];
      }
      if (iterables.isArrayLike(iterable)) {
        if (n >= iterable.length)
          return iterable.slice().sort(compare);
        result = iterable.slice(0, n);
        heapify(reverseCompare, result);
        for (i = n, l = iterable.length; i < l; i++)
          if (reverseCompare(iterable[i], result[0]) > 0)
            replace(reverseCompare, result, iterable[i]);
        return result.sort(compare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n)
        n = size;
      result = new Array(n);
      i = 0;
      forEach(iterable, function(value) {
        if (i < n) {
          result[i] = value;
        } else {
          if (i === n)
            heapify(reverseCompare, result);
          if (reverseCompare(value, result[0]) > 0)
            replace(reverseCompare, result, value);
        }
        i++;
      });
      if (result.length > i)
        result.length = i;
      return result.sort(compare);
    }
    __name(nsmallest, "nsmallest");
    function nlargest(compare, n, iterable) {
      if (arguments.length === 2) {
        iterable = n;
        n = compare;
        compare = DEFAULT_COMPARATOR;
      }
      var reverseCompare = reverseComparator(compare);
      var i, l, v;
      var max = -Infinity;
      var result;
      if (n === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i = 0, l = iterable.length; i < l; i++) {
            v = iterable[i];
            if (max === -Infinity || compare(v, max) > 0)
              max = v;
          }
          result = new iterable.constructor(1);
          result[0] = max;
          return result;
        }
        forEach(iterable, function(value) {
          if (max === -Infinity || compare(value, max) > 0)
            max = value;
        });
        return [max];
      }
      if (iterables.isArrayLike(iterable)) {
        if (n >= iterable.length)
          return iterable.slice().sort(reverseCompare);
        result = iterable.slice(0, n);
        heapify(compare, result);
        for (i = n, l = iterable.length; i < l; i++)
          if (compare(iterable[i], result[0]) > 0)
            replace(compare, result, iterable[i]);
        return result.sort(reverseCompare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n)
        n = size;
      result = new Array(n);
      i = 0;
      forEach(iterable, function(value) {
        if (i < n) {
          result[i] = value;
        } else {
          if (i === n)
            heapify(compare, result);
          if (compare(value, result[0]) > 0)
            replace(compare, result, value);
        }
        i++;
      });
      if (result.length > i)
        result.length = i;
      return result.sort(reverseCompare);
    }
    __name(nlargest, "nlargest");
    function Heap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/Heap.constructor: given comparator should be a function.");
    }
    __name(Heap2, "Heap");
    Heap2.prototype.clear = function() {
      this.items = [];
      this.size = 0;
    };
    Heap2.prototype.push = function(item) {
      push(this.comparator, this.items, item);
      return ++this.size;
    };
    Heap2.prototype.peek = function() {
      return this.items[0];
    };
    Heap2.prototype.pop = function() {
      if (this.size !== 0)
        this.size--;
      return pop(this.comparator, this.items);
    };
    Heap2.prototype.replace = function(item) {
      return replace(this.comparator, this.items, item);
    };
    Heap2.prototype.pushpop = function(item) {
      return pushpop(this.comparator, this.items, item);
    };
    Heap2.prototype.consume = function() {
      this.size = 0;
      return consume(this.comparator, this.items);
    };
    Heap2.prototype.toArray = function() {
      return consume(this.comparator, this.items.slice());
    };
    Heap2.prototype.inspect = function() {
      var proxy = this.toArray();
      Object.defineProperty(proxy, "constructor", {
        value: Heap2,
        enumerable: false
      });
      return proxy;
    };
    if (typeof Symbol !== "undefined")
      Heap2.prototype[Symbol.for("nodejs.util.inspect.custom")] = Heap2.prototype.inspect;
    function MaxHeap2(comparator) {
      this.clear();
      this.comparator = comparator || DEFAULT_COMPARATOR;
      if (typeof this.comparator !== "function")
        throw new Error("mnemonist/MaxHeap.constructor: given comparator should be a function.");
      this.comparator = reverseComparator(this.comparator);
    }
    __name(MaxHeap2, "MaxHeap");
    MaxHeap2.prototype = Heap2.prototype;
    Heap2.from = function(iterable, comparator) {
      var heap = new Heap2(comparator);
      var items;
      if (iterables.isArrayLike(iterable))
        items = iterable.slice();
      else
        items = iterables.toArray(iterable);
      heapify(heap.comparator, items);
      heap.items = items;
      heap.size = items.length;
      return heap;
    };
    MaxHeap2.from = function(iterable, comparator) {
      var heap = new MaxHeap2(comparator);
      var items;
      if (iterables.isArrayLike(iterable))
        items = iterable.slice();
      else
        items = iterables.toArray(iterable);
      heapify(heap.comparator, items);
      heap.items = items;
      heap.size = items.length;
      return heap;
    };
    Heap2.siftUp = siftUp;
    Heap2.siftDown = siftDown;
    Heap2.push = push;
    Heap2.pop = pop;
    Heap2.replace = replace;
    Heap2.pushpop = pushpop;
    Heap2.heapify = heapify;
    Heap2.consume = consume;
    Heap2.nsmallest = nsmallest;
    Heap2.nlargest = nlargest;
    Heap2.MinHeap = Heap2;
    Heap2.MaxHeap = MaxHeap2;
    module.exports = Heap2;
  }
});

// node_modules/mnemonist/suffix-array.js
var require_suffix_array = __commonJS({
  "node_modules/mnemonist/suffix-array.js"(exports, module) {
    init_esbuild_shims();
    var SEPARATOR = "";
    function sort(string, array, offset) {
      var l = array.length, buckets = [], i = l, j = -1, b, d = 0, bits;
      while (i--)
        j = Math.max(string[array[i] + offset], j);
      bits = j >> 24 && 32 || j >> 16 && 24 || j >> 8 && 16 || 8;
      for (; d < bits; d += 4) {
        for (i = 16; i--; )
          buckets[i] = [];
        for (i = l; i--; )
          buckets[string[array[i] + offset] >> d & 15].push(array[i]);
        for (b = 0; b < 16; b++) {
          for (j = buckets[b].length; j--; )
            array[++i] = buckets[b][j];
        }
      }
    }
    __name(sort, "sort");
    function compare(string, lookup, m, n) {
      return string[m] - string[n] || (m % 3 === 2 ? string[m + 1] - string[n + 1] || lookup[m + 2] - lookup[n + 2] : lookup[m + 1] - lookup[n + 1]);
    }
    __name(compare, "compare");
    function build(string, l) {
      var a = [], b = [], al = 2 * l / 3 | 0, bl = l - al, r = al + 1 >> 1, i = al, j = 0, k, lookup = [], result = [];
      if (l === 1)
        return [0];
      while (i--)
        a[i] = (i * 3 >> 1) + 1;
      for (i = 3; i--; )
        sort(string, a, i);
      j = b[(a[0] / 3 | 0) + (a[0] % 3 === 1 ? 0 : r)] = 1;
      for (i = 1; i < al; i++) {
        if (string[a[i]] !== string[a[i - 1]] || string[a[i] + 1] !== string[a[i - 1] + 1] || string[a[i] + 2] !== string[a[i - 1] + 2])
          j++;
        b[(a[i] / 3 | 0) + (a[i] % 3 === 1 ? 0 : r)] = j;
      }
      if (j < al) {
        b = build(b, al);
        for (i = al; i--; )
          a[i] = b[i] < r ? b[i] * 3 + 1 : (b[i] - r) * 3 + 2;
      }
      for (i = al; i--; )
        lookup[a[i]] = i;
      lookup[l] = -1;
      lookup[l + 1] = -2;
      b = l % 3 === 1 ? [l - 1] : [];
      for (i = 0; i < al; i++) {
        if (a[i] % 3 === 1)
          b.push(a[i] - 1);
      }
      sort(string, b, 0);
      for (i = 0, j = 0, k = 0; i < al && j < bl; )
        result[k++] = compare(string, lookup, a[i], b[j]) < 0 ? a[i++] : b[j++];
      while (i < al)
        result[k++] = a[i++];
      while (j < bl)
        result[k++] = b[j++];
      return result;
    }
    __name(build, "build");
    function convert(target) {
      var length = target.length, paddingOffset = length % 3, array = new Array(length + paddingOffset), l, i;
      if (typeof target !== "string") {
        var uniqueTokens = /* @__PURE__ */ Object.create(null);
        for (i = 0; i < length; i++) {
          if (!uniqueTokens[target[i]])
            uniqueTokens[target[i]] = true;
        }
        var alphabet = /* @__PURE__ */ Object.create(null), sortedUniqueTokens = Object.keys(uniqueTokens).sort();
        for (i = 0, l = sortedUniqueTokens.length; i < l; i++)
          alphabet[sortedUniqueTokens[i]] = i + 1;
        for (i = 0; i < length; i++) {
          array[i] = alphabet[target[i]];
        }
      } else {
        for (i = 0; i < length; i++)
          array[i] = target.charCodeAt(i);
      }
      for (i = length; i < length + paddingOffset; i++)
        array[i] = 0;
      return array;
    }
    __name(convert, "convert");
    function SuffixArray2(string) {
      this.hasArbitrarySequence = typeof string !== "string";
      this.string = string;
      this.length = string.length;
      this.array = build(convert(string), this.length);
    }
    __name(SuffixArray2, "SuffixArray");
    SuffixArray2.prototype.toString = function() {
      return this.array.join(",");
    };
    SuffixArray2.prototype.toJSON = function() {
      return this.array;
    };
    SuffixArray2.prototype.inspect = function() {
      var array = new Array(this.length);
      for (var i = 0; i < this.length; i++)
        array[i] = this.string.slice(this.array[i]);
      Object.defineProperty(array, "constructor", {
        value: SuffixArray2,
        enumerable: false
      });
      return array;
    };
    if (typeof Symbol !== "undefined")
      SuffixArray2.prototype[Symbol.for("nodejs.util.inspect.custom")] = SuffixArray2.prototype.inspect;
    function GeneralizedSuffixArray2(strings) {
      this.hasArbitrarySequence = typeof strings[0] !== "string";
      this.size = strings.length;
      if (this.hasArbitrarySequence) {
        this.text = [];
        for (var i = 0, l = this.size; i < l; i++) {
          this.text.push.apply(this.text, strings[i]);
          if (i < l - 1)
            this.text.push(SEPARATOR);
        }
      } else {
        this.text = strings.join(SEPARATOR);
      }
      this.firstLength = strings[0].length;
      this.length = this.text.length;
      this.array = build(convert(this.text), this.length);
    }
    __name(GeneralizedSuffixArray2, "GeneralizedSuffixArray");
    GeneralizedSuffixArray2.prototype.longestCommonSubsequence = function() {
      var lcs = this.hasArbitrarySequence ? [] : "", lcp, i, j, s, t;
      for (i = 1; i < this.length; i++) {
        s = this.array[i];
        t = this.array[i - 1];
        if (s < this.firstLength && t < this.firstLength)
          continue;
        if (s > this.firstLength && t > this.firstLength)
          continue;
        lcp = Math.min(this.length - s, this.length - t);
        for (j = 0; j < lcp; j++) {
          if (this.text[s + j] !== this.text[t + j]) {
            lcp = j;
            break;
          }
        }
        if (lcp > lcs.length)
          lcs = this.text.slice(s, s + lcp);
      }
      return lcs;
    };
    GeneralizedSuffixArray2.prototype.toString = function() {
      return this.array.join(",");
    };
    GeneralizedSuffixArray2.prototype.toJSON = function() {
      return this.array;
    };
    GeneralizedSuffixArray2.prototype.inspect = function() {
      var array = new Array(this.length);
      for (var i = 0; i < this.length; i++)
        array[i] = this.text.slice(this.array[i]);
      Object.defineProperty(array, "constructor", {
        value: GeneralizedSuffixArray2,
        enumerable: false
      });
      return array;
    };
    if (typeof Symbol !== "undefined")
      GeneralizedSuffixArray2.prototype[Symbol.for("nodejs.util.inspect.custom")] = GeneralizedSuffixArray2.prototype.inspect;
    SuffixArray2.GeneralizedSuffixArray = GeneralizedSuffixArray2;
    module.exports = SuffixArray2;
  }
});

// node_modules/obliterator/iterator.js
var require_iterator = __commonJS({
  "node_modules/obliterator/iterator.js"(exports, module) {
    init_esbuild_shims();
    function Iterator(next) {
      if (typeof next !== "function")
        throw new Error("obliterator/iterator: expecting a function!");
      this.next = next;
    }
    __name(Iterator, "Iterator");
    if (typeof Symbol !== "undefined")
      Iterator.prototype[Symbol.iterator] = function() {
        return this;
      };
    Iterator.of = function() {
      var args = arguments, l = args.length, i = 0;
      return new Iterator(function() {
        if (i >= l) return { done: true };
        return { done: false, value: args[i++] };
      });
    };
    Iterator.empty = function() {
      var iterator = new Iterator(function() {
        return { done: true };
      });
      return iterator;
    };
    Iterator.fromSequence = function(sequence) {
      var i = 0, l = sequence.length;
      return new Iterator(function() {
        if (i >= l) return { done: true };
        return { done: false, value: sequence[i++] };
      });
    };
    Iterator.is = function(value) {
      if (value instanceof Iterator) return true;
      return typeof value === "object" && value !== null && typeof value.next === "function";
    };
    module.exports = Iterator;
  }
});

// node_modules/mnemonist/vector.js
var require_vector = __commonJS({
  "node_modules/mnemonist/vector.js"(exports, module) {
    init_esbuild_shims();
    var Iterator = require_iterator();
    var forEach = require_foreach();
    var iterables = require_iterables();
    var typed = require_typed_arrays();
    var DEFAULT_GROWING_POLICY = /* @__PURE__ */ __name(function(currentCapacity) {
      return Math.max(1, Math.ceil(currentCapacity * 1.5));
    }, "DEFAULT_GROWING_POLICY");
    var pointerArrayFactory = /* @__PURE__ */ __name(function(capacity) {
      var PointerArray = typed.getPointerArray(capacity);
      return new PointerArray(capacity);
    }, "pointerArrayFactory");
    function Vector2(ArrayClass, initialCapacityOrOptions) {
      if (arguments.length < 1)
        throw new Error("mnemonist/vector: expecting at least a byte array constructor.");
      var initialCapacity = initialCapacityOrOptions || 0, policy = DEFAULT_GROWING_POLICY, initialLength = 0, factory = false;
      if (typeof initialCapacityOrOptions === "object") {
        initialCapacity = initialCapacityOrOptions.initialCapacity || 0;
        initialLength = initialCapacityOrOptions.initialLength || 0;
        policy = initialCapacityOrOptions.policy || policy;
        factory = initialCapacityOrOptions.factory === true;
      }
      this.factory = factory ? ArrayClass : null;
      this.ArrayClass = ArrayClass;
      this.length = initialLength;
      this.capacity = Math.max(initialLength, initialCapacity);
      this.policy = policy;
      this.array = new ArrayClass(this.capacity);
    }
    __name(Vector2, "Vector");
    Vector2.prototype.set = function(index, value) {
      if (this.length < index)
        throw new Error("Vector(" + this.ArrayClass.name + ").set: index out of bounds.");
      this.array[index] = value;
      return this;
    };
    Vector2.prototype.get = function(index) {
      if (this.length < index)
        return void 0;
      return this.array[index];
    };
    Vector2.prototype.applyPolicy = function(override) {
      var newCapacity = this.policy(override || this.capacity);
      if (typeof newCapacity !== "number" || newCapacity < 0)
        throw new Error("mnemonist/vector.applyPolicy: policy returned an invalid value (expecting a positive integer).");
      if (newCapacity <= this.capacity)
        throw new Error("mnemonist/vector.applyPolicy: policy returned a less or equal capacity to allocate.");
      return newCapacity;
    };
    Vector2.prototype.reallocate = function(capacity) {
      if (capacity === this.capacity)
        return this;
      var oldArray = this.array;
      if (capacity < this.length)
        this.length = capacity;
      if (capacity > this.capacity) {
        if (this.factory === null)
          this.array = new this.ArrayClass(capacity);
        else
          this.array = this.factory(capacity);
        if (typed.isTypedArray(this.array)) {
          this.array.set(oldArray, 0);
        } else {
          for (var i = 0, l = this.length; i < l; i++)
            this.array[i] = oldArray[i];
        }
      } else {
        this.array = oldArray.slice(0, capacity);
      }
      this.capacity = capacity;
      return this;
    };
    Vector2.prototype.grow = function(capacity) {
      var newCapacity;
      if (typeof capacity === "number") {
        if (this.capacity >= capacity)
          return this;
        newCapacity = this.capacity;
        while (newCapacity < capacity)
          newCapacity = this.applyPolicy(newCapacity);
        this.reallocate(newCapacity);
        return this;
      }
      newCapacity = this.applyPolicy();
      this.reallocate(newCapacity);
      return this;
    };
    Vector2.prototype.resize = function(length) {
      if (length === this.length)
        return this;
      if (length < this.length) {
        this.length = length;
        return this;
      }
      this.length = length;
      this.reallocate(length);
      return this;
    };
    Vector2.prototype.push = function(value) {
      if (this.capacity === this.length)
        this.grow();
      this.array[this.length++] = value;
      return this.length;
    };
    Vector2.prototype.pop = function() {
      if (this.length === 0)
        return;
      return this.array[--this.length];
    };
    Vector2.prototype.values = function() {
      var items = this.array, l = this.length, i = 0;
      return new Iterator(function() {
        if (i >= l)
          return {
            done: true
          };
        var value = items[i];
        i++;
        return {
          value,
          done: false
        };
      });
    };
    Vector2.prototype.entries = function() {
      var items = this.array, l = this.length, i = 0;
      return new Iterator(function() {
        if (i >= l)
          return {
            done: true
          };
        var value = items[i];
        return {
          value: [i++, value],
          done: false
        };
      });
    };
    if (typeof Symbol !== "undefined")
      Vector2.prototype[Symbol.iterator] = Vector2.prototype.values;
    Vector2.prototype.inspect = function() {
      var proxy = this.array.slice(0, this.length);
      proxy.type = this.array.constructor.name;
      proxy.items = this.length;
      proxy.capacity = this.capacity;
      Object.defineProperty(proxy, "constructor", {
        value: Vector2,
        enumerable: false
      });
      return proxy;
    };
    if (typeof Symbol !== "undefined")
      Vector2.prototype[Symbol.for("nodejs.util.inspect.custom")] = Vector2.prototype.inspect;
    Vector2.from = function(iterable, ArrayClass, capacity) {
      if (arguments.length < 3) {
        capacity = iterables.guessLength(iterable);
        if (typeof capacity !== "number")
          throw new Error("mnemonist/vector.from: could not guess iterable length. Please provide desired capacity as last argument.");
      }
      var vector = new Vector2(ArrayClass, capacity);
      forEach(iterable, function(value) {
        vector.push(value);
      });
      return vector;
    };
    function subClass(ArrayClass) {
      var SubClass = /* @__PURE__ */ __name(function(initialCapacityOrOptions) {
        Vector2.call(this, ArrayClass, initialCapacityOrOptions);
      }, "SubClass");
      for (var k in Vector2.prototype) {
        if (Vector2.prototype.hasOwnProperty(k))
          SubClass.prototype[k] = Vector2.prototype[k];
      }
      SubClass.from = function(iterable, capacity) {
        return Vector2.from(iterable, ArrayClass, capacity);
      };
      if (typeof Symbol !== "undefined")
        SubClass.prototype[Symbol.iterator] = SubClass.prototype.values;
      return SubClass;
    }
    __name(subClass, "subClass");
    Vector2.Int8Vector = subClass(Int8Array);
    Vector2.Uint8Vector = subClass(Uint8Array);
    Vector2.Uint8ClampedVector = subClass(Uint8ClampedArray);
    Vector2.Int16Vector = subClass(Int16Array);
    Vector2.Uint16Vector = subClass(Uint16Array);
    Vector2.Int32Vector = subClass(Int32Array);
    Vector2.Uint32Vector = subClass(Uint32Array);
    Vector2.Float32Vector = subClass(Float32Array);
    Vector2.Float64Vector = subClass(Float64Array);
    Vector2.PointerVector = subClass(pointerArrayFactory);
    module.exports = Vector2;
  }
});

// node_modules/mnemonist/fixed-deque.js
var require_fixed_deque = __commonJS({
  "node_modules/mnemonist/fixed-deque.js"(exports, module) {
    init_esbuild_shims();
    var iterables = require_iterables();
    var Iterator = require_iterator();
    function FixedDeque(ArrayClass, capacity) {
      if (arguments.length < 2)
        throw new Error("mnemonist/fixed-deque: expecting an Array class and a capacity.");
      if (typeof capacity !== "number" || capacity <= 0)
        throw new Error("mnemonist/fixed-deque: `capacity` should be a positive number.");
      this.ArrayClass = ArrayClass;
      this.capacity = capacity;
      this.items = new ArrayClass(this.capacity);
      this.clear();
    }
    __name(FixedDeque, "FixedDeque");
    FixedDeque.prototype.clear = function() {
      this.start = 0;
      this.size = 0;
    };
    FixedDeque.prototype.push = function(item) {
      if (this.size === this.capacity)
        throw new Error("mnemonist/fixed-deque.push: deque capacity (" + this.capacity + ") exceeded!");
      var index = this.start + this.size;
      if (index >= this.capacity)
        index -= this.capacity;
      this.items[index] = item;
      return ++this.size;
    };
    FixedDeque.prototype.unshift = function(item) {
      if (this.size === this.capacity)
        throw new Error("mnemonist/fixed-deque.unshift: deque capacity (" + this.capacity + ") exceeded!");
      var index = this.start - 1;
      if (this.start === 0)
        index = this.capacity - 1;
      this.items[index] = item;
      this.start = index;
      return ++this.size;
    };
    FixedDeque.prototype.pop = function() {
      if (this.size === 0)
        return;
      this.size--;
      var index = this.start + this.size;
      if (index >= this.capacity)
        index -= this.capacity;
      return this.items[index];
    };
    FixedDeque.prototype.shift = function() {
      if (this.size === 0)
        return;
      var index = this.start;
      this.size--;
      this.start++;
      if (this.start === this.capacity)
        this.start = 0;
      return this.items[index];
    };
    FixedDeque.prototype.peekFirst = function() {
      if (this.size === 0)
        return;
      return this.items[this.start];
    };
    FixedDeque.prototype.peekLast = function() {
      if (this.size === 0)
        return;
      var index = this.start + this.size - 1;
      if (index >= this.capacity)
        index -= this.capacity;
      return this.items[index];
    };
    FixedDeque.prototype.get = function(index) {
      if (this.size === 0 || index >= this.capacity)
        return;
      index = this.start + index;
      if (index >= this.capacity)
        index -= this.capacity;
      return this.items[index];
    };
    FixedDeque.prototype.forEach = function(callback, scope) {
      scope = arguments.length > 1 ? scope : this;
      var c = this.capacity, l = this.size, i = this.start, j = 0;
      while (j < l) {
        callback.call(scope, this.items[i], j, this);
        i++;
        j++;
        if (i === c)
          i = 0;
      }
    };
    FixedDeque.prototype.toArray = function() {
      var offset = this.start + this.size;
      if (offset < this.capacity)
        return this.items.slice(this.start, offset);
      var array = new this.ArrayClass(this.size), c = this.capacity, l = this.size, i = this.start, j = 0;
      while (j < l) {
        array[j] = this.items[i];
        i++;
        j++;
        if (i === c)
          i = 0;
      }
      return array;
    };
    FixedDeque.prototype.values = function() {
      var items = this.items, c = this.capacity, l = this.size, i = this.start, j = 0;
      return new Iterator(function() {
        if (j >= l)
          return {
            done: true
          };
        var value = items[i];
        i++;
        j++;
        if (i === c)
          i = 0;
        return {
          value,
          done: false
        };
      });
    };
    FixedDeque.prototype.entries = function() {
      var items = this.items, c = this.capacity, l = this.size, i = this.start, j = 0;
      return new Iterator(function() {
        if (j >= l)
          return {
            done: true
          };
        var value = items[i];
        i++;
        if (i === c)
          i = 0;
        return {
          value: [j++, value],
          done: false
        };
      });
    };
    if (typeof Symbol !== "undefined")
      FixedDeque.prototype[Symbol.iterator] = FixedDeque.prototype.values;
    FixedDeque.prototype.inspect = function() {
      var array = this.toArray();
      array.type = this.ArrayClass.name;
      array.capacity = this.capacity;
      Object.defineProperty(array, "constructor", {
        value: FixedDeque,
        enumerable: false
      });
      return array;
    };
    if (typeof Symbol !== "undefined")
      FixedDeque.prototype[Symbol.for("nodejs.util.inspect.custom")] = FixedDeque.prototype.inspect;
    FixedDeque.from = function(iterable, ArrayClass, capacity) {
      if (arguments.length < 3) {
        capacity = iterables.guessLength(iterable);
        if (typeof capacity !== "number")
          throw new Error("mnemonist/fixed-deque.from: could not guess iterable length. Please provide desired capacity as last argument.");
      }
      var deque = new FixedDeque(ArrayClass, capacity);
      if (iterables.isArrayLike(iterable)) {
        var i, l;
        for (i = 0, l = iterable.length; i < l; i++)
          deque.items[i] = iterable[i];
        deque.size = l;
        return deque;
      }
      iterables.forEach(iterable, function(value) {
        deque.push(value);
      });
      return deque;
    };
    module.exports = FixedDeque;
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js
var OTLPExporterBase;
var init_OTLPExporterBase = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js"() {
    init_esbuild_shims();
    OTLPExporterBase = class {
      static {
        __name(this, "OTLPExporterBase");
      }
      _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();
      }
    };
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js
var OTLPExporterError;
var init_types = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js"() {
    init_esbuild_shims();
    OTLPExporterError = class extends Error {
      static {
        __name(this, "OTLPExporterError");
      }
      code;
      name = "OTLPExporterError";
      data;
      constructor(message, code, data) {
        super(message);
        this.data = data;
        this.code = code;
      }
    };
  }
});

// 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 void 0;
  }
  return () => headers;
}
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 = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-configuration.js"() {
    init_esbuild_shims();
    __name(validateTimeoutMillis, "validateTimeoutMillis");
    __name(wrapStaticHeadersInFunction, "wrapStaticHeadersInFunction");
    __name(mergeOtlpSharedConfigurationWithDefaults, "mergeOtlpSharedConfigurationWithDefaults");
    __name(getSharedConfigurationDefaults, "getSharedConfigurationDefaults");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/legacy-node-configuration.js
var CompressionAlgorithm;
var init_legacy_node_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/legacy-node-configuration.js"() {
    init_esbuild_shims();
    (function(CompressionAlgorithm2) {
      CompressionAlgorithm2["NONE"] = "none";
      CompressionAlgorithm2["GZIP"] = "gzip";
    })(CompressionAlgorithm || (CompressionAlgorithm = {}));
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js
function createBoundedQueueExportPromiseHandler(options) {
  return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);
}
var BoundedQueueExportPromiseHandler;
var init_bounded_queue_export_promise_handler = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js"() {
    init_esbuild_shims();
    BoundedQueueExportPromiseHandler = class {
      static {
        __name(this, "BoundedQueueExportPromiseHandler");
      }
      _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 = /* @__PURE__ */ __name(() => {
          const index = this._sendingPromises.indexOf(promise);
          void this._sendingPromises.splice(index, 1);
        }, "popPromise");
        promise.then(popPromise, popPromise);
      }
      hasReachedLimit() {
        return this._sendingPromises.length >= this._concurrencyLimit;
      }
      async awaitAll() {
        await Promise.all(this._sendingPromises);
      }
    };
    __name(createBoundedQueueExportPromiseHandler, "createBoundedQueueExportPromiseHandler");
  }
});

// node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js
var require_suppress_tracing = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
    function suppressTracing(context2) {
      return context2.setValue(SUPPRESS_TRACING_KEY, true);
    }
    __name(suppressTracing, "suppressTracing");
    exports.suppressTracing = suppressTracing;
    function unsuppressTracing(context2) {
      return context2.deleteValue(SUPPRESS_TRACING_KEY);
    }
    __name(unsuppressTracing, "unsuppressTracing");
    exports.unsuppressTracing = unsuppressTracing;
    function isTracingSuppressed(context2) {
      return context2.getValue(SUPPRESS_TRACING_KEY) === true;
    }
    __name(isTracingSuppressed, "isTracingSuppressed");
    exports.isTracingSuppressed = isTracingSuppressed;
  }
});

// node_modules/@opentelemetry/core/build/src/baggage/constants.js
var require_constants = __commonJS({
  "node_modules/@opentelemetry/core/build/src/baggage/constants.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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;
  }
});

// node_modules/@opentelemetry/core/build/src/baggage/utils.js
var require_utils2 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/baggage/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseKeyPairsIntoRecord = exports.parsePairKeyValue = exports.getKeyPairs = exports.serializeKeyPairs = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var 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;
      }, "");
    }
    __name(serializeKeyPairs, "serializeKeyPairs");
    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;
      });
    }
    __name(getKeyPairs, "getKeyPairs");
    exports.getKeyPairs = getKeyPairs;
    function parsePairKeyValue(entry) {
      const valueProps = entry.split(constants_1.BAGGAGE_PROPERTIES_SEPARATOR);
      if (valueProps.length <= 0)
        return;
      const keyPairPart = valueProps.shift();
      if (!keyPairPart)
        return;
      const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR);
      if (separatorIndex <= 0)
        return;
      const key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim());
      const value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim());
      let metadata;
      if (valueProps.length > 0) {
        metadata = (0, api_1.baggageEntryMetadataFromString)(valueProps.join(constants_1.BAGGAGE_PROPERTIES_SEPARATOR));
      }
      return { key, value, metadata };
    }
    __name(parsePairKeyValue, "parsePairKeyValue");
    exports.parsePairKeyValue = parsePairKeyValue;
    function parseKeyPairsIntoRecord2(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;
    }
    __name(parseKeyPairsIntoRecord2, "parseKeyPairsIntoRecord");
    exports.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord2;
  }
});

// node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js
var require_W3CBaggagePropagator = __commonJS({
  "node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.W3CBaggagePropagator = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var suppress_tracing_1 = require_suppress_tracing();
    var constants_1 = require_constants();
    var utils_1 = require_utils2();
    var W3CBaggagePropagator = class {
      static {
        __name(this, "W3CBaggagePropagator");
      }
      inject(context2, carrier, setter) {
        const baggage = api_1.propagation.getBaggage(context2);
        if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context2))
          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(context2, carrier, getter) {
        const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER);
        const baggageString = Array.isArray(headerValue) ? headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR) : headerValue;
        if (!baggageString)
          return context2;
        const baggage = {};
        if (baggageString.length === 0) {
          return context2;
        }
        const pairs = baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR);
        pairs.forEach((entry) => {
          const keyPair = (0, utils_1.parsePairKeyValue)(entry);
          if (keyPair) {
            const baggageEntry = { value: keyPair.value };
            if (keyPair.metadata) {
              baggageEntry.metadata = keyPair.metadata;
            }
            baggage[keyPair.key] = baggageEntry;
          }
        });
        if (Object.entries(baggage).length === 0) {
          return context2;
        }
        return api_1.propagation.setBaggage(context2, api_1.propagation.createBaggage(baggage));
      }
      fields() {
        return [constants_1.BAGGAGE_HEADER];
      }
    };
    exports.W3CBaggagePropagator = W3CBaggagePropagator;
  }
});

// node_modules/@opentelemetry/core/build/src/common/anchored-clock.js
var require_anchored_clock = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/anchored-clock.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AnchoredClock = void 0;
    var AnchoredClock = class {
      static {
        __name(this, "AnchoredClock");
      }
      _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;
  }
});

// node_modules/@opentelemetry/core/build/src/common/attributes.js
var require_attributes = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/attributes.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isAttributeValue = exports.isAttributeKey = exports.sanitizeAttributes = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    function sanitizeAttributes(attributes) {
      const out = {};
      if (typeof attributes !== "object" || attributes == null) {
        return out;
      }
      for (const [key, val] of Object.entries(attributes)) {
        if (!isAttributeKey(key)) {
          api_1.diag.warn(`Invalid attribute key: ${key}`);
          continue;
        }
        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;
    }
    __name(sanitizeAttributes, "sanitizeAttributes");
    exports.sanitizeAttributes = sanitizeAttributes;
    function isAttributeKey(key) {
      return typeof key === "string" && key.length > 0;
    }
    __name(isAttributeKey, "isAttributeKey");
    exports.isAttributeKey = isAttributeKey;
    function isAttributeValue(val) {
      if (val == null) {
        return true;
      }
      if (Array.isArray(val)) {
        return isHomogeneousAttributeValueArray(val);
      }
      return isValidPrimitiveAttributeValue(val);
    }
    __name(isAttributeValue, "isAttributeValue");
    exports.isAttributeValue = isAttributeValue;
    function isHomogeneousAttributeValueArray(arr) {
      let type;
      for (const element of arr) {
        if (element == null)
          continue;
        if (!type) {
          if (isValidPrimitiveAttributeValue(element)) {
            type = typeof element;
            continue;
          }
          return false;
        }
        if (typeof element === type) {
          continue;
        }
        return false;
      }
      return true;
    }
    __name(isHomogeneousAttributeValueArray, "isHomogeneousAttributeValueArray");
    function isValidPrimitiveAttributeValue(val) {
      switch (typeof val) {
        case "number":
        case "boolean":
        case "string":
          return true;
      }
      return false;
    }
    __name(isValidPrimitiveAttributeValue, "isValidPrimitiveAttributeValue");
  }
});

// node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js
var require_logging_error_handler = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.loggingErrorHandler = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    function loggingErrorHandler() {
      return (ex) => {
        api_1.diag.error(stringifyException(ex));
      };
    }
    __name(loggingErrorHandler, "loggingErrorHandler");
    exports.loggingErrorHandler = loggingErrorHandler;
    function stringifyException(ex) {
      if (typeof ex === "string") {
        return ex;
      } else {
        return JSON.stringify(flattenException(ex));
      }
    }
    __name(stringifyException, "stringifyException");
    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;
    }
    __name(flattenException, "flattenException");
  }
});

// node_modules/@opentelemetry/core/build/src/common/global-error-handler.js
var require_global_error_handler = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/global-error-handler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.globalErrorHandler = exports.setGlobalErrorHandler = void 0;
    var logging_error_handler_1 = require_logging_error_handler();
    var delegateHandler = (0, logging_error_handler_1.loggingErrorHandler)();
    function setGlobalErrorHandler(handler) {
      delegateHandler = handler;
    }
    __name(setGlobalErrorHandler, "setGlobalErrorHandler");
    exports.setGlobalErrorHandler = setGlobalErrorHandler;
    function globalErrorHandler(ex) {
      try {
        delegateHandler(ex);
      } catch {
      }
    }
    __name(globalErrorHandler, "globalErrorHandler");
    exports.globalErrorHandler = globalErrorHandler;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/environment.js
var require_environment = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/environment.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getStringListFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports.getNumberFromEnv = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var util_1 = __require("util");
    function getNumberFromEnv(key) {
      const raw = process.env[key];
      if (raw == null || raw.trim() === "") {
        return void 0;
      }
      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 void 0;
      }
      return value;
    }
    __name(getNumberFromEnv, "getNumberFromEnv");
    exports.getNumberFromEnv = getNumberFromEnv;
    function getStringFromEnv(key) {
      const raw = process.env[key];
      if (raw == null || raw.trim() === "") {
        return void 0;
      }
      return raw;
    }
    __name(getStringFromEnv, "getStringFromEnv");
    exports.getStringFromEnv = getStringFromEnv;
    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;
      }
    }
    __name(getBooleanFromEnv, "getBooleanFromEnv");
    exports.getBooleanFromEnv = getBooleanFromEnv;
    function getStringListFromEnv(key) {
      return getStringFromEnv(key)?.split(",").map((v) => v.trim()).filter((s) => s !== "");
    }
    __name(getStringListFromEnv, "getStringListFromEnv");
    exports.getStringListFromEnv = getStringListFromEnv;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js
var require_globalThis2 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports._globalThis = void 0;
    exports._globalThis = typeof globalThis === "object" ? globalThis : globalThis;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/performance.js
var require_performance = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/performance.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.otperformance = void 0;
    var perf_hooks_1 = __require("perf_hooks");
    exports.otperformance = perf_hooks_1.performance;
  }
});

// node_modules/@opentelemetry/core/build/src/version.js
var require_version = __commonJS({
  "node_modules/@opentelemetry/core/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "2.0.1";
  }
});

// node_modules/@opentelemetry/core/build/src/semconv.js
var require_semconv = __commonJS({
  "node_modules/@opentelemetry/core/build/src/semconv.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ATTR_PROCESS_RUNTIME_NAME = void 0;
    exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js
var require_sdk_info = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SDK_INFO = void 0;
    var version_1 = require_version();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var semconv_1 = require_semconv();
    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
    };
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/timer-util.js
var require_timer_util = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/timer-util.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.unrefTimer = void 0;
    function unrefTimer(timer) {
      timer.unref();
    }
    __name(unrefTimer, "unrefTimer");
    exports.unrefTimer = unrefTimer;
  }
});

// node_modules/@opentelemetry/core/build/src/platform/node/index.js
var require_node3 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.unrefTimer = exports.SDK_INFO = exports.otperformance = exports._globalThis = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = void 0;
    var environment_1 = require_environment();
    Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getStringFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getBooleanFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getNumberFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return environment_1.getStringListFromEnv;
    }, "get") });
    var globalThis_1 = require_globalThis2();
    Object.defineProperty(exports, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return globalThis_1._globalThis;
    }, "get") });
    var performance_1 = require_performance();
    Object.defineProperty(exports, "otperformance", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return performance_1.otperformance;
    }, "get") });
    var sdk_info_1 = require_sdk_info();
    Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_info_1.SDK_INFO;
    }, "get") });
    var timer_util_1 = require_timer_util();
    Object.defineProperty(exports, "unrefTimer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return timer_util_1.unrefTimer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/core/build/src/platform/index.js
var require_platform2 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getStringFromEnv = exports.getBooleanFromEnv = exports.unrefTimer = exports.otperformance = exports._globalThis = exports.SDK_INFO = void 0;
    var node_1 = require_node3();
    Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.SDK_INFO;
    }, "get") });
    Object.defineProperty(exports, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1._globalThis;
    }, "get") });
    Object.defineProperty(exports, "otperformance", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.otperformance;
    }, "get") });
    Object.defineProperty(exports, "unrefTimer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.unrefTimer;
    }, "get") });
    Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getBooleanFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getStringFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getNumberFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.getStringListFromEnv;
    }, "get") });
  }
});

// node_modules/@opentelemetry/core/build/src/common/time.js
var require_time = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/time.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.addHrTimes = exports.isTimeInput = exports.isTimeInputHrTime = exports.hrTimeToMicroseconds = exports.hrTimeToMilliseconds = exports.hrTimeToNanoseconds = exports.hrTimeToTimeStamp = exports.hrTimeDuration = exports.timeInputToHrTime = exports.hrTime = exports.getTimeOrigin = exports.millisToHrTime = void 0;
    var platform_1 = require_platform2();
    var NANOSECOND_DIGITS = 9;
    var NANOSECOND_DIGITS_IN_MILLIS = 6;
    var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
    var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
    function millisToHrTime(epochMillis) {
      const epochSeconds = epochMillis / 1e3;
      const seconds = Math.trunc(epochSeconds);
      const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
      return [seconds, nanos];
    }
    __name(millisToHrTime, "millisToHrTime");
    exports.millisToHrTime = millisToHrTime;
    function getTimeOrigin() {
      let timeOrigin = platform_1.otperformance.timeOrigin;
      if (typeof timeOrigin !== "number") {
        const perf = platform_1.otperformance;
        timeOrigin = perf.timing && perf.timing.fetchStart;
      }
      return timeOrigin;
    }
    __name(getTimeOrigin, "getTimeOrigin");
    exports.getTimeOrigin = getTimeOrigin;
    function hrTime(performanceNow) {
      const timeOrigin = millisToHrTime(getTimeOrigin());
      const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : platform_1.otperformance.now());
      return addHrTimes(timeOrigin, now);
    }
    __name(hrTime, "hrTime");
    exports.hrTime = hrTime;
    function timeInputToHrTime(time) {
      if (isTimeInputHrTime(time)) {
        return time;
      } else if (typeof time === "number") {
        if (time < getTimeOrigin()) {
          return hrTime(time);
        } else {
          return millisToHrTime(time);
        }
      } else if (time instanceof Date) {
        return millisToHrTime(time.getTime());
      } else {
        throw TypeError("Invalid input type");
      }
    }
    __name(timeInputToHrTime, "timeInputToHrTime");
    exports.timeInputToHrTime = timeInputToHrTime;
    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];
    }
    __name(hrTimeDuration, "hrTimeDuration");
    exports.hrTimeDuration = hrTimeDuration;
    function hrTimeToTimeStamp(time) {
      const precision = NANOSECOND_DIGITS;
      const tmp = `${"0".repeat(precision)}${time[1]}Z`;
      const nanoString = tmp.substring(tmp.length - precision - 1);
      const date = new Date(time[0] * 1e3).toISOString();
      return date.replace("000Z", nanoString);
    }
    __name(hrTimeToTimeStamp, "hrTimeToTimeStamp");
    exports.hrTimeToTimeStamp = hrTimeToTimeStamp;
    function hrTimeToNanoseconds(time) {
      return time[0] * SECOND_TO_NANOSECONDS + time[1];
    }
    __name(hrTimeToNanoseconds, "hrTimeToNanoseconds");
    exports.hrTimeToNanoseconds = hrTimeToNanoseconds;
    function hrTimeToMilliseconds(time) {
      return time[0] * 1e3 + time[1] / 1e6;
    }
    __name(hrTimeToMilliseconds, "hrTimeToMilliseconds");
    exports.hrTimeToMilliseconds = hrTimeToMilliseconds;
    function hrTimeToMicroseconds(time) {
      return time[0] * 1e6 + time[1] / 1e3;
    }
    __name(hrTimeToMicroseconds, "hrTimeToMicroseconds");
    exports.hrTimeToMicroseconds = hrTimeToMicroseconds;
    function isTimeInputHrTime(value) {
      return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number";
    }
    __name(isTimeInputHrTime, "isTimeInputHrTime");
    exports.isTimeInputHrTime = isTimeInputHrTime;
    function isTimeInput(value) {
      return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date;
    }
    __name(isTimeInput, "isTimeInput");
    exports.isTimeInput = isTimeInput;
    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;
    }
    __name(addHrTimes, "addHrTimes");
    exports.addHrTimes = addHrTimes;
  }
});

// node_modules/@opentelemetry/core/build/src/ExportResult.js
var require_ExportResult = __commonJS({
  "node_modules/@opentelemetry/core/build/src/ExportResult.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExportResultCode = void 0;
    var ExportResultCode3;
    (function(ExportResultCode4) {
      ExportResultCode4[ExportResultCode4["SUCCESS"] = 0] = "SUCCESS";
      ExportResultCode4[ExportResultCode4["FAILED"] = 1] = "FAILED";
    })(ExportResultCode3 = exports.ExportResultCode || (exports.ExportResultCode = {}));
  }
});

// node_modules/@opentelemetry/core/build/src/propagation/composite.js
var require_composite = __commonJS({
  "node_modules/@opentelemetry/core/build/src/propagation/composite.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompositePropagator = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var CompositePropagator = class {
      static {
        __name(this, "CompositePropagator");
      }
      _propagators;
      _fields;
      /**
       * Construct a composite propagator from a list of propagators.
       *
       * @param [config] Configuration object for composite propagator
       */
      constructor(config = {}) {
        this._propagators = config.propagators ?? [];
        this._fields = Array.from(new Set(this._propagators.map((p) => typeof p.fields === "function" ? p.fields() : []).reduce((x, y) => x.concat(y), [])));
      }
      /**
       * 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(context2, carrier, setter) {
        for (const propagator of this._propagators) {
          try {
            propagator.inject(context2, 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(context2, 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;
        }, context2);
      }
      fields() {
        return this._fields.slice();
      }
    };
    exports.CompositePropagator = CompositePropagator;
  }
});

// node_modules/@opentelemetry/core/build/src/internal/validators.js
var require_validators = __commonJS({
  "node_modules/@opentelemetry/core/build/src/internal/validators.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateValue = exports.validateKey = void 0;
    var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
    var VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
    var VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
    var VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
    var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
    var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
    function validateKey(key) {
      return VALID_KEY_REGEX.test(key);
    }
    __name(validateKey, "validateKey");
    exports.validateKey = validateKey;
    function validateValue(value) {
      return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
    }
    __name(validateValue, "validateValue");
    exports.validateValue = validateValue;
  }
});

// node_modules/@opentelemetry/core/build/src/trace/TraceState.js
var require_TraceState = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/TraceState.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TraceState = void 0;
    var validators_1 = require_validators();
    var MAX_TRACE_STATE_ITEMS = 32;
    var MAX_TRACE_STATE_LEN = 512;
    var LIST_MEMBERS_SEPARATOR = ",";
    var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
    var TraceState = class _TraceState {
      static {
        __name(this, "TraceState");
      }
      _internalState = /* @__PURE__ */ new Map();
      constructor(rawTraceState) {
        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 this._keys().reduce((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).reverse().reduce((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 ((0, validators_1.validateKey)(key) && (0, validators_1.validateValue)(value)) {
              agg.set(key, value);
            } else {
            }
          }
          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 _TraceState();
        traceState._internalState = new Map(this._internalState);
        return traceState;
      }
    };
    exports.TraceState = TraceState;
  }
});

// node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js
var require_W3CTraceContextPropagator = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.W3CTraceContextPropagator = exports.parseTraceParent = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var suppress_tracing_1 = require_suppress_tracing();
    var TraceState_1 = require_TraceState();
    exports.TRACE_PARENT_HEADER = "traceparent";
    exports.TRACE_STATE_HEADER = "tracestate";
    var VERSION = "00";
    var VERSION_PART = "(?!ff)[\\da-f]{2}";
    var TRACE_ID_PART = "(?![0]{32})[\\da-f]{32}";
    var PARENT_ID_PART = "(?![0]{16})[\\da-f]{16}";
    var FLAGS_PART = "[\\da-f]{2}";
    var TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);
    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)
      };
    }
    __name(parseTraceParent, "parseTraceParent");
    exports.parseTraceParent = parseTraceParent;
    var W3CTraceContextPropagator = class {
      static {
        __name(this, "W3CTraceContextPropagator");
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        if (!spanContext || (0, suppress_tracing_1.isTracingSuppressed)(context2) || !(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(context2, carrier, getter) {
        const traceParentHeader = getter.get(carrier, exports.TRACE_PARENT_HEADER);
        if (!traceParentHeader)
          return context2;
        const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader;
        if (typeof traceParent !== "string")
          return context2;
        const spanContext = parseTraceParent(traceParent);
        if (!spanContext)
          return context2;
        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(context2, spanContext);
      }
      fields() {
        return [exports.TRACE_PARENT_HEADER, exports.TRACE_STATE_HEADER];
      }
    };
    exports.W3CTraceContextPropagator = W3CTraceContextPropagator;
  }
});

// node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js
var require_rpc_metadata = __commonJS({
  "node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getRPCMetadata = exports.deleteRPCMetadata = exports.setRPCMetadata = exports.RPCType = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var RPC_METADATA_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA");
    var RPCType;
    (function(RPCType2) {
      RPCType2["HTTP"] = "http";
    })(RPCType = exports.RPCType || (exports.RPCType = {}));
    function setRPCMetadata(context2, meta) {
      return context2.setValue(RPC_METADATA_KEY, meta);
    }
    __name(setRPCMetadata, "setRPCMetadata");
    exports.setRPCMetadata = setRPCMetadata;
    function deleteRPCMetadata(context2) {
      return context2.deleteValue(RPC_METADATA_KEY);
    }
    __name(deleteRPCMetadata, "deleteRPCMetadata");
    exports.deleteRPCMetadata = deleteRPCMetadata;
    function getRPCMetadata(context2) {
      return context2.getValue(RPC_METADATA_KEY);
    }
    __name(getRPCMetadata, "getRPCMetadata");
    exports.getRPCMetadata = getRPCMetadata;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js
var require_lodash_merge = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isPlainObject = void 0;
    var objectTag = "[object Object]";
    var nullTag = "[object Null]";
    var undefinedTag = "[object Undefined]";
    var funcProto = Function.prototype;
    var funcToString = funcProto.toString;
    var objectCtorString = funcToString.call(Object);
    var getPrototypeOf = Object.getPrototypeOf;
    var objectProto = Object.prototype;
    var hasOwnProperty = objectProto.hasOwnProperty;
    var symToStringTag = Symbol ? Symbol.toStringTag : void 0;
    var nativeObjectToString = objectProto.toString;
    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;
    }
    __name(isPlainObject, "isPlainObject");
    exports.isPlainObject = isPlainObject;
    function isObjectLike(value) {
      return value != null && typeof value == "object";
    }
    __name(isObjectLike, "isObjectLike");
    function baseGetTag(value) {
      if (value == null) {
        return value === void 0 ? undefinedTag : nullTag;
      }
      return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
    }
    __name(baseGetTag, "baseGetTag");
    function getRawTag(value) {
      const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
      let unmasked = false;
      try {
        value[symToStringTag] = void 0;
        unmasked = true;
      } catch (e) {
      }
      const result = nativeObjectToString.call(value);
      if (unmasked) {
        if (isOwn) {
          value[symToStringTag] = tag;
        } else {
          delete value[symToStringTag];
        }
      }
      return result;
    }
    __name(getRawTag, "getRawTag");
    function objectToString(value) {
      return nativeObjectToString.call(value);
    }
    __name(objectToString, "objectToString");
  }
});

// node_modules/@opentelemetry/core/build/src/utils/merge.js
var require_merge = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/merge.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.merge = void 0;
    var lodash_merge_1 = require_lodash_merge();
    var MAX_LEVEL = 20;
    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;
    }
    __name(merge, "merge");
    exports.merge = merge;
    function takeValue(value) {
      if (isArray(value)) {
        return value.slice();
      }
      return value;
    }
    __name(takeValue, "takeValue");
    function mergeTwoObjects(one, two, level = 0, objects) {
      let result;
      if (level > MAX_LEVEL) {
        return void 0;
      }
      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];
            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];
            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;
    }
    __name(mergeTwoObjects, "mergeTwoObjects");
    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;
    }
    __name(wasObjectReferenced, "wasObjectReferenced");
    function isArray(value) {
      return Array.isArray(value);
    }
    __name(isArray, "isArray");
    function isFunction(value) {
      return typeof value === "function";
    }
    __name(isFunction, "isFunction");
    function isObject(value) {
      return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object";
    }
    __name(isObject, "isObject");
    function isPrimitive(value) {
      return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
    }
    __name(isPrimitive, "isPrimitive");
    function shouldMerge(one, two) {
      if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) {
        return false;
      }
      return true;
    }
    __name(shouldMerge, "shouldMerge");
  }
});

// node_modules/@opentelemetry/core/build/src/utils/timeout.js
var require_timeout = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/timeout.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.callWithTimeout = exports.TimeoutError = void 0;
    var TimeoutError = class _TimeoutError extends Error {
      static {
        __name(this, "TimeoutError");
      }
      constructor(message) {
        super(message);
        Object.setPrototypeOf(this, _TimeoutError.prototype);
      }
    };
    exports.TimeoutError = TimeoutError;
    function callWithTimeout(promise, timeout) {
      let timeoutHandle;
      const timeoutPromise = new Promise(/* @__PURE__ */ __name(function timeoutFunction(_resolve, reject) {
        timeoutHandle = setTimeout(/* @__PURE__ */ __name(function timeoutHandler() {
          reject(new TimeoutError("Operation timed out."));
        }, "timeoutHandler"), timeout);
      }, "timeoutFunction"));
      return Promise.race([promise, timeoutPromise]).then((result) => {
        clearTimeout(timeoutHandle);
        return result;
      }, (reason) => {
        clearTimeout(timeoutHandle);
        throw reason;
      });
    }
    __name(callWithTimeout, "callWithTimeout");
    exports.callWithTimeout = callWithTimeout;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/url.js
var require_url = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/url.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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);
      }
    }
    __name(urlMatches, "urlMatches");
    exports.urlMatches = urlMatches;
    function isUrlIgnored(url, ignoredUrls) {
      if (!ignoredUrls) {
        return false;
      }
      for (const ignoreUrl of ignoredUrls) {
        if (urlMatches(url, ignoreUrl)) {
          return true;
        }
      }
      return false;
    }
    __name(isUrlIgnored, "isUrlIgnored");
    exports.isUrlIgnored = isUrlIgnored;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/promise.js
var require_promise = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/promise.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Deferred = void 0;
    var Deferred = class {
      static {
        __name(this, "Deferred");
      }
      _promise;
      _resolve;
      _reject;
      constructor() {
        this._promise = new Promise((resolve2, reject) => {
          this._resolve = resolve2;
          this._reject = reject;
        });
      }
      get promise() {
        return this._promise;
      }
      resolve(val) {
        this._resolve(val);
      }
      reject(err) {
        this._reject(err);
      }
    };
    exports.Deferred = Deferred;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/callback.js
var require_callback = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/callback.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BindOnceFuture = void 0;
    var promise_1 = require_promise();
    var BindOnceFuture = class {
      static {
        __name(this, "BindOnceFuture");
      }
      _callback;
      _that;
      _isCalled = false;
      _deferred = new promise_1.Deferred();
      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;
  }
});

// node_modules/@opentelemetry/core/build/src/utils/configuration.js
var require_configuration = __commonJS({
  "node_modules/@opentelemetry/core/build/src/utils/configuration.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.diagLogLevelFromString = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var 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
    };
    function diagLogLevelFromString(value) {
      if (value == null) {
        return void 0;
      }
      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;
    }
    __name(diagLogLevelFromString, "diagLogLevelFromString");
    exports.diagLogLevelFromString = diagLogLevelFromString;
  }
});

// node_modules/@opentelemetry/core/build/src/internal/exporter.js
var require_exporter = __commonJS({
  "node_modules/@opentelemetry/core/build/src/internal/exporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports._export = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var suppress_tracing_1 = require_suppress_tracing();
    function _export(exporter, arg) {
      return new Promise((resolve2) => {
        api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => {
          exporter.export(arg, (result) => {
            resolve2(result);
          });
        });
      });
    }
    __name(_export, "_export");
    exports._export = _export;
  }
});

// node_modules/@opentelemetry/core/build/src/index.js
var require_src3 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.internal = 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.unrefTimer = exports.otperformance = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports._globalThis = exports.SDK_INFO = exports.parseKeyPairsIntoRecord = exports.ExportResultCode = exports.timeInputToHrTime = exports.millisToHrTime = exports.isTimeInputHrTime = exports.isTimeInput = exports.hrTimeToTimeStamp = 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;
    var W3CBaggagePropagator_1 = require_W3CBaggagePropagator();
    Object.defineProperty(exports, "W3CBaggagePropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CBaggagePropagator_1.W3CBaggagePropagator;
    }, "get") });
    var anchored_clock_1 = require_anchored_clock();
    Object.defineProperty(exports, "AnchoredClock", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return anchored_clock_1.AnchoredClock;
    }, "get") });
    var attributes_1 = require_attributes();
    Object.defineProperty(exports, "isAttributeValue", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return attributes_1.isAttributeValue;
    }, "get") });
    Object.defineProperty(exports, "sanitizeAttributes", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return attributes_1.sanitizeAttributes;
    }, "get") });
    var global_error_handler_1 = require_global_error_handler();
    Object.defineProperty(exports, "globalErrorHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return global_error_handler_1.globalErrorHandler;
    }, "get") });
    Object.defineProperty(exports, "setGlobalErrorHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return global_error_handler_1.setGlobalErrorHandler;
    }, "get") });
    var logging_error_handler_1 = require_logging_error_handler();
    Object.defineProperty(exports, "loggingErrorHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logging_error_handler_1.loggingErrorHandler;
    }, "get") });
    var time_1 = require_time();
    Object.defineProperty(exports, "addHrTimes", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.addHrTimes;
    }, "get") });
    Object.defineProperty(exports, "getTimeOrigin", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.getTimeOrigin;
    }, "get") });
    Object.defineProperty(exports, "hrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTime;
    }, "get") });
    Object.defineProperty(exports, "hrTimeDuration", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeDuration;
    }, "get") });
    Object.defineProperty(exports, "hrTimeToMicroseconds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToMicroseconds;
    }, "get") });
    Object.defineProperty(exports, "hrTimeToMilliseconds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToMilliseconds;
    }, "get") });
    Object.defineProperty(exports, "hrTimeToNanoseconds", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToNanoseconds;
    }, "get") });
    Object.defineProperty(exports, "hrTimeToTimeStamp", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.hrTimeToTimeStamp;
    }, "get") });
    Object.defineProperty(exports, "isTimeInput", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.isTimeInput;
    }, "get") });
    Object.defineProperty(exports, "isTimeInputHrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.isTimeInputHrTime;
    }, "get") });
    Object.defineProperty(exports, "millisToHrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.millisToHrTime;
    }, "get") });
    Object.defineProperty(exports, "timeInputToHrTime", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return time_1.timeInputToHrTime;
    }, "get") });
    var ExportResult_1 = require_ExportResult();
    Object.defineProperty(exports, "ExportResultCode", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ExportResult_1.ExportResultCode;
    }, "get") });
    var utils_1 = require_utils2();
    Object.defineProperty(exports, "parseKeyPairsIntoRecord", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.parseKeyPairsIntoRecord;
    }, "get") });
    var platform_1 = require_platform2();
    Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.SDK_INFO;
    }, "get") });
    Object.defineProperty(exports, "_globalThis", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1._globalThis;
    }, "get") });
    Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getStringFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getBooleanFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getNumberFromEnv;
    }, "get") });
    Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.getStringListFromEnv;
    }, "get") });
    Object.defineProperty(exports, "otperformance", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.otperformance;
    }, "get") });
    Object.defineProperty(exports, "unrefTimer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.unrefTimer;
    }, "get") });
    var composite_1 = require_composite();
    Object.defineProperty(exports, "CompositePropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return composite_1.CompositePropagator;
    }, "get") });
    var W3CTraceContextPropagator_1 = require_W3CTraceContextPropagator();
    Object.defineProperty(exports, "TRACE_PARENT_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.TRACE_PARENT_HEADER;
    }, "get") });
    Object.defineProperty(exports, "TRACE_STATE_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.TRACE_STATE_HEADER;
    }, "get") });
    Object.defineProperty(exports, "W3CTraceContextPropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.W3CTraceContextPropagator;
    }, "get") });
    Object.defineProperty(exports, "parseTraceParent", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return W3CTraceContextPropagator_1.parseTraceParent;
    }, "get") });
    var rpc_metadata_1 = require_rpc_metadata();
    Object.defineProperty(exports, "RPCType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.RPCType;
    }, "get") });
    Object.defineProperty(exports, "deleteRPCMetadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.deleteRPCMetadata;
    }, "get") });
    Object.defineProperty(exports, "getRPCMetadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.getRPCMetadata;
    }, "get") });
    Object.defineProperty(exports, "setRPCMetadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return rpc_metadata_1.setRPCMetadata;
    }, "get") });
    var suppress_tracing_1 = require_suppress_tracing();
    Object.defineProperty(exports, "isTracingSuppressed", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return suppress_tracing_1.isTracingSuppressed;
    }, "get") });
    Object.defineProperty(exports, "suppressTracing", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return suppress_tracing_1.suppressTracing;
    }, "get") });
    Object.defineProperty(exports, "unsuppressTracing", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return suppress_tracing_1.unsuppressTracing;
    }, "get") });
    var TraceState_1 = require_TraceState();
    Object.defineProperty(exports, "TraceState", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return TraceState_1.TraceState;
    }, "get") });
    var merge_1 = require_merge();
    Object.defineProperty(exports, "merge", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return merge_1.merge;
    }, "get") });
    var timeout_1 = require_timeout();
    Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return timeout_1.TimeoutError;
    }, "get") });
    Object.defineProperty(exports, "callWithTimeout", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return timeout_1.callWithTimeout;
    }, "get") });
    var url_1 = require_url();
    Object.defineProperty(exports, "isUrlIgnored", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return url_1.isUrlIgnored;
    }, "get") });
    Object.defineProperty(exports, "urlMatches", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return url_1.urlMatches;
    }, "get") });
    var callback_1 = require_callback();
    Object.defineProperty(exports, "BindOnceFuture", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return callback_1.BindOnceFuture;
    }, "get") });
    var configuration_1 = require_configuration();
    Object.defineProperty(exports, "diagLogLevelFromString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return configuration_1.diagLogLevelFromString;
    }, "get") });
    var exporter_1 = require_exporter();
    exports.internal = {
      _export: exporter_1._export
    };
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js
function isPartialSuccessResponse(response) {
  return Object.prototype.hasOwnProperty.call(response, "partialSuccess");
}
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 = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js"() {
    init_esbuild_shims();
    init_esm();
    __name(isPartialSuccessResponse, "isPartialSuccessResponse");
    __name(createLoggingPartialSuccessResponseHandler, "createLoggingPartialSuccessResponseHandler");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js
function createOtlpExportDelegate(components, settings) {
  return new OTLPExportDelegate(components.transport, components.serializer, createLoggingPartialSuccessResponseHandler(), components.promiseHandler, settings.timeout);
}
var import_core, OTLPExportDelegate;
var init_otlp_export_delegate = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js"() {
    init_esbuild_shims();
    import_core = __toESM(require_src3());
    init_types();
    init_logging_response_handler();
    init_esm();
    OTLPExportDelegate = class {
      static {
        __name(this, "OTLPExportDelegate");
      }
      _transport;
      _serializer;
      _responseHandler;
      _promiseQueue;
      _timeout;
      _diagLogger;
      constructor(_transport, _serializer, _responseHandler, _promiseQueue, _timeout) {
        this._transport = _transport;
        this._serializer = _serializer;
        this._responseHandler = _responseHandler;
        this._promiseQueue = _promiseQueue;
        this._timeout = _timeout;
        this._diagLogger = diag.createComponentLogger({
          namespace: "OTLPExportDelegate"
        });
      }
      export(internalRepresentation, resultCallback) {
        this._diagLogger.debug("items to be sent", internalRepresentation);
        if (this._promiseQueue.hasReachedLimit()) {
          resultCallback({
            code: import_core.ExportResultCode.FAILED,
            error: new Error("Concurrent export limit reached")
          });
          return;
        }
        const serializedRequest = this._serializer.serializeRequest(internalRepresentation);
        if (serializedRequest == null) {
          resultCallback({
            code: import_core.ExportResultCode.FAILED,
            error: new Error("Nothing to send")
          });
          return;
        }
        this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then((response) => {
          if (response.status === "success") {
            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_core.ExportResultCode.SUCCESS
            });
            return;
          } else if (response.status === "failure" && response.error) {
            resultCallback({
              code: import_core.ExportResultCode.FAILED,
              error: response.error
            });
            return;
          } else if (response.status === "retryable") {
            resultCallback({
              code: import_core.ExportResultCode.FAILED,
              error: new OTLPExporterError("Export failed with retryable status")
            });
          } else {
            resultCallback({
              code: import_core.ExportResultCode.FAILED,
              error: new OTLPExporterError("Export failed with unknown error")
            });
          }
        }, (reason) => resultCallback({
          code: import_core.ExportResultCode.FAILED,
          error: reason
        })));
      }
      forceFlush() {
        return this._promiseQueue.awaitAll();
      }
      async shutdown() {
        this._diagLogger.debug("shutdown started");
        await this.forceFlush();
        this._transport.shutdown();
      }
    };
    __name(createOtlpExportDelegate, "createOtlpExportDelegate");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-network-export-delegate.js
function createOtlpNetworkExportDelegate(options, serializer, transport) {
  return createOtlpExportDelegate({
    transport,
    serializer,
    promiseHandler: createBoundedQueueExportPromiseHandler(options)
  }, { timeout: options.timeoutMillis });
}
var init_otlp_network_export_delegate = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-network-export-delegate.js"() {
    init_esbuild_shims();
    init_bounded_queue_export_promise_handler();
    init_otlp_export_delegate();
    __name(createOtlpNetworkExportDelegate, "createOtlpNetworkExportDelegate");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/index.js
var esm_exports3 = {};
__export(esm_exports3, {
  CompressionAlgorithm: () => CompressionAlgorithm,
  OTLPExporterBase: () => OTLPExporterBase,
  OTLPExporterError: () => OTLPExporterError,
  createOtlpNetworkExportDelegate: () => createOtlpNetworkExportDelegate,
  getSharedConfigurationDefaults: () => getSharedConfigurationDefaults,
  mergeOtlpSharedConfigurationWithDefaults: () => mergeOtlpSharedConfigurationWithDefaults
});
var init_esm3 = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/index.js"() {
    init_esbuild_shims();
    init_OTLPExporterBase();
    init_types();
    init_shared_configuration();
    init_legacy_node_configuration();
    init_otlp_network_export_delegate();
  }
});

// node_modules/@grpc/grpc-js/build/src/constants.js
var require_constants2 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/constants.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = void 0;
    var Status;
    (function(Status2) {
      Status2[Status2["OK"] = 0] = "OK";
      Status2[Status2["CANCELLED"] = 1] = "CANCELLED";
      Status2[Status2["UNKNOWN"] = 2] = "UNKNOWN";
      Status2[Status2["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
      Status2[Status2["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
      Status2[Status2["NOT_FOUND"] = 5] = "NOT_FOUND";
      Status2[Status2["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
      Status2[Status2["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
      Status2[Status2["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
      Status2[Status2["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
      Status2[Status2["ABORTED"] = 10] = "ABORTED";
      Status2[Status2["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
      Status2[Status2["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
      Status2[Status2["INTERNAL"] = 13] = "INTERNAL";
      Status2[Status2["UNAVAILABLE"] = 14] = "UNAVAILABLE";
      Status2[Status2["DATA_LOSS"] = 15] = "DATA_LOSS";
      Status2[Status2["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
    })(Status || (exports.Status = Status = {}));
    var LogVerbosity;
    (function(LogVerbosity2) {
      LogVerbosity2[LogVerbosity2["DEBUG"] = 0] = "DEBUG";
      LogVerbosity2[LogVerbosity2["INFO"] = 1] = "INFO";
      LogVerbosity2[LogVerbosity2["ERROR"] = 2] = "ERROR";
      LogVerbosity2[LogVerbosity2["NONE"] = 3] = "NONE";
    })(LogVerbosity || (exports.LogVerbosity = LogVerbosity = {}));
    var Propagate;
    (function(Propagate2) {
      Propagate2[Propagate2["DEADLINE"] = 1] = "DEADLINE";
      Propagate2[Propagate2["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT";
      Propagate2[Propagate2["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT";
      Propagate2[Propagate2["CANCELLATION"] = 8] = "CANCELLATION";
      Propagate2[Propagate2["DEFAULTS"] = 65535] = "DEFAULTS";
    })(Propagate || (exports.Propagate = Propagate = {}));
    exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1;
    exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024;
  }
});

// node_modules/@grpc/grpc-js/package.json
var require_package = __commonJS({
  "node_modules/@grpc/grpc-js/package.json"(exports, module) {
    module.exports = {
      name: "@grpc/grpc-js",
      version: "1.14.4",
      description: "gRPC Library for Node - pure JS implementation",
      homepage: "https://grpc.io/",
      repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",
      main: "build/src/index.js",
      engines: {
        node: ">=12.10.0"
      },
      keywords: [],
      author: {
        name: "Google Inc."
      },
      types: "build/src/index.d.ts",
      license: "Apache-2.0",
      devDependencies: {
        "@grpc/proto-loader": "file:../proto-loader",
        "@types/gulp": "^4.0.17",
        "@types/gulp-mocha": "0.0.37",
        "@types/lodash": "^4.14.202",
        "@types/mocha": "^10.0.6",
        "@types/ncp": "^2.0.8",
        "@types/node": ">=20.11.20",
        "@types/pify": "^5.0.4",
        "@types/semver": "^7.5.8",
        "@typescript-eslint/eslint-plugin": "^7.1.0",
        "@typescript-eslint/parser": "^7.1.0",
        "@typescript-eslint/typescript-estree": "^7.1.0",
        "clang-format": "^1.8.0",
        eslint: "^8.42.0",
        "eslint-config-prettier": "^8.8.0",
        "eslint-plugin-node": "^11.1.0",
        "eslint-plugin-prettier": "^4.2.1",
        execa: "^2.0.3",
        gulp: "^4.0.2",
        "gulp-mocha": "^6.0.0",
        lodash: "^4.17.21",
        madge: "^5.0.1",
        "mocha-jenkins-reporter": "^0.4.1",
        ncp: "^2.0.0",
        pify: "^4.0.1",
        prettier: "^2.8.8",
        rimraf: "^3.0.2",
        semver: "^7.6.0",
        "ts-node": "^10.9.2",
        typescript: "^5.3.3"
      },
      contributors: [
        {
          name: "Google Inc."
        }
      ],
      scripts: {
        build: "npm run compile",
        clean: "rimraf ./build",
        compile: "tsc -p .",
        format: 'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',
        lint: "eslint src/*.ts test/*.ts",
        prepare: "npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",
        test: "gulp test",
        check: "npm run lint",
        fix: "eslint --fix src/*.ts test/*.ts",
        pretest: "npm run generate-types && npm run generate-test-types && npm run compile",
        posttest: "npm run check && madge -c ./build/src",
        "generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto",
        "generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto",
        "copy-protos": "node ./copy-protos"
      },
      dependencies: {
        "@grpc/proto-loader": "^0.8.0",
        "@js-sdsl/ordered-map": "^4.4.2"
      },
      files: [
        "src/**/*.ts",
        "build/src/**/*.{js,d.ts,js.map}",
        "proto/**/*.proto",
        "proto/**/LICENSE",
        "LICENSE",
        "deps/envoy-api/envoy/api/v2/**/*.proto",
        "deps/envoy-api/envoy/config/**/*.proto",
        "deps/envoy-api/envoy/service/**/*.proto",
        "deps/envoy-api/envoy/type/**/*.proto",
        "deps/udpa/udpa/**/*.proto",
        "deps/googleapis/google/api/*.proto",
        "deps/googleapis/google/rpc/*.proto",
        "deps/protoc-gen-validate/validate/**/*.proto"
      ]
    };
  }
});

// node_modules/@grpc/grpc-js/build/src/logging.js
var require_logging = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/logging.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var _a;
    var _b;
    var _c;
    var _d;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = void 0;
    exports.trace = trace2;
    exports.isTracerEnabled = isTracerEnabled;
    var constants_1 = require_constants2();
    var process_1 = __require("process");
    var clientVersion = require_package().version;
    var DEFAULT_LOGGER = {
      error: /* @__PURE__ */ __name((message, ...optionalParams) => {
        console.error("E " + message, ...optionalParams);
      }, "error"),
      info: /* @__PURE__ */ __name((message, ...optionalParams) => {
        console.error("I " + message, ...optionalParams);
      }, "info"),
      debug: /* @__PURE__ */ __name((message, ...optionalParams) => {
        console.error("D " + message, ...optionalParams);
      }, "debug")
    };
    var _logger = DEFAULT_LOGGER;
    var _logVerbosity = constants_1.LogVerbosity.ERROR;
    var verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : "";
    switch (verbosityString.toUpperCase()) {
      case "DEBUG":
        _logVerbosity = constants_1.LogVerbosity.DEBUG;
        break;
      case "INFO":
        _logVerbosity = constants_1.LogVerbosity.INFO;
        break;
      case "ERROR":
        _logVerbosity = constants_1.LogVerbosity.ERROR;
        break;
      case "NONE":
        _logVerbosity = constants_1.LogVerbosity.NONE;
        break;
      default:
    }
    var getLogger = /* @__PURE__ */ __name(() => {
      return _logger;
    }, "getLogger");
    exports.getLogger = getLogger;
    var setLogger = /* @__PURE__ */ __name((logger) => {
      _logger = logger;
    }, "setLogger");
    exports.setLogger = setLogger;
    var setLoggerVerbosity = /* @__PURE__ */ __name((verbosity) => {
      _logVerbosity = verbosity;
    }, "setLoggerVerbosity");
    exports.setLoggerVerbosity = setLoggerVerbosity;
    var log = /* @__PURE__ */ __name((severity, ...args) => {
      let logFunction;
      if (severity >= _logVerbosity) {
        switch (severity) {
          case constants_1.LogVerbosity.DEBUG:
            logFunction = _logger.debug;
            break;
          case constants_1.LogVerbosity.INFO:
            logFunction = _logger.info;
            break;
          case constants_1.LogVerbosity.ERROR:
            logFunction = _logger.error;
            break;
        }
        if (!logFunction) {
          logFunction = _logger.error;
        }
        if (logFunction) {
          logFunction.bind(_logger)(...args);
        }
      }
    }, "log");
    exports.log = log;
    var tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : "";
    var enabledTracers = /* @__PURE__ */ new Set();
    var disabledTracers = /* @__PURE__ */ new Set();
    for (const tracerName of tracersString.split(",")) {
      if (tracerName.startsWith("-")) {
        disabledTracers.add(tracerName.substring(1));
      } else {
        enabledTracers.add(tracerName);
      }
    }
    var allEnabled = enabledTracers.has("all");
    function trace2(severity, tracer2, text) {
      if (isTracerEnabled(tracer2)) {
        (0, exports.log)(severity, (/* @__PURE__ */ new Date()).toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer2 + " | " + text);
      }
    }
    __name(trace2, "trace");
    function isTracerEnabled(tracer2) {
      return !disabledTracers.has(tracer2) && (allEnabled || enabledTracers.has(tracer2));
    }
    __name(isTracerEnabled, "isTracerEnabled");
  }
});

// node_modules/@grpc/grpc-js/build/src/error.js
var require_error = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/error.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getErrorMessage = getErrorMessage2;
    exports.getErrorCode = getErrorCode;
    function getErrorMessage2(error) {
      if (error instanceof Error) {
        return error.message;
      } else {
        return String(error);
      }
    }
    __name(getErrorMessage2, "getErrorMessage");
    function getErrorCode(error) {
      if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "number") {
        return error.code;
      } else {
        return null;
      }
    }
    __name(getErrorCode, "getErrorCode");
  }
});

// node_modules/@grpc/grpc-js/build/src/metadata.js
var require_metadata = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/metadata.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Metadata = void 0;
    var logging_1 = require_logging();
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/;
    var LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;
    function isLegalKey(key) {
      return LEGAL_KEY_REGEX.test(key);
    }
    __name(isLegalKey, "isLegalKey");
    function isLegalNonBinaryValue(value) {
      return LEGAL_NON_BINARY_VALUE_REGEX.test(value);
    }
    __name(isLegalNonBinaryValue, "isLegalNonBinaryValue");
    function isBinaryKey(key) {
      return key.endsWith("-bin");
    }
    __name(isBinaryKey, "isBinaryKey");
    function isCustomMetadata(key) {
      return !key.startsWith("grpc-");
    }
    __name(isCustomMetadata, "isCustomMetadata");
    function normalizeKey(key) {
      return key.toLowerCase();
    }
    __name(normalizeKey, "normalizeKey");
    function validate(key, value) {
      if (!isLegalKey(key)) {
        throw new Error('Metadata key "' + key + '" contains illegal characters');
      }
      if (value !== null && value !== void 0) {
        if (isBinaryKey(key)) {
          if (!Buffer.isBuffer(value)) {
            throw new Error("keys that end with '-bin' must have Buffer values");
          }
        } else {
          if (Buffer.isBuffer(value)) {
            throw new Error("keys that don't end with '-bin' must have String values");
          }
          if (!isLegalNonBinaryValue(value)) {
            throw new Error('Metadata string value "' + value + '" contains illegal characters');
          }
        }
      }
    }
    __name(validate, "validate");
    var Metadata = class _Metadata {
      static {
        __name(this, "Metadata");
      }
      constructor(options = {}) {
        this.internalRepr = /* @__PURE__ */ new Map();
        this.opaqueData = /* @__PURE__ */ new Map();
        this.options = options;
      }
      /**
       * Sets the given value for the given key by replacing any other values
       * associated with that key. Normalizes the key.
       * @param key The key to whose value should be set.
       * @param value The value to set. Must be a buffer if and only
       *   if the normalized key ends with '-bin'.
       */
      set(key, value) {
        key = normalizeKey(key);
        validate(key, value);
        this.internalRepr.set(key, [value]);
      }
      /**
       * Adds the given value for the given key by appending to a list of previous
       * values associated with that key. Normalizes the key.
       * @param key The key for which a new value should be appended.
       * @param value The value to add. Must be a buffer if and only
       *   if the normalized key ends with '-bin'.
       */
      add(key, value) {
        key = normalizeKey(key);
        validate(key, value);
        const existingValue = this.internalRepr.get(key);
        if (existingValue === void 0) {
          this.internalRepr.set(key, [value]);
        } else {
          existingValue.push(value);
        }
      }
      /**
       * Removes the given key and any associated values. Normalizes the key.
       * @param key The key whose values should be removed.
       */
      remove(key) {
        key = normalizeKey(key);
        this.internalRepr.delete(key);
      }
      /**
       * Gets a list of all values associated with the key. Normalizes the key.
       * @param key The key whose value should be retrieved.
       * @return A list of values associated with the given key.
       */
      get(key) {
        key = normalizeKey(key);
        return this.internalRepr.get(key) || [];
      }
      /**
       * Gets a plain object mapping each key to the first value associated with it.
       * This reflects the most common way that people will want to see metadata.
       * @return A key/value mapping of the metadata.
       */
      getMap() {
        const result = {};
        for (const [key, values] of this.internalRepr) {
          if (values.length > 0) {
            const v = values[0];
            result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v;
          }
        }
        return result;
      }
      /**
       * Clones the metadata object.
       * @return The newly cloned object.
       */
      clone() {
        const newMetadata = new _Metadata(this.options);
        const newInternalRepr = newMetadata.internalRepr;
        for (const [key, value] of this.internalRepr) {
          const clonedValue = value.map((v) => {
            if (Buffer.isBuffer(v)) {
              return Buffer.from(v);
            } else {
              return v;
            }
          });
          newInternalRepr.set(key, clonedValue);
        }
        return newMetadata;
      }
      /**
       * Merges all key-value pairs from a given Metadata object into this one.
       * If both this object and the given object have values in the same key,
       * values from the other Metadata object will be appended to this object's
       * values.
       * @param other A Metadata object.
       */
      merge(other) {
        for (const [key, values] of other.internalRepr) {
          const mergedValue = (this.internalRepr.get(key) || []).concat(values);
          this.internalRepr.set(key, mergedValue);
        }
      }
      setOptions(options) {
        this.options = options;
      }
      getOptions() {
        return this.options;
      }
      /**
       * Creates an OutgoingHttpHeaders object that can be used with the http2 API.
       */
      toHttp2Headers() {
        const result = {};
        for (const [key, values] of this.internalRepr) {
          if (key.startsWith(":")) {
            continue;
          }
          result[key] = values.map(bufToString);
        }
        return result;
      }
      /**
       * This modifies the behavior of JSON.stringify to show an object
       * representation of the metadata map.
       */
      toJSON() {
        const result = {};
        for (const [key, values] of this.internalRepr) {
          result[key] = values;
        }
        return result;
      }
      /**
       * Attach additional data of any type to the metadata object, which will not
       * be included when sending headers. The data can later be retrieved with
       * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this
       * library.
       * @param key
       * @param value
       */
      setOpaque(key, value) {
        this.opaqueData.set(key, value);
      }
      /**
       * Retrieve data previously added with `setOpaque`.
       * @param key
       * @returns
       */
      getOpaque(key) {
        return this.opaqueData.get(key);
      }
      /**
       * Returns a new Metadata object based fields in a given IncomingHttpHeaders
       * object.
       * @param headers An IncomingHttpHeaders object.
       */
      static fromHttp2Headers(headers) {
        const result = new _Metadata();
        for (const key of Object.keys(headers)) {
          if (key.charAt(0) === ":") {
            continue;
          }
          const values = headers[key];
          try {
            if (isBinaryKey(key)) {
              if (Array.isArray(values)) {
                values.forEach((value) => {
                  result.add(key, Buffer.from(value, "base64"));
                });
              } else if (values !== void 0) {
                if (isCustomMetadata(key)) {
                  values.split(",").forEach((v) => {
                    result.add(key, Buffer.from(v.trim(), "base64"));
                  });
                } else {
                  result.add(key, Buffer.from(values, "base64"));
                }
              }
            } else {
              if (Array.isArray(values)) {
                values.forEach((value) => {
                  result.add(key, value);
                });
              } else if (values !== void 0) {
                result.add(key, values);
              }
            }
          } catch (error) {
            const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;
            (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message);
          }
        }
        return result;
      }
    };
    exports.Metadata = Metadata;
    var bufToString = /* @__PURE__ */ __name((val) => {
      return Buffer.isBuffer(val) ? val.toString("base64") : val;
    }, "bufToString");
  }
});

// node_modules/@grpc/grpc-js/build/src/call-credentials.js
var require_call_credentials = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call-credentials.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CallCredentials = void 0;
    var metadata_1 = require_metadata();
    function isCurrentOauth2Client(client) {
      return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function";
    }
    __name(isCurrentOauth2Client, "isCurrentOauth2Client");
    var CallCredentials = class _CallCredentials {
      static {
        __name(this, "CallCredentials");
      }
      /**
       * Creates a new CallCredentials object from a given function that generates
       * Metadata objects.
       * @param metadataGenerator A function that accepts a set of options, and
       * generates a Metadata object based on these options, which is passed back
       * to the caller via a supplied (err, metadata) callback.
       */
      static createFromMetadataGenerator(metadataGenerator) {
        return new SingleCallCredentials(metadataGenerator);
      }
      /**
       * Create a gRPC credential from a Google credential object.
       * @param googleCredentials The authentication client to use.
       * @return The resulting CallCredentials object.
       */
      static createFromGoogleCredential(googleCredentials) {
        return _CallCredentials.createFromMetadataGenerator((options, callback) => {
          let getHeaders;
          if (isCurrentOauth2Client(googleCredentials)) {
            getHeaders = googleCredentials.getRequestHeaders(options.service_url);
          } else {
            getHeaders = new Promise((resolve2, reject) => {
              googleCredentials.getRequestMetadata(options.service_url, (err, headers) => {
                if (err) {
                  reject(err);
                  return;
                }
                if (!headers) {
                  reject(new Error("Headers not set by metadata plugin"));
                  return;
                }
                resolve2(headers);
              });
            });
          }
          getHeaders.then((headers) => {
            const metadata = new metadata_1.Metadata();
            for (const key of Object.keys(headers)) {
              metadata.add(key, headers[key]);
            }
            callback(null, metadata);
          }, (err) => {
            callback(err);
          });
        });
      }
      static createEmpty() {
        return new EmptyCallCredentials();
      }
    };
    exports.CallCredentials = CallCredentials;
    var ComposedCallCredentials = class _ComposedCallCredentials extends CallCredentials {
      static {
        __name(this, "ComposedCallCredentials");
      }
      constructor(creds) {
        super();
        this.creds = creds;
      }
      async generateMetadata(options) {
        const base = new metadata_1.Metadata();
        const generated = await Promise.all(this.creds.map((cred) => cred.generateMetadata(options)));
        for (const gen of generated) {
          base.merge(gen);
        }
        return base;
      }
      compose(other) {
        return new _ComposedCallCredentials(this.creds.concat([other]));
      }
      _equals(other) {
        if (this === other) {
          return true;
        }
        if (other instanceof _ComposedCallCredentials) {
          return this.creds.every((value, index) => value._equals(other.creds[index]));
        } else {
          return false;
        }
      }
    };
    var SingleCallCredentials = class _SingleCallCredentials extends CallCredentials {
      static {
        __name(this, "SingleCallCredentials");
      }
      constructor(metadataGenerator) {
        super();
        this.metadataGenerator = metadataGenerator;
      }
      generateMetadata(options) {
        return new Promise((resolve2, reject) => {
          this.metadataGenerator(options, (err, metadata) => {
            if (metadata !== void 0) {
              resolve2(metadata);
            } else {
              reject(err);
            }
          });
        });
      }
      compose(other) {
        return new ComposedCallCredentials([this, other]);
      }
      _equals(other) {
        if (this === other) {
          return true;
        }
        if (other instanceof _SingleCallCredentials) {
          return this.metadataGenerator === other.metadataGenerator;
        } else {
          return false;
        }
      }
    };
    var EmptyCallCredentials = class _EmptyCallCredentials extends CallCredentials {
      static {
        __name(this, "EmptyCallCredentials");
      }
      generateMetadata(options) {
        return Promise.resolve(new metadata_1.Metadata());
      }
      compose(other) {
        return other;
      }
      _equals(other) {
        return other instanceof _EmptyCallCredentials;
      }
    };
  }
});

// node_modules/@grpc/grpc-js/build/src/tls-helpers.js
var require_tls_helpers = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/tls-helpers.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CIPHER_SUITES = void 0;
    exports.getDefaultRootsData = getDefaultRootsData;
    var fs9 = __require("fs");
    exports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES;
    var DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH;
    var defaultRootsData = null;
    function getDefaultRootsData() {
      if (DEFAULT_ROOTS_FILE_PATH) {
        if (defaultRootsData === null) {
          defaultRootsData = fs9.readFileSync(DEFAULT_ROOTS_FILE_PATH);
        }
        return defaultRootsData;
      }
      return null;
    }
    __name(getDefaultRootsData, "getDefaultRootsData");
  }
});

// node_modules/@grpc/grpc-js/build/src/uri-parser.js
var require_uri_parser = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/uri-parser.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseUri = parseUri;
    exports.splitHostPort = splitHostPort;
    exports.combineHostPort = combineHostPort;
    exports.uriToString = uriToString;
    var URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;
    function parseUri(uriString) {
      const parsedUri = URI_REGEX.exec(uriString);
      if (parsedUri === null) {
        return null;
      }
      return {
        scheme: parsedUri[1],
        authority: parsedUri[2],
        path: parsedUri[3]
      };
    }
    __name(parseUri, "parseUri");
    var NUMBER_REGEX = /^\d+$/;
    function splitHostPort(path11) {
      if (path11.startsWith("[")) {
        const hostEnd = path11.indexOf("]");
        if (hostEnd === -1) {
          return null;
        }
        const host = path11.substring(1, hostEnd);
        if (host.indexOf(":") === -1) {
          return null;
        }
        if (path11.length > hostEnd + 1) {
          if (path11[hostEnd + 1] === ":") {
            const portString = path11.substring(hostEnd + 2);
            if (NUMBER_REGEX.test(portString)) {
              return {
                host,
                port: +portString
              };
            } else {
              return null;
            }
          } else {
            return null;
          }
        } else {
          return {
            host
          };
        }
      } else {
        const splitPath = path11.split(":");
        if (splitPath.length === 2) {
          if (NUMBER_REGEX.test(splitPath[1])) {
            return {
              host: splitPath[0],
              port: +splitPath[1]
            };
          } else {
            return null;
          }
        } else {
          return {
            host: path11
          };
        }
      }
    }
    __name(splitHostPort, "splitHostPort");
    function combineHostPort(hostPort) {
      if (hostPort.port === void 0) {
        return hostPort.host;
      } else {
        if (hostPort.host.includes(":")) {
          return `[${hostPort.host}]:${hostPort.port}`;
        } else {
          return `${hostPort.host}:${hostPort.port}`;
        }
      }
    }
    __name(combineHostPort, "combineHostPort");
    function uriToString(uri) {
      let result = "";
      if (uri.scheme !== void 0) {
        result += uri.scheme + ":";
      }
      if (uri.authority !== void 0) {
        result += "//" + uri.authority + "/";
      }
      result += uri.path;
      return result;
    }
    __name(uriToString, "uriToString");
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver.js
var require_resolver = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0;
    exports.registerResolver = registerResolver;
    exports.registerDefaultScheme = registerDefaultScheme;
    exports.createResolver = createResolver;
    exports.getDefaultAuthority = getDefaultAuthority;
    exports.mapUriDefaultScheme = mapUriDefaultScheme;
    var uri_parser_1 = require_uri_parser();
    exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = "grpc.internal.config_selector";
    var registeredResolvers = {};
    var defaultScheme = null;
    function registerResolver(scheme, resolverClass) {
      registeredResolvers[scheme] = resolverClass;
    }
    __name(registerResolver, "registerResolver");
    function registerDefaultScheme(scheme) {
      defaultScheme = scheme;
    }
    __name(registerDefaultScheme, "registerDefaultScheme");
    function createResolver(target, listener, options) {
      if (target.scheme !== void 0 && target.scheme in registeredResolvers) {
        return new registeredResolvers[target.scheme](target, listener, options);
      } else {
        throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`);
      }
    }
    __name(createResolver, "createResolver");
    function getDefaultAuthority(target) {
      if (target.scheme !== void 0 && target.scheme in registeredResolvers) {
        return registeredResolvers[target.scheme].getDefaultAuthority(target);
      } else {
        throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`);
      }
    }
    __name(getDefaultAuthority, "getDefaultAuthority");
    function mapUriDefaultScheme(target) {
      if (target.scheme === void 0 || !(target.scheme in registeredResolvers)) {
        if (defaultScheme !== null) {
          return {
            scheme: defaultScheme,
            authority: void 0,
            path: (0, uri_parser_1.uriToString)(target)
          };
        } else {
          return null;
        }
      }
      return target;
    }
    __name(mapUriDefaultScheme, "mapUriDefaultScheme");
  }
});

// node_modules/@grpc/grpc-js/build/src/channel-credentials.js
var require_channel_credentials = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channel-credentials.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChannelCredentials = void 0;
    exports.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials;
    var tls_1 = __require("tls");
    var call_credentials_1 = require_call_credentials();
    var tls_helpers_1 = require_tls_helpers();
    var uri_parser_1 = require_uri_parser();
    var resolver_1 = require_resolver();
    var logging_1 = require_logging();
    var constants_1 = require_constants2();
    function verifyIsBufferOrNull(obj, friendlyName) {
      if (obj && !(obj instanceof Buffer)) {
        throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`);
      }
    }
    __name(verifyIsBufferOrNull, "verifyIsBufferOrNull");
    var ChannelCredentials = class {
      static {
        __name(this, "ChannelCredentials");
      }
      /**
       * Returns a copy of this object with the included set of per-call credentials
       * expanded to include callCredentials.
       * @param callCredentials A CallCredentials object to associate with this
       * instance.
       */
      compose(callCredentials) {
        return new ComposedChannelCredentialsImpl(this, callCredentials);
      }
      /**
       * Return a new ChannelCredentials instance with a given set of credentials.
       * The resulting instance can be used to construct a Channel that communicates
       * over TLS.
       * @param rootCerts The root certificate data.
       * @param privateKey The client certificate private key, if available.
       * @param certChain The client certificate key chain, if available.
       * @param verifyOptions Additional options to modify certificate verification
       */
      static createSsl(rootCerts, privateKey, certChain, verifyOptions) {
        var _a;
        verifyIsBufferOrNull(rootCerts, "Root certificate");
        verifyIsBufferOrNull(privateKey, "Private key");
        verifyIsBufferOrNull(certChain, "Certificate chain");
        if (privateKey && !certChain) {
          throw new Error("Private key must be given with accompanying certificate chain");
        }
        if (!privateKey && certChain) {
          throw new Error("Certificate chain must be given with accompanying private key");
        }
        const secureContext = (0, tls_1.createSecureContext)({
          ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : void 0,
          key: privateKey !== null && privateKey !== void 0 ? privateKey : void 0,
          cert: certChain !== null && certChain !== void 0 ? certChain : void 0,
          ciphers: tls_helpers_1.CIPHER_SUITES
        });
        return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
      }
      /**
       * Return a new ChannelCredentials instance with credentials created using
       * the provided secureContext. The resulting instances can be used to
       * construct a Channel that communicates over TLS. gRPC will not override
       * anything in the provided secureContext, so the environment variables
       * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will
       * not be applied.
       * @param secureContext The return value of tls.createSecureContext()
       * @param verifyOptions Additional options to modify certificate verification
       */
      static createFromSecureContext(secureContext, verifyOptions) {
        return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
      }
      /**
       * Return a new ChannelCredentials instance with no credentials.
       */
      static createInsecure() {
        return new InsecureChannelCredentialsImpl();
      }
    };
    exports.ChannelCredentials = ChannelCredentials;
    var InsecureChannelCredentialsImpl = class _InsecureChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "InsecureChannelCredentialsImpl");
      }
      constructor() {
        super();
      }
      compose(callCredentials) {
        throw new Error("Cannot compose insecure credentials");
      }
      _isSecure() {
        return false;
      }
      _equals(other) {
        return other instanceof _InsecureChannelCredentialsImpl;
      }
      _createSecureConnector(channelTarget, options, callCredentials) {
        return {
          connect(socket) {
            return Promise.resolve({
              socket,
              secure: false
            });
          },
          waitForReady: /* @__PURE__ */ __name(() => {
            return Promise.resolve();
          }, "waitForReady"),
          getCallCredentials: /* @__PURE__ */ __name(() => {
            return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty();
          }, "getCallCredentials"),
          destroy() {
          }
        };
      }
    };
    function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) {
      var _a, _b;
      const connectionOptions = {
        secureContext
      };
      let realTarget = channelTarget;
      if ("grpc.http_connect_target" in options) {
        const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]);
        if (parsedTarget) {
          realTarget = parsedTarget;
        }
      }
      const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget);
      const hostPort = (0, uri_parser_1.splitHostPort)(targetPath);
      const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath;
      connectionOptions.host = remoteHost;
      if (verifyOptions.checkServerIdentity) {
        connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity;
      }
      if (verifyOptions.rejectUnauthorized !== void 0) {
        connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized;
      }
      connectionOptions.ALPNProtocols = ["h2"];
      if (options["grpc.ssl_target_name_override"]) {
        const sslTargetNameOverride = options["grpc.ssl_target_name_override"];
        const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity;
        connectionOptions.checkServerIdentity = (host, cert) => {
          return originalCheckServerIdentity(sslTargetNameOverride, cert);
        };
        connectionOptions.servername = sslTargetNameOverride;
      } else {
        connectionOptions.servername = remoteHost;
      }
      if (options["grpc-node.tls_enable_trace"]) {
        connectionOptions.enableTrace = true;
      }
      return connectionOptions;
    }
    __name(getConnectionOptions, "getConnectionOptions");
    var SecureConnectorImpl = class {
      static {
        __name(this, "SecureConnectorImpl");
      }
      constructor(connectionOptions, callCredentials) {
        this.connectionOptions = connectionOptions;
        this.callCredentials = callCredentials;
      }
      connect(socket) {
        const tlsConnectOptions = Object.assign({ socket }, this.connectionOptions);
        return new Promise((resolve2, reject) => {
          const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => {
            var _a;
            if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) {
              reject(tlsSocket.authorizationError);
              return;
            }
            resolve2({
              socket: tlsSocket,
              secure: true
            });
          });
          tlsSocket.on("error", (error) => {
            reject(error);
          });
        });
      }
      waitForReady() {
        return Promise.resolve();
      }
      getCallCredentials() {
        return this.callCredentials;
      }
      destroy() {
      }
    };
    var SecureChannelCredentialsImpl = class _SecureChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "SecureChannelCredentialsImpl");
      }
      constructor(secureContext, verifyOptions) {
        super();
        this.secureContext = secureContext;
        this.verifyOptions = verifyOptions;
      }
      _isSecure() {
        return true;
      }
      _equals(other) {
        if (this === other) {
          return true;
        }
        if (other instanceof _SecureChannelCredentialsImpl) {
          return this.secureContext === other.secureContext && this.verifyOptions.checkServerIdentity === other.verifyOptions.checkServerIdentity;
        } else {
          return false;
        }
      }
      _createSecureConnector(channelTarget, options, callCredentials) {
        const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options);
        return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty());
      }
    };
    var CertificateProviderChannelCredentialsImpl = class _CertificateProviderChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "CertificateProviderChannelCredentialsImpl");
      }
      constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) {
        super();
        this.caCertificateProvider = caCertificateProvider;
        this.identityCertificateProvider = identityCertificateProvider;
        this.verifyOptions = verifyOptions;
        this.refcount = 0;
        this.latestCaUpdate = void 0;
        this.latestIdentityUpdate = void 0;
        this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this);
        this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this);
        this.secureContextWatchers = [];
      }
      _isSecure() {
        return true;
      }
      _equals(other) {
        var _a, _b;
        if (this === other) {
          return true;
        }
        if (other instanceof _CertificateProviderChannelCredentialsImpl) {
          return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && ((_a = this.verifyOptions) === null || _a === void 0 ? void 0 : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === void 0 ? void 0 : _b.checkServerIdentity);
        } else {
          return false;
        }
      }
      ref() {
        var _a;
        if (this.refcount === 0) {
          this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener);
          (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        this.refcount += 1;
      }
      unref() {
        var _a;
        this.refcount -= 1;
        if (this.refcount === 0) {
          this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener);
          (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
      }
      _createSecureConnector(channelTarget, options, callCredentials) {
        this.ref();
        return new _CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty());
      }
      maybeUpdateWatchers() {
        if (this.hasReceivedUpdates()) {
          for (const watcher of this.secureContextWatchers) {
            watcher(this.getLatestSecureContext());
          }
          this.secureContextWatchers = [];
        }
      }
      handleCaCertificateUpdate(update) {
        this.latestCaUpdate = update;
        this.maybeUpdateWatchers();
      }
      handleIdentityCertitificateUpdate(update) {
        this.latestIdentityUpdate = update;
        this.maybeUpdateWatchers();
      }
      hasReceivedUpdates() {
        if (this.latestCaUpdate === void 0) {
          return false;
        }
        if (this.identityCertificateProvider && this.latestIdentityUpdate === void 0) {
          return false;
        }
        return true;
      }
      getSecureContext() {
        if (this.hasReceivedUpdates()) {
          return Promise.resolve(this.getLatestSecureContext());
        } else {
          return new Promise((resolve2) => {
            this.secureContextWatchers.push(resolve2);
          });
        }
      }
      getLatestSecureContext() {
        var _a, _b;
        if (!this.latestCaUpdate) {
          return null;
        }
        if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) {
          return null;
        }
        try {
          return (0, tls_1.createSecureContext)({
            ca: this.latestCaUpdate.caCertificate,
            key: (_a = this.latestIdentityUpdate) === null || _a === void 0 ? void 0 : _a.privateKey,
            cert: (_b = this.latestIdentityUpdate) === null || _b === void 0 ? void 0 : _b.certificate,
            ciphers: tls_helpers_1.CIPHER_SUITES
          });
        } catch (e) {
          (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to createSecureContext with error " + e.message);
          return null;
        }
      }
    };
    CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class {
      constructor(parent, channelTarget, options, callCredentials) {
        this.parent = parent;
        this.channelTarget = channelTarget;
        this.options = options;
        this.callCredentials = callCredentials;
      }
      connect(socket) {
        return new Promise((resolve2, reject) => {
          const secureContext = this.parent.getLatestSecureContext();
          if (!secureContext) {
            reject(new Error("Failed to load credentials"));
            return;
          }
          if (socket.closed) {
            reject(new Error("Socket closed while loading credentials"));
          }
          const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options);
          const tlsConnectOptions = Object.assign({ socket }, connnectionOptions);
          const closeCallback = /* @__PURE__ */ __name(() => {
            reject(new Error("Socket closed"));
          }, "closeCallback");
          const errorCallback = /* @__PURE__ */ __name((error) => {
            reject(error);
          }, "errorCallback");
          const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => {
            var _a;
            tlsSocket.removeListener("close", closeCallback);
            tlsSocket.removeListener("error", errorCallback);
            if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) {
              reject(tlsSocket.authorizationError);
              return;
            }
            resolve2({
              socket: tlsSocket,
              secure: true
            });
          });
          tlsSocket.once("close", closeCallback);
          tlsSocket.once("error", errorCallback);
        });
      }
      async waitForReady() {
        await this.parent.getSecureContext();
      }
      getCallCredentials() {
        return this.callCredentials;
      }
      destroy() {
        this.parent.unref();
      }
    };
    function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) {
      return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {});
    }
    __name(createCertificateProviderChannelCredentials, "createCertificateProviderChannelCredentials");
    var ComposedChannelCredentialsImpl = class _ComposedChannelCredentialsImpl extends ChannelCredentials {
      static {
        __name(this, "ComposedChannelCredentialsImpl");
      }
      constructor(channelCredentials, callCredentials) {
        super();
        this.channelCredentials = channelCredentials;
        this.callCredentials = callCredentials;
        if (!channelCredentials._isSecure()) {
          throw new Error("Cannot compose insecure credentials");
        }
      }
      compose(callCredentials) {
        const combinedCallCredentials = this.callCredentials.compose(callCredentials);
        return new _ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials);
      }
      _isSecure() {
        return true;
      }
      _equals(other) {
        if (this === other) {
          return true;
        }
        if (other instanceof _ComposedChannelCredentialsImpl) {
          return this.channelCredentials._equals(other.channelCredentials) && this.callCredentials._equals(other.callCredentials);
        } else {
          return false;
        }
      }
      _createSecureConnector(channelTarget, options, callCredentials) {
        const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty());
        return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials);
      }
    };
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer.js
var require_load_balancer = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createChildChannelControlHelper = createChildChannelControlHelper;
    exports.registerLoadBalancerType = registerLoadBalancerType;
    exports.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType;
    exports.createLoadBalancer = createLoadBalancer;
    exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered;
    exports.parseLoadBalancingConfig = parseLoadBalancingConfig;
    exports.getDefaultConfig = getDefaultConfig;
    exports.selectLbConfigFromList = selectLbConfigFromList;
    var logging_1 = require_logging();
    var constants_1 = require_constants2();
    function createChildChannelControlHelper(parent, overrides) {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
      return {
        createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent),
        updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent),
        requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent),
        addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent),
        removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent)
      };
    }
    __name(createChildChannelControlHelper, "createChildChannelControlHelper");
    var registeredLoadBalancerTypes = {};
    var defaultLoadBalancerType = null;
    function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) {
      registeredLoadBalancerTypes[typeName] = {
        LoadBalancer: loadBalancerType,
        LoadBalancingConfig: loadBalancingConfigType
      };
    }
    __name(registerLoadBalancerType, "registerLoadBalancerType");
    function registerDefaultLoadBalancerType(typeName) {
      defaultLoadBalancerType = typeName;
    }
    __name(registerDefaultLoadBalancerType, "registerDefaultLoadBalancerType");
    function createLoadBalancer(config, channelControlHelper) {
      const typeName = config.getLoadBalancerName();
      if (typeName in registeredLoadBalancerTypes) {
        return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper);
      } else {
        return null;
      }
    }
    __name(createLoadBalancer, "createLoadBalancer");
    function isLoadBalancerNameRegistered(typeName) {
      return typeName in registeredLoadBalancerTypes;
    }
    __name(isLoadBalancerNameRegistered, "isLoadBalancerNameRegistered");
    function parseLoadBalancingConfig(rawConfig) {
      const keys = Object.keys(rawConfig);
      if (keys.length !== 1) {
        throw new Error("Provided load balancing config has multiple conflicting entries");
      }
      const typeName = keys[0];
      if (typeName in registeredLoadBalancerTypes) {
        try {
          return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]);
        } catch (e) {
          throw new Error(`${typeName}: ${e.message}`);
        }
      } else {
        throw new Error(`Unrecognized load balancing config name ${typeName}`);
      }
    }
    __name(parseLoadBalancingConfig, "parseLoadBalancingConfig");
    function getDefaultConfig() {
      if (!defaultLoadBalancerType) {
        throw new Error("No default load balancer type registered");
      }
      return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig();
    }
    __name(getDefaultConfig, "getDefaultConfig");
    function selectLbConfigFromList(configs, fallbackTodefault = false) {
      for (const config of configs) {
        try {
          return parseLoadBalancingConfig(config);
        } catch (e) {
          (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, "Config parsing failed with error", e.message);
          continue;
        }
      }
      if (fallbackTodefault) {
        if (defaultLoadBalancerType) {
          return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig();
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
    __name(selectLbConfigFromList, "selectLbConfigFromList");
  }
});

// node_modules/@grpc/grpc-js/build/src/service-config.js
var require_service_config = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/service-config.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateRetryThrottling = validateRetryThrottling;
    exports.validateServiceConfig = validateServiceConfig;
    exports.extractAndSelectServiceConfig = extractAndSelectServiceConfig;
    var os4 = __require("os");
    var constants_1 = require_constants2();
    var DURATION_REGEX = /^\d+(\.\d{1,9})?s$/;
    var CLIENT_LANGUAGE_STRING = "node";
    function validateName(obj) {
      if ("service" in obj && obj.service !== "") {
        if (typeof obj.service !== "string") {
          throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`);
        }
        if ("method" in obj && obj.method !== "") {
          if (typeof obj.method !== "string") {
            throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`);
          }
          return {
            service: obj.service,
            method: obj.method
          };
        } else {
          return {
            service: obj.service
          };
        }
      } else {
        if ("method" in obj && obj.method !== void 0) {
          throw new Error(`Invalid method config name: method set with empty or unset service`);
        }
        return {};
      }
    }
    __name(validateName, "validateName");
    function validateRetryPolicy(obj) {
      if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) {
        throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");
      }
      if (!("initialBackoff" in obj) || typeof obj.initialBackoff !== "string" || !DURATION_REGEX.test(obj.initialBackoff)) {
        throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");
      }
      if (!("maxBackoff" in obj) || typeof obj.maxBackoff !== "string" || !DURATION_REGEX.test(obj.maxBackoff)) {
        throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");
      }
      if (!("backoffMultiplier" in obj) || typeof obj.backoffMultiplier !== "number" || obj.backoffMultiplier <= 0) {
        throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");
      }
      if (!("retryableStatusCodes" in obj && Array.isArray(obj.retryableStatusCodes))) {
        throw new Error("Invalid method config retry policy: retryableStatusCodes is required");
      }
      if (obj.retryableStatusCodes.length === 0) {
        throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");
      }
      for (const value of obj.retryableStatusCodes) {
        if (typeof value === "number") {
          if (!Object.values(constants_1.Status).includes(value)) {
            throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range");
          }
        } else if (typeof value === "string") {
          if (!Object.values(constants_1.Status).includes(value.toUpperCase())) {
            throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name");
          }
        } else {
          throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");
        }
      }
      return {
        maxAttempts: obj.maxAttempts,
        initialBackoff: obj.initialBackoff,
        maxBackoff: obj.maxBackoff,
        backoffMultiplier: obj.backoffMultiplier,
        retryableStatusCodes: obj.retryableStatusCodes
      };
    }
    __name(validateRetryPolicy, "validateRetryPolicy");
    function validateHedgingPolicy(obj) {
      if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) {
        throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");
      }
      if ("hedgingDelay" in obj && (typeof obj.hedgingDelay !== "string" || !DURATION_REGEX.test(obj.hedgingDelay))) {
        throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");
      }
      if ("nonFatalStatusCodes" in obj && Array.isArray(obj.nonFatalStatusCodes)) {
        for (const value of obj.nonFatalStatusCodes) {
          if (typeof value === "number") {
            if (!Object.values(constants_1.Status).includes(value)) {
              throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range");
            }
          } else if (typeof value === "string") {
            if (!Object.values(constants_1.Status).includes(value.toUpperCase())) {
              throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name");
            }
          } else {
            throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");
          }
        }
      }
      const result = {
        maxAttempts: obj.maxAttempts
      };
      if (obj.hedgingDelay) {
        result.hedgingDelay = obj.hedgingDelay;
      }
      if (obj.nonFatalStatusCodes) {
        result.nonFatalStatusCodes = obj.nonFatalStatusCodes;
      }
      return result;
    }
    __name(validateHedgingPolicy, "validateHedgingPolicy");
    function validateMethodConfig(obj) {
      var _a;
      const result = {
        name: []
      };
      if (!("name" in obj) || !Array.isArray(obj.name)) {
        throw new Error("Invalid method config: invalid name array");
      }
      for (const name of obj.name) {
        result.name.push(validateName(name));
      }
      if ("waitForReady" in obj) {
        if (typeof obj.waitForReady !== "boolean") {
          throw new Error("Invalid method config: invalid waitForReady");
        }
        result.waitForReady = obj.waitForReady;
      }
      if ("timeout" in obj) {
        if (typeof obj.timeout === "object") {
          if (!("seconds" in obj.timeout) || !(typeof obj.timeout.seconds === "number")) {
            throw new Error("Invalid method config: invalid timeout.seconds");
          }
          if (!("nanos" in obj.timeout) || !(typeof obj.timeout.nanos === "number")) {
            throw new Error("Invalid method config: invalid timeout.nanos");
          }
          result.timeout = obj.timeout;
        } else if (typeof obj.timeout === "string" && DURATION_REGEX.test(obj.timeout)) {
          const timeoutParts = obj.timeout.substring(0, obj.timeout.length - 1).split(".");
          result.timeout = {
            seconds: timeoutParts[0] | 0,
            nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0
          };
        } else {
          throw new Error("Invalid method config: invalid timeout");
        }
      }
      if ("maxRequestBytes" in obj) {
        if (typeof obj.maxRequestBytes !== "number") {
          throw new Error("Invalid method config: invalid maxRequestBytes");
        }
        result.maxRequestBytes = obj.maxRequestBytes;
      }
      if ("maxResponseBytes" in obj) {
        if (typeof obj.maxResponseBytes !== "number") {
          throw new Error("Invalid method config: invalid maxRequestBytes");
        }
        result.maxResponseBytes = obj.maxResponseBytes;
      }
      if ("retryPolicy" in obj) {
        if ("hedgingPolicy" in obj) {
          throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");
        } else {
          result.retryPolicy = validateRetryPolicy(obj.retryPolicy);
        }
      } else if ("hedgingPolicy" in obj) {
        result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy);
      }
      return result;
    }
    __name(validateMethodConfig, "validateMethodConfig");
    function validateRetryThrottling(obj) {
      if (!("maxTokens" in obj) || typeof obj.maxTokens !== "number" || obj.maxTokens <= 0 || obj.maxTokens > 1e3) {
        throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");
      }
      if (!("tokenRatio" in obj) || typeof obj.tokenRatio !== "number" || obj.tokenRatio <= 0) {
        throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");
      }
      return {
        maxTokens: +obj.maxTokens.toFixed(3),
        tokenRatio: +obj.tokenRatio.toFixed(3)
      };
    }
    __name(validateRetryThrottling, "validateRetryThrottling");
    function validateLoadBalancingConfig(obj) {
      if (!(typeof obj === "object" && obj !== null)) {
        throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`);
      }
      const keys = Object.keys(obj);
      if (keys.length > 1) {
        throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`);
      }
      if (keys.length === 0) {
        throw new Error("Invalid loadBalancingConfig: load balancing policy name required");
      }
      return {
        [keys[0]]: obj[keys[0]]
      };
    }
    __name(validateLoadBalancingConfig, "validateLoadBalancingConfig");
    function validateServiceConfig(obj) {
      const result = {
        loadBalancingConfig: [],
        methodConfig: []
      };
      if ("loadBalancingPolicy" in obj) {
        if (typeof obj.loadBalancingPolicy === "string") {
          result.loadBalancingPolicy = obj.loadBalancingPolicy;
        } else {
          throw new Error("Invalid service config: invalid loadBalancingPolicy");
        }
      }
      if ("loadBalancingConfig" in obj) {
        if (Array.isArray(obj.loadBalancingConfig)) {
          for (const config of obj.loadBalancingConfig) {
            result.loadBalancingConfig.push(validateLoadBalancingConfig(config));
          }
        } else {
          throw new Error("Invalid service config: invalid loadBalancingConfig");
        }
      }
      if ("methodConfig" in obj) {
        if (Array.isArray(obj.methodConfig)) {
          for (const methodConfig of obj.methodConfig) {
            result.methodConfig.push(validateMethodConfig(methodConfig));
          }
        }
      }
      if ("retryThrottling" in obj) {
        result.retryThrottling = validateRetryThrottling(obj.retryThrottling);
      }
      const seenMethodNames = [];
      for (const methodConfig of result.methodConfig) {
        for (const name of methodConfig.name) {
          for (const seenName of seenMethodNames) {
            if (name.service === seenName.service && name.method === seenName.method) {
              throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`);
            }
          }
          seenMethodNames.push(name);
        }
      }
      return result;
    }
    __name(validateServiceConfig, "validateServiceConfig");
    function validateCanaryConfig(obj) {
      if (!("serviceConfig" in obj)) {
        throw new Error("Invalid service config choice: missing service config");
      }
      const result = {
        serviceConfig: validateServiceConfig(obj.serviceConfig)
      };
      if ("clientLanguage" in obj) {
        if (Array.isArray(obj.clientLanguage)) {
          result.clientLanguage = [];
          for (const lang of obj.clientLanguage) {
            if (typeof lang === "string") {
              result.clientLanguage.push(lang);
            } else {
              throw new Error("Invalid service config choice: invalid clientLanguage");
            }
          }
        } else {
          throw new Error("Invalid service config choice: invalid clientLanguage");
        }
      }
      if ("clientHostname" in obj) {
        if (Array.isArray(obj.clientHostname)) {
          result.clientHostname = [];
          for (const lang of obj.clientHostname) {
            if (typeof lang === "string") {
              result.clientHostname.push(lang);
            } else {
              throw new Error("Invalid service config choice: invalid clientHostname");
            }
          }
        } else {
          throw new Error("Invalid service config choice: invalid clientHostname");
        }
      }
      if ("percentage" in obj) {
        if (typeof obj.percentage === "number" && 0 <= obj.percentage && obj.percentage <= 100) {
          result.percentage = obj.percentage;
        } else {
          throw new Error("Invalid service config choice: invalid percentage");
        }
      }
      const allowedFields = [
        "clientLanguage",
        "percentage",
        "clientHostname",
        "serviceConfig"
      ];
      for (const field in obj) {
        if (!allowedFields.includes(field)) {
          throw new Error(`Invalid service config choice: unexpected field ${field}`);
        }
      }
      return result;
    }
    __name(validateCanaryConfig, "validateCanaryConfig");
    function validateAndSelectCanaryConfig(obj, percentage) {
      if (!Array.isArray(obj)) {
        throw new Error("Invalid service config list");
      }
      for (const config of obj) {
        const validatedConfig = validateCanaryConfig(config);
        if (typeof validatedConfig.percentage === "number" && percentage > validatedConfig.percentage) {
          continue;
        }
        if (Array.isArray(validatedConfig.clientHostname)) {
          let hostnameMatched = false;
          for (const hostname2 of validatedConfig.clientHostname) {
            if (hostname2 === os4.hostname()) {
              hostnameMatched = true;
            }
          }
          if (!hostnameMatched) {
            continue;
          }
        }
        if (Array.isArray(validatedConfig.clientLanguage)) {
          let languageMatched = false;
          for (const language of validatedConfig.clientLanguage) {
            if (language === CLIENT_LANGUAGE_STRING) {
              languageMatched = true;
            }
          }
          if (!languageMatched) {
            continue;
          }
        }
        return validatedConfig.serviceConfig;
      }
      throw new Error("No matching service config found");
    }
    __name(validateAndSelectCanaryConfig, "validateAndSelectCanaryConfig");
    function extractAndSelectServiceConfig(txtRecord, percentage) {
      for (const record of txtRecord) {
        if (record.length > 0 && record[0].startsWith("grpc_config=")) {
          const recordString = record.join("").substring("grpc_config=".length);
          const recordJson = JSON.parse(recordString);
          return validateAndSelectCanaryConfig(recordJson, percentage);
        }
      }
      return null;
    }
    __name(extractAndSelectServiceConfig, "extractAndSelectServiceConfig");
  }
});

// node_modules/@grpc/grpc-js/build/src/connectivity-state.js
var require_connectivity_state = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/connectivity-state.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConnectivityState = void 0;
    var ConnectivityState;
    (function(ConnectivityState2) {
      ConnectivityState2[ConnectivityState2["IDLE"] = 0] = "IDLE";
      ConnectivityState2[ConnectivityState2["CONNECTING"] = 1] = "CONNECTING";
      ConnectivityState2[ConnectivityState2["READY"] = 2] = "READY";
      ConnectivityState2[ConnectivityState2["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE";
      ConnectivityState2[ConnectivityState2["SHUTDOWN"] = 4] = "SHUTDOWN";
    })(ConnectivityState || (exports.ConnectivityState = ConnectivityState = {}));
  }
});

// node_modules/@grpc/grpc-js/build/src/picker.js
var require_picker = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/picker.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = void 0;
    var metadata_1 = require_metadata();
    var constants_1 = require_constants2();
    var PickResultType;
    (function(PickResultType2) {
      PickResultType2[PickResultType2["COMPLETE"] = 0] = "COMPLETE";
      PickResultType2[PickResultType2["QUEUE"] = 1] = "QUEUE";
      PickResultType2[PickResultType2["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE";
      PickResultType2[PickResultType2["DROP"] = 3] = "DROP";
    })(PickResultType || (exports.PickResultType = PickResultType = {}));
    var UnavailablePicker = class {
      static {
        __name(this, "UnavailablePicker");
      }
      constructor(status) {
        this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: "No connection established", metadata: new metadata_1.Metadata() }, status);
      }
      pick(pickArgs) {
        return {
          pickResultType: PickResultType.TRANSIENT_FAILURE,
          subchannel: null,
          status: this.status,
          onCallStarted: null,
          onCallEnded: null
        };
      }
    };
    exports.UnavailablePicker = UnavailablePicker;
    var QueuePicker = class {
      static {
        __name(this, "QueuePicker");
      }
      // Constructed with a load balancer. Calls exitIdle on it the first time pick is called
      constructor(loadBalancer, childPicker) {
        this.loadBalancer = loadBalancer;
        this.childPicker = childPicker;
        this.calledExitIdle = false;
      }
      pick(pickArgs) {
        if (!this.calledExitIdle) {
          process.nextTick(() => {
            this.loadBalancer.exitIdle();
          });
          this.calledExitIdle = true;
        }
        if (this.childPicker) {
          return this.childPicker.pick(pickArgs);
        } else {
          return {
            pickResultType: PickResultType.QUEUE,
            subchannel: null,
            status: null,
            onCallStarted: null,
            onCallEnded: null
          };
        }
      }
    };
    exports.QueuePicker = QueuePicker;
  }
});

// node_modules/@grpc/grpc-js/build/src/backoff-timeout.js
var require_backoff_timeout = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/backoff-timeout.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BackoffTimeout = void 0;
    var constants_1 = require_constants2();
    var logging = require_logging();
    var TRACER_NAME = "backoff";
    var INITIAL_BACKOFF_MS = 1e3;
    var BACKOFF_MULTIPLIER2 = 1.6;
    var MAX_BACKOFF_MS = 12e4;
    var BACKOFF_JITTER = 0.2;
    function uniformRandom(min, max) {
      return Math.random() * (max - min) + min;
    }
    __name(uniformRandom, "uniformRandom");
    var BackoffTimeout = class _BackoffTimeout {
      static {
        __name(this, "BackoffTimeout");
      }
      constructor(callback, options) {
        this.callback = callback;
        this.initialDelay = INITIAL_BACKOFF_MS;
        this.multiplier = BACKOFF_MULTIPLIER2;
        this.maxDelay = MAX_BACKOFF_MS;
        this.jitter = BACKOFF_JITTER;
        this.running = false;
        this.hasRef = true;
        this.startTime = /* @__PURE__ */ new Date();
        this.endTime = /* @__PURE__ */ new Date();
        this.id = _BackoffTimeout.getNextId();
        if (options) {
          if (options.initialDelay) {
            this.initialDelay = options.initialDelay;
          }
          if (options.multiplier) {
            this.multiplier = options.multiplier;
          }
          if (options.jitter) {
            this.jitter = options.jitter;
          }
          if (options.maxDelay) {
            this.maxDelay = options.maxDelay;
          }
        }
        this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay);
        this.nextDelay = this.initialDelay;
        this.timerId = setTimeout(() => {
        }, 0);
        clearTimeout(this.timerId);
      }
      static getNextId() {
        return this.nextId++;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text);
      }
      runTimer(delay) {
        var _a, _b;
        this.trace("runTimer(delay=" + delay + ")");
        this.endTime = this.startTime;
        this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay);
        clearTimeout(this.timerId);
        this.timerId = setTimeout(() => {
          this.trace("timer fired");
          this.running = false;
          this.callback();
        }, delay);
        if (!this.hasRef) {
          (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
        }
      }
      /**
       * Call the callback after the current amount of delay time
       */
      runOnce() {
        this.trace("runOnce()");
        this.running = true;
        this.startTime = /* @__PURE__ */ new Date();
        this.runTimer(this.nextDelay);
        const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay);
        const jitterMagnitude = nextBackoff * this.jitter;
        this.nextDelay = nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude);
      }
      /**
       * Stop the timer. The callback will not be called until `runOnce` is called
       * again.
       */
      stop() {
        this.trace("stop()");
        clearTimeout(this.timerId);
        this.running = false;
      }
      /**
       * Reset the delay time to its initial value. If the timer is still running,
       * retroactively apply that reset to the current timer.
       */
      reset() {
        this.trace("reset() running=" + this.running);
        this.nextDelay = this.initialDelay;
        if (this.running) {
          const now = /* @__PURE__ */ new Date();
          const newEndTime = this.startTime;
          newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay);
          clearTimeout(this.timerId);
          if (now < newEndTime) {
            this.runTimer(newEndTime.getTime() - now.getTime());
          } else {
            this.running = false;
          }
        }
      }
      /**
       * Check whether the timer is currently running.
       */
      isRunning() {
        return this.running;
      }
      /**
       * Set that while the timer is running, it should keep the Node process
       * running.
       */
      ref() {
        var _a, _b;
        this.hasRef = true;
        (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a);
      }
      /**
       * Set that while the timer is running, it should not keep the Node process
       * running.
       */
      unref() {
        var _a, _b;
        this.hasRef = false;
        (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
      }
      /**
       * Get the approximate timestamp of when the timer will fire. Only valid if
       * this.isRunning() is true.
       */
      getEndTime() {
        return this.endTime;
      }
    };
    exports.BackoffTimeout = BackoffTimeout;
    BackoffTimeout.nextId = 0;
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js
var require_load_balancer_child_handler = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChildLoadBalancerHandler = void 0;
    var load_balancer_1 = require_load_balancer();
    var connectivity_state_1 = require_connectivity_state();
    var TYPE_NAME = "child_load_balancer_helper";
    var ChildLoadBalancerHandler = class {
      static {
        __name(this, "ChildLoadBalancerHandler");
      }
      constructor(channelControlHelper) {
        this.channelControlHelper = channelControlHelper;
        this.currentChild = null;
        this.pendingChild = null;
        this.latestConfig = null;
        this.ChildPolicyHelper = class {
          constructor(parent) {
            this.parent = parent;
            this.child = null;
          }
          createSubchannel(subchannelAddress, subchannelArgs) {
            return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
          }
          updateState(connectivityState, picker, errorMessage2) {
            var _a;
            if (this.calledByPendingChild()) {
              if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) {
                return;
              }
              (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy();
              this.parent.currentChild = this.parent.pendingChild;
              this.parent.pendingChild = null;
            } else if (!this.calledByCurrentChild()) {
              return;
            }
            this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage2);
          }
          requestReresolution() {
            var _a;
            const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild;
            if (this.child === latestChild) {
              this.parent.channelControlHelper.requestReresolution();
            }
          }
          setChild(newChild) {
            this.child = newChild;
          }
          addChannelzChild(child) {
            this.parent.channelControlHelper.addChannelzChild(child);
          }
          removeChannelzChild(child) {
            this.parent.channelControlHelper.removeChannelzChild(child);
          }
          calledByPendingChild() {
            return this.child === this.parent.pendingChild;
          }
          calledByCurrentChild() {
            return this.child === this.parent.currentChild;
          }
        };
      }
      configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) {
        return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName();
      }
      /**
       * Prerequisites: lbConfig !== null and lbConfig.name is registered
       * @param endpointList
       * @param lbConfig
       * @param attributes
       */
      updateAddressList(endpointList, lbConfig, options, resolutionNote) {
        let childToUpdate;
        if (this.currentChild === null || this.latestConfig === null || this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) {
          const newHelper = new this.ChildPolicyHelper(this);
          const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper);
          newHelper.setChild(newChild);
          if (this.currentChild === null) {
            this.currentChild = newChild;
            childToUpdate = this.currentChild;
          } else {
            if (this.pendingChild) {
              this.pendingChild.destroy();
            }
            this.pendingChild = newChild;
            childToUpdate = this.pendingChild;
          }
        } else {
          if (this.pendingChild === null) {
            childToUpdate = this.currentChild;
          } else {
            childToUpdate = this.pendingChild;
          }
        }
        this.latestConfig = lbConfig;
        return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote);
      }
      exitIdle() {
        if (this.currentChild) {
          this.currentChild.exitIdle();
          if (this.pendingChild) {
            this.pendingChild.exitIdle();
          }
        }
      }
      resetBackoff() {
        if (this.currentChild) {
          this.currentChild.resetBackoff();
          if (this.pendingChild) {
            this.pendingChild.resetBackoff();
          }
        }
      }
      destroy() {
        if (this.currentChild) {
          this.currentChild.destroy();
          this.currentChild = null;
        }
        if (this.pendingChild) {
          this.pendingChild.destroy();
          this.pendingChild = null;
        }
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports.ChildLoadBalancerHandler = ChildLoadBalancerHandler;
  }
});

// node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js
var require_resolving_load_balancer = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResolvingLoadBalancer = void 0;
    var load_balancer_1 = require_load_balancer();
    var service_config_1 = require_service_config();
    var connectivity_state_1 = require_connectivity_state();
    var resolver_1 = require_resolver();
    var picker_1 = require_picker();
    var backoff_timeout_1 = require_backoff_timeout();
    var constants_1 = require_constants2();
    var metadata_1 = require_metadata();
    var logging = require_logging();
    var constants_2 = require_constants2();
    var uri_parser_1 = require_uri_parser();
    var load_balancer_child_handler_1 = require_load_balancer_child_handler();
    var TRACER_NAME = "resolving_load_balancer";
    function trace2(text) {
      logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var NAME_MATCH_LEVEL_ORDER = [
      "SERVICE_AND_METHOD",
      "SERVICE",
      "EMPTY"
    ];
    function hasMatchingName(service, method, methodConfig, matchLevel) {
      for (const name of methodConfig.name) {
        switch (matchLevel) {
          case "EMPTY":
            if (!name.service && !name.method) {
              return true;
            }
            break;
          case "SERVICE":
            if (name.service === service && !name.method) {
              return true;
            }
            break;
          case "SERVICE_AND_METHOD":
            if (name.service === service && name.method === method) {
              return true;
            }
        }
      }
      return false;
    }
    __name(hasMatchingName, "hasMatchingName");
    function findMatchingConfig(service, method, methodConfigs, matchLevel) {
      for (const config of methodConfigs) {
        if (hasMatchingName(service, method, config, matchLevel)) {
          return config;
        }
      }
      return null;
    }
    __name(findMatchingConfig, "findMatchingConfig");
    function getDefaultConfigSelector(serviceConfig) {
      return {
        invoke(methodName, metadata) {
          var _a, _b;
          const splitName = methodName.split("/").filter((x) => x.length > 0);
          const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : "";
          const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : "";
          if (serviceConfig && serviceConfig.methodConfig) {
            for (const matchLevel of NAME_MATCH_LEVEL_ORDER) {
              const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel);
              if (matchingConfig) {
                return {
                  methodConfig: matchingConfig,
                  pickInformation: {},
                  status: constants_1.Status.OK,
                  dynamicFilterFactories: []
                };
              }
            }
          }
          return {
            methodConfig: { name: [] },
            pickInformation: {},
            status: constants_1.Status.OK,
            dynamicFilterFactories: []
          };
        },
        unref() {
        }
      };
    }
    __name(getDefaultConfigSelector, "getDefaultConfigSelector");
    var ResolvingLoadBalancer = class {
      static {
        __name(this, "ResolvingLoadBalancer");
      }
      /**
       * Wrapper class that behaves like a `LoadBalancer` and also handles name
       * resolution internally.
       * @param target The address of the backend to connect to.
       * @param channelControlHelper `ChannelControlHelper` instance provided by
       *     this load balancer's owner.
       * @param defaultServiceConfig The default service configuration to be used
       *     if none is provided by the name resolver. A `null` value indicates
       *     that the default behavior should be the default unconfigured behavior.
       *     In practice, that means using the "pick first" load balancer
       *     implmentation
       */
      constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) {
        this.target = target;
        this.channelControlHelper = channelControlHelper;
        this.channelOptions = channelOptions;
        this.onSuccessfulResolution = onSuccessfulResolution;
        this.onFailedResolution = onFailedResolution;
        this.latestChildState = connectivity_state_1.ConnectivityState.IDLE;
        this.latestChildPicker = new picker_1.QueuePicker(this);
        this.latestChildErrorMessage = null;
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.previousServiceConfig = null;
        this.continueResolving = false;
        if (channelOptions["grpc.service_config"]) {
          this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions["grpc.service_config"]));
        } else {
          this.defaultServiceConfig = {
            loadBalancingConfig: [],
            methodConfig: []
          };
        }
        this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
        this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({
          createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper),
          requestReresolution: /* @__PURE__ */ __name(() => {
            if (this.backoffTimeout.isRunning()) {
              trace2("requestReresolution delayed by backoff timer until " + this.backoffTimeout.getEndTime().toISOString());
              this.continueResolving = true;
            } else {
              this.updateResolution();
            }
          }, "requestReresolution"),
          updateState: /* @__PURE__ */ __name((newState, picker, errorMessage2) => {
            this.latestChildState = newState;
            this.latestChildPicker = picker;
            this.latestChildErrorMessage = errorMessage2;
            this.updateState(newState, picker, errorMessage2);
          }, "updateState"),
          addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper),
          removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper)
        });
        this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions);
        const backoffOptions = {
          initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"],
          maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"]
        };
        this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {
          if (this.continueResolving) {
            this.updateResolution();
            this.continueResolving = false;
          } else {
            this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage);
          }
        }, backoffOptions);
        this.backoffTimeout.unref();
      }
      handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) {
        var _a, _b;
        this.backoffTimeout.stop();
        this.backoffTimeout.reset();
        let resultAccepted = true;
        let workingServiceConfig = null;
        if (serviceConfig === null) {
          workingServiceConfig = this.defaultServiceConfig;
        } else if (serviceConfig.ok) {
          workingServiceConfig = serviceConfig.value;
        } else {
          if (this.previousServiceConfig !== null) {
            workingServiceConfig = this.previousServiceConfig;
          } else {
            resultAccepted = false;
            this.handleResolutionFailure(serviceConfig.error);
          }
        }
        if (workingServiceConfig !== null) {
          const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : [];
          const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true);
          if (loadBalancingConfig === null) {
            resultAccepted = false;
            this.handleResolutionFailure({
              code: constants_1.Status.UNAVAILABLE,
              details: "All load balancer options in service config are not compatible",
              metadata: new metadata_1.Metadata()
            });
          } else {
            resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote);
          }
        }
        if (resultAccepted) {
          this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== void 0 ? _b : getDefaultConfigSelector(workingServiceConfig));
        }
        return resultAccepted;
      }
      updateResolution() {
        this.innerResolver.updateResolution();
        if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) {
          this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage);
        }
        this.backoffTimeout.runOnce();
      }
      updateState(connectivityState, picker, errorMessage2) {
        trace2((0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[connectivityState]);
        if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) {
          picker = new picker_1.QueuePicker(this, picker);
        }
        this.currentState = connectivityState;
        this.channelControlHelper.updateState(connectivityState, picker, errorMessage2);
      }
      handleResolutionFailure(error) {
        if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) {
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error), error.details);
          this.onFailedResolution(error);
        }
      }
      exitIdle() {
        if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
          if (this.backoffTimeout.isRunning()) {
            this.continueResolving = true;
          } else {
            this.updateResolution();
          }
        }
        this.childLoadBalancer.exitIdle();
      }
      updateAddressList(endpointList, lbConfig) {
        throw new Error("updateAddressList not supported on ResolvingLoadBalancer");
      }
      resetBackoff() {
        this.backoffTimeout.reset();
        this.childLoadBalancer.resetBackoff();
      }
      destroy() {
        this.childLoadBalancer.destroy();
        this.innerResolver.destroy();
        this.backoffTimeout.reset();
        this.backoffTimeout.stop();
        this.latestChildState = connectivity_state_1.ConnectivityState.IDLE;
        this.latestChildPicker = new picker_1.QueuePicker(this);
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.previousServiceConfig = null;
        this.continueResolving = false;
      }
      getTypeName() {
        return "resolving_load_balancer";
      }
    };
    exports.ResolvingLoadBalancer = ResolvingLoadBalancer;
  }
});

// node_modules/@grpc/grpc-js/build/src/channel-options.js
var require_channel_options = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channel-options.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.recognizedOptions = void 0;
    exports.channelOptionsEqual = channelOptionsEqual;
    exports.recognizedOptions = {
      "grpc.ssl_target_name_override": true,
      "grpc.primary_user_agent": true,
      "grpc.secondary_user_agent": true,
      "grpc.default_authority": true,
      "grpc.keepalive_time_ms": true,
      "grpc.keepalive_timeout_ms": true,
      "grpc.keepalive_permit_without_calls": true,
      "grpc.service_config": true,
      "grpc.max_concurrent_streams": true,
      "grpc.initial_reconnect_backoff_ms": true,
      "grpc.max_reconnect_backoff_ms": true,
      "grpc.use_local_subchannel_pool": true,
      "grpc.max_send_message_length": true,
      "grpc.max_receive_message_length": true,
      "grpc.enable_http_proxy": true,
      "grpc.enable_channelz": true,
      "grpc.dns_min_time_between_resolutions_ms": true,
      "grpc.enable_retries": true,
      "grpc.per_rpc_retry_buffer_size": true,
      "grpc.retry_buffer_size": true,
      "grpc.max_connection_age_ms": true,
      "grpc.max_connection_age_grace_ms": true,
      "grpc-node.max_session_memory": true,
      "grpc.service_config_disable_resolution": true,
      "grpc.client_idle_timeout_ms": true,
      "grpc-node.tls_enable_trace": true,
      "grpc.lb.ring_hash.ring_size_cap": true,
      "grpc-node.retry_max_attempts_limit": true,
      "grpc-node.flow_control_window": true,
      "grpc.server_call_metric_recording": true
    };
    function channelOptionsEqual(options1, options2) {
      const keys1 = Object.keys(options1).sort();
      const keys2 = Object.keys(options2).sort();
      if (keys1.length !== keys2.length) {
        return false;
      }
      for (let i = 0; i < keys1.length; i += 1) {
        if (keys1[i] !== keys2[i]) {
          return false;
        }
        if (options1[keys1[i]] !== options2[keys2[i]]) {
          return false;
        }
      }
      return true;
    }
    __name(channelOptionsEqual, "channelOptionsEqual");
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-address.js
var require_subchannel_address = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-address.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EndpointMap = void 0;
    exports.isTcpSubchannelAddress = isTcpSubchannelAddress;
    exports.subchannelAddressEqual = subchannelAddressEqual;
    exports.subchannelAddressToString = subchannelAddressToString;
    exports.stringToSubchannelAddress = stringToSubchannelAddress;
    exports.endpointEqual = endpointEqual;
    exports.endpointToString = endpointToString;
    exports.endpointHasAddress = endpointHasAddress;
    var net_1 = __require("net");
    function isTcpSubchannelAddress(address) {
      return "port" in address;
    }
    __name(isTcpSubchannelAddress, "isTcpSubchannelAddress");
    function subchannelAddressEqual(address1, address2) {
      if (!address1 && !address2) {
        return true;
      }
      if (!address1 || !address2) {
        return false;
      }
      if (isTcpSubchannelAddress(address1)) {
        return isTcpSubchannelAddress(address2) && address1.host === address2.host && address1.port === address2.port;
      } else {
        return !isTcpSubchannelAddress(address2) && address1.path === address2.path;
      }
    }
    __name(subchannelAddressEqual, "subchannelAddressEqual");
    function subchannelAddressToString(address) {
      if (isTcpSubchannelAddress(address)) {
        if ((0, net_1.isIPv6)(address.host)) {
          return "[" + address.host + "]:" + address.port;
        } else {
          return address.host + ":" + address.port;
        }
      } else {
        return address.path;
      }
    }
    __name(subchannelAddressToString, "subchannelAddressToString");
    var DEFAULT_PORT = 443;
    function stringToSubchannelAddress(addressString, port) {
      if ((0, net_1.isIP)(addressString)) {
        return {
          host: addressString,
          port: port !== null && port !== void 0 ? port : DEFAULT_PORT
        };
      } else {
        return {
          path: addressString
        };
      }
    }
    __name(stringToSubchannelAddress, "stringToSubchannelAddress");
    function endpointEqual(endpoint1, endpoint2) {
      if (endpoint1.addresses.length !== endpoint2.addresses.length) {
        return false;
      }
      for (let i = 0; i < endpoint1.addresses.length; i++) {
        if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) {
          return false;
        }
      }
      return true;
    }
    __name(endpointEqual, "endpointEqual");
    function endpointToString(endpoint) {
      return "[" + endpoint.addresses.map(subchannelAddressToString).join(", ") + "]";
    }
    __name(endpointToString, "endpointToString");
    function endpointHasAddress(endpoint, expectedAddress) {
      for (const address of endpoint.addresses) {
        if (subchannelAddressEqual(address, expectedAddress)) {
          return true;
        }
      }
      return false;
    }
    __name(endpointHasAddress, "endpointHasAddress");
    function endpointEqualUnordered(endpoint1, endpoint2) {
      if (endpoint1.addresses.length !== endpoint2.addresses.length) {
        return false;
      }
      for (const address1 of endpoint1.addresses) {
        let matchFound = false;
        for (const address2 of endpoint2.addresses) {
          if (subchannelAddressEqual(address1, address2)) {
            matchFound = true;
            break;
          }
        }
        if (!matchFound) {
          return false;
        }
      }
      return true;
    }
    __name(endpointEqualUnordered, "endpointEqualUnordered");
    var EndpointMap = class {
      static {
        __name(this, "EndpointMap");
      }
      constructor() {
        this.map = /* @__PURE__ */ new Set();
      }
      get size() {
        return this.map.size;
      }
      getForSubchannelAddress(address) {
        for (const entry of this.map) {
          if (endpointHasAddress(entry.key, address)) {
            return entry.value;
          }
        }
        return void 0;
      }
      /**
       * Delete any entries in this map with keys that are not in endpoints
       * @param endpoints
       */
      deleteMissing(endpoints) {
        const removedValues = [];
        for (const entry of this.map) {
          let foundEntry = false;
          for (const endpoint of endpoints) {
            if (endpointEqualUnordered(endpoint, entry.key)) {
              foundEntry = true;
            }
          }
          if (!foundEntry) {
            removedValues.push(entry.value);
            this.map.delete(entry);
          }
        }
        return removedValues;
      }
      get(endpoint) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            return entry.value;
          }
        }
        return void 0;
      }
      set(endpoint, mapEntry) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            entry.value = mapEntry;
            return;
          }
        }
        this.map.add({ key: endpoint, value: mapEntry });
      }
      delete(endpoint) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            this.map.delete(entry);
            return;
          }
        }
      }
      has(endpoint) {
        for (const entry of this.map) {
          if (endpointEqualUnordered(endpoint, entry.key)) {
            return true;
          }
        }
        return false;
      }
      clear() {
        this.map.clear();
      }
      *keys() {
        for (const entry of this.map) {
          yield entry.key;
        }
      }
      *values() {
        for (const entry of this.map) {
          yield entry.value;
        }
      }
      *entries() {
        for (const entry of this.map) {
          yield [entry.key, entry.value];
        }
      }
    };
    exports.EndpointMap = EndpointMap;
  }
});

// node_modules/@js-sdsl/ordered-map/dist/cjs/index.js
var require_cjs = __commonJS({
  "node_modules/@js-sdsl/ordered-map/dist/cjs/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "t", {
      value: true
    });
    var TreeNode = class {
      static {
        __name(this, "TreeNode");
      }
      constructor(t, e, s = 1) {
        this.i = void 0;
        this.h = void 0;
        this.o = void 0;
        this.u = t;
        this.l = e;
        this.p = s;
      }
      I() {
        let t = this;
        const e = t.o.o === t;
        if (e && t.p === 1) {
          t = t.h;
        } else if (t.i) {
          t = t.i;
          while (t.h) {
            t = t.h;
          }
        } else {
          if (e) {
            return t.o;
          }
          let s = t.o;
          while (s.i === t) {
            t = s;
            s = t.o;
          }
          t = s;
        }
        return t;
      }
      B() {
        let t = this;
        if (t.h) {
          t = t.h;
          while (t.i) {
            t = t.i;
          }
          return t;
        } else {
          let e = t.o;
          while (e.h === t) {
            t = e;
            e = t.o;
          }
          if (t.h !== e) {
            return e;
          } else return t;
        }
      }
      _() {
        const t = this.o;
        const e = this.h;
        const s = e.i;
        if (t.o === this) t.o = e;
        else if (t.i === this) t.i = e;
        else t.h = e;
        e.o = t;
        e.i = this;
        this.o = e;
        this.h = s;
        if (s) s.o = this;
        return e;
      }
      g() {
        const t = this.o;
        const e = this.i;
        const s = e.h;
        if (t.o === this) t.o = e;
        else if (t.i === this) t.i = e;
        else t.h = e;
        e.o = t;
        e.h = this;
        this.o = e;
        this.i = s;
        if (s) s.o = this;
        return e;
      }
    };
    var TreeNodeEnableIndex = class extends TreeNode {
      static {
        __name(this, "TreeNodeEnableIndex");
      }
      constructor() {
        super(...arguments);
        this.M = 1;
      }
      _() {
        const t = super._();
        this.O();
        t.O();
        return t;
      }
      g() {
        const t = super.g();
        this.O();
        t.O();
        return t;
      }
      O() {
        this.M = 1;
        if (this.i) {
          this.M += this.i.M;
        }
        if (this.h) {
          this.M += this.h.M;
        }
      }
    };
    var ContainerIterator = class {
      static {
        __name(this, "ContainerIterator");
      }
      constructor(t = 0) {
        this.iteratorType = t;
      }
      equals(t) {
        return this.T === t.T;
      }
    };
    var Base = class {
      static {
        __name(this, "Base");
      }
      constructor() {
        this.m = 0;
      }
      get length() {
        return this.m;
      }
      size() {
        return this.m;
      }
      empty() {
        return this.m === 0;
      }
    };
    var Container = class extends Base {
      static {
        __name(this, "Container");
      }
    };
    function throwIteratorAccessError() {
      throw new RangeError("Iterator access denied!");
    }
    __name(throwIteratorAccessError, "throwIteratorAccessError");
    var TreeContainer = class extends Container {
      static {
        __name(this, "TreeContainer");
      }
      constructor(t = function(t2, e2) {
        if (t2 < e2) return -1;
        if (t2 > e2) return 1;
        return 0;
      }, e = false) {
        super();
        this.v = void 0;
        this.A = t;
        this.enableIndex = e;
        this.N = e ? TreeNodeEnableIndex : TreeNode;
        this.C = new this.N();
      }
      R(t, e) {
        let s = this.C;
        while (t) {
          const i = this.A(t.u, e);
          if (i < 0) {
            t = t.h;
          } else if (i > 0) {
            s = t;
            t = t.i;
          } else return t;
        }
        return s;
      }
      K(t, e) {
        let s = this.C;
        while (t) {
          const i = this.A(t.u, e);
          if (i <= 0) {
            t = t.h;
          } else {
            s = t;
            t = t.i;
          }
        }
        return s;
      }
      L(t, e) {
        let s = this.C;
        while (t) {
          const i = this.A(t.u, e);
          if (i < 0) {
            s = t;
            t = t.h;
          } else if (i > 0) {
            t = t.i;
          } else return t;
        }
        return s;
      }
      k(t, e) {
        let s = this.C;
        while (t) {
          const i = this.A(t.u, e);
          if (i < 0) {
            s = t;
            t = t.h;
          } else {
            t = t.i;
          }
        }
        return s;
      }
      P(t) {
        while (true) {
          const e = t.o;
          if (e === this.C) return;
          if (t.p === 1) {
            t.p = 0;
            return;
          }
          if (t === e.i) {
            const s = e.h;
            if (s.p === 1) {
              s.p = 0;
              e.p = 1;
              if (e === this.v) {
                this.v = e._();
              } else e._();
            } else {
              if (s.h && s.h.p === 1) {
                s.p = e.p;
                e.p = 0;
                s.h.p = 0;
                if (e === this.v) {
                  this.v = e._();
                } else e._();
                return;
              } else if (s.i && s.i.p === 1) {
                s.p = 1;
                s.i.p = 0;
                s.g();
              } else {
                s.p = 1;
                t = e;
              }
            }
          } else {
            const s = e.i;
            if (s.p === 1) {
              s.p = 0;
              e.p = 1;
              if (e === this.v) {
                this.v = e.g();
              } else e.g();
            } else {
              if (s.i && s.i.p === 1) {
                s.p = e.p;
                e.p = 0;
                s.i.p = 0;
                if (e === this.v) {
                  this.v = e.g();
                } else e.g();
                return;
              } else if (s.h && s.h.p === 1) {
                s.p = 1;
                s.h.p = 0;
                s._();
              } else {
                s.p = 1;
                t = e;
              }
            }
          }
        }
      }
      S(t) {
        if (this.m === 1) {
          this.clear();
          return;
        }
        let e = t;
        while (e.i || e.h) {
          if (e.h) {
            e = e.h;
            while (e.i) e = e.i;
          } else {
            e = e.i;
          }
          const s2 = t.u;
          t.u = e.u;
          e.u = s2;
          const i = t.l;
          t.l = e.l;
          e.l = i;
          t = e;
        }
        if (this.C.i === e) {
          this.C.i = e.o;
        } else if (this.C.h === e) {
          this.C.h = e.o;
        }
        this.P(e);
        let s = e.o;
        if (e === s.i) {
          s.i = void 0;
        } else s.h = void 0;
        this.m -= 1;
        this.v.p = 0;
        if (this.enableIndex) {
          while (s !== this.C) {
            s.M -= 1;
            s = s.o;
          }
        }
      }
      U(t) {
        const e = typeof t === "number" ? t : void 0;
        const s = typeof t === "function" ? t : void 0;
        const i = typeof t === "undefined" ? [] : void 0;
        let r = 0;
        let n = this.v;
        const h = [];
        while (h.length || n) {
          if (n) {
            h.push(n);
            n = n.i;
          } else {
            n = h.pop();
            if (r === e) return n;
            i && i.push(n);
            s && s(n, r, this);
            r += 1;
            n = n.h;
          }
        }
        return i;
      }
      j(t) {
        while (true) {
          const e = t.o;
          if (e.p === 0) return;
          const s = e.o;
          if (e === s.i) {
            const i = s.h;
            if (i && i.p === 1) {
              i.p = e.p = 0;
              if (s === this.v) return;
              s.p = 1;
              t = s;
              continue;
            } else if (t === e.h) {
              t.p = 0;
              if (t.i) {
                t.i.o = e;
              }
              if (t.h) {
                t.h.o = s;
              }
              e.h = t.i;
              s.i = t.h;
              t.i = e;
              t.h = s;
              if (s === this.v) {
                this.v = t;
                this.C.o = t;
              } else {
                const e2 = s.o;
                if (e2.i === s) {
                  e2.i = t;
                } else e2.h = t;
              }
              t.o = s.o;
              e.o = t;
              s.o = t;
              s.p = 1;
            } else {
              e.p = 0;
              if (s === this.v) {
                this.v = s.g();
              } else s.g();
              s.p = 1;
              return;
            }
          } else {
            const i = s.i;
            if (i && i.p === 1) {
              i.p = e.p = 0;
              if (s === this.v) return;
              s.p = 1;
              t = s;
              continue;
            } else if (t === e.i) {
              t.p = 0;
              if (t.i) {
                t.i.o = s;
              }
              if (t.h) {
                t.h.o = e;
              }
              s.h = t.i;
              e.i = t.h;
              t.i = s;
              t.h = e;
              if (s === this.v) {
                this.v = t;
                this.C.o = t;
              } else {
                const e2 = s.o;
                if (e2.i === s) {
                  e2.i = t;
                } else e2.h = t;
              }
              t.o = s.o;
              e.o = t;
              s.o = t;
              s.p = 1;
            } else {
              e.p = 0;
              if (s === this.v) {
                this.v = s._();
              } else s._();
              s.p = 1;
              return;
            }
          }
          if (this.enableIndex) {
            e.O();
            s.O();
            t.O();
          }
          return;
        }
      }
      q(t, e, s) {
        if (this.v === void 0) {
          this.m += 1;
          this.v = new this.N(t, e, 0);
          this.v.o = this.C;
          this.C.o = this.C.i = this.C.h = this.v;
          return this.m;
        }
        let i;
        const r = this.C.i;
        const n = this.A(r.u, t);
        if (n === 0) {
          r.l = e;
          return this.m;
        } else if (n > 0) {
          r.i = new this.N(t, e);
          r.i.o = r;
          i = r.i;
          this.C.i = i;
        } else {
          const r2 = this.C.h;
          const n2 = this.A(r2.u, t);
          if (n2 === 0) {
            r2.l = e;
            return this.m;
          } else if (n2 < 0) {
            r2.h = new this.N(t, e);
            r2.h.o = r2;
            i = r2.h;
            this.C.h = i;
          } else {
            if (s !== void 0) {
              const r3 = s.T;
              if (r3 !== this.C) {
                const s2 = this.A(r3.u, t);
                if (s2 === 0) {
                  r3.l = e;
                  return this.m;
                } else if (s2 > 0) {
                  const s3 = r3.I();
                  const n3 = this.A(s3.u, t);
                  if (n3 === 0) {
                    s3.l = e;
                    return this.m;
                  } else if (n3 < 0) {
                    i = new this.N(t, e);
                    if (s3.h === void 0) {
                      s3.h = i;
                      i.o = s3;
                    } else {
                      r3.i = i;
                      i.o = r3;
                    }
                  }
                }
              }
            }
            if (i === void 0) {
              i = this.v;
              while (true) {
                const s2 = this.A(i.u, t);
                if (s2 > 0) {
                  if (i.i === void 0) {
                    i.i = new this.N(t, e);
                    i.i.o = i;
                    i = i.i;
                    break;
                  }
                  i = i.i;
                } else if (s2 < 0) {
                  if (i.h === void 0) {
                    i.h = new this.N(t, e);
                    i.h.o = i;
                    i = i.h;
                    break;
                  }
                  i = i.h;
                } else {
                  i.l = e;
                  return this.m;
                }
              }
            }
          }
        }
        if (this.enableIndex) {
          let t2 = i.o;
          while (t2 !== this.C) {
            t2.M += 1;
            t2 = t2.o;
          }
        }
        this.j(i);
        this.m += 1;
        return this.m;
      }
      H(t, e) {
        while (t) {
          const s = this.A(t.u, e);
          if (s < 0) {
            t = t.h;
          } else if (s > 0) {
            t = t.i;
          } else return t;
        }
        return t || this.C;
      }
      clear() {
        this.m = 0;
        this.v = void 0;
        this.C.o = void 0;
        this.C.i = this.C.h = void 0;
      }
      updateKeyByIterator(t, e) {
        const s = t.T;
        if (s === this.C) {
          throwIteratorAccessError();
        }
        if (this.m === 1) {
          s.u = e;
          return true;
        }
        const i = s.B().u;
        if (s === this.C.i) {
          if (this.A(i, e) > 0) {
            s.u = e;
            return true;
          }
          return false;
        }
        const r = s.I().u;
        if (s === this.C.h) {
          if (this.A(r, e) < 0) {
            s.u = e;
            return true;
          }
          return false;
        }
        if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false;
        s.u = e;
        return true;
      }
      eraseElementByPos(t) {
        if (t < 0 || t > this.m - 1) {
          throw new RangeError();
        }
        const e = this.U(t);
        this.S(e);
        return this.m;
      }
      eraseElementByKey(t) {
        if (this.m === 0) return false;
        const e = this.H(this.v, t);
        if (e === this.C) return false;
        this.S(e);
        return true;
      }
      eraseElementByIterator(t) {
        const e = t.T;
        if (e === this.C) {
          throwIteratorAccessError();
        }
        const s = e.h === void 0;
        const i = t.iteratorType === 0;
        if (i) {
          if (s) t.next();
        } else {
          if (!s || e.i === void 0) t.next();
        }
        this.S(e);
        return t;
      }
      getHeight() {
        if (this.m === 0) return 0;
        function traversal(t) {
          if (!t) return 0;
          return Math.max(traversal(t.i), traversal(t.h)) + 1;
        }
        __name(traversal, "traversal");
        return traversal(this.v);
      }
    };
    var TreeIterator = class extends ContainerIterator {
      static {
        __name(this, "TreeIterator");
      }
      constructor(t, e, s) {
        super(s);
        this.T = t;
        this.C = e;
        if (this.iteratorType === 0) {
          this.pre = function() {
            if (this.T === this.C.i) {
              throwIteratorAccessError();
            }
            this.T = this.T.I();
            return this;
          };
          this.next = function() {
            if (this.T === this.C) {
              throwIteratorAccessError();
            }
            this.T = this.T.B();
            return this;
          };
        } else {
          this.pre = function() {
            if (this.T === this.C.h) {
              throwIteratorAccessError();
            }
            this.T = this.T.B();
            return this;
          };
          this.next = function() {
            if (this.T === this.C) {
              throwIteratorAccessError();
            }
            this.T = this.T.I();
            return this;
          };
        }
      }
      get index() {
        let t = this.T;
        const e = this.C.o;
        if (t === this.C) {
          if (e) {
            return e.M - 1;
          }
          return 0;
        }
        let s = 0;
        if (t.i) {
          s += t.i.M;
        }
        while (t !== e) {
          const e2 = t.o;
          if (t === e2.h) {
            s += 1;
            if (e2.i) {
              s += e2.i.M;
            }
          }
          t = e2;
        }
        return s;
      }
      isAccessible() {
        return this.T !== this.C;
      }
    };
    var OrderedMapIterator = class _OrderedMapIterator extends TreeIterator {
      static {
        __name(this, "OrderedMapIterator");
      }
      constructor(t, e, s, i) {
        super(t, e, i);
        this.container = s;
      }
      get pointer() {
        if (this.T === this.C) {
          throwIteratorAccessError();
        }
        const t = this;
        return new Proxy([], {
          get(e, s) {
            if (s === "0") return t.T.u;
            else if (s === "1") return t.T.l;
            e[0] = t.T.u;
            e[1] = t.T.l;
            return e[s];
          },
          set(e, s, i) {
            if (s !== "1") {
              throw new TypeError("prop must be 1");
            }
            t.T.l = i;
            return true;
          }
        });
      }
      copy() {
        return new _OrderedMapIterator(this.T, this.C, this.container, this.iteratorType);
      }
    };
    var OrderedMap = class extends TreeContainer {
      static {
        __name(this, "OrderedMap");
      }
      constructor(t = [], e, s) {
        super(e, s);
        const i = this;
        t.forEach(function(t2) {
          i.setElement(t2[0], t2[1]);
        });
      }
      begin() {
        return new OrderedMapIterator(this.C.i || this.C, this.C, this);
      }
      end() {
        return new OrderedMapIterator(this.C, this.C, this);
      }
      rBegin() {
        return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1);
      }
      rEnd() {
        return new OrderedMapIterator(this.C, this.C, this, 1);
      }
      front() {
        if (this.m === 0) return;
        const t = this.C.i;
        return [t.u, t.l];
      }
      back() {
        if (this.m === 0) return;
        const t = this.C.h;
        return [t.u, t.l];
      }
      lowerBound(t) {
        const e = this.R(this.v, t);
        return new OrderedMapIterator(e, this.C, this);
      }
      upperBound(t) {
        const e = this.K(this.v, t);
        return new OrderedMapIterator(e, this.C, this);
      }
      reverseLowerBound(t) {
        const e = this.L(this.v, t);
        return new OrderedMapIterator(e, this.C, this);
      }
      reverseUpperBound(t) {
        const e = this.k(this.v, t);
        return new OrderedMapIterator(e, this.C, this);
      }
      forEach(t) {
        this.U(function(e, s, i) {
          t([e.u, e.l], s, i);
        });
      }
      setElement(t, e, s) {
        return this.q(t, e, s);
      }
      getElementByPos(t) {
        if (t < 0 || t > this.m - 1) {
          throw new RangeError();
        }
        const e = this.U(t);
        return [e.u, e.l];
      }
      find(t) {
        const e = this.H(this.v, t);
        return new OrderedMapIterator(e, this.C, this);
      }
      getElementByKey(t) {
        const e = this.H(this.v, t);
        return e.l;
      }
      union(t) {
        const e = this;
        t.forEach(function(t2) {
          e.setElement(t2[0], t2[1]);
        });
        return this.m;
      }
      *[Symbol.iterator]() {
        const t = this.m;
        const e = this.U();
        for (let s = 0; s < t; ++s) {
          const t2 = e[s];
          yield [t2.u, t2.l];
        }
      }
    };
    exports.OrderedMap = OrderedMap;
  }
});

// node_modules/@grpc/grpc-js/build/src/admin.js
var require_admin = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/admin.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.registerAdminService = registerAdminService;
    exports.addAdminServicesToServer = addAdminServicesToServer;
    var registeredAdminServices = [];
    function registerAdminService(getServiceDefinition, getHandlers) {
      registeredAdminServices.push({ getServiceDefinition, getHandlers });
    }
    __name(registerAdminService, "registerAdminService");
    function addAdminServicesToServer(server) {
      for (const { getServiceDefinition, getHandlers } of registeredAdminServices) {
        server.addService(getServiceDefinition(), getHandlers());
      }
    }
    __name(addAdminServicesToServer, "addAdminServicesToServer");
  }
});

// node_modules/@grpc/grpc-js/build/src/call.js
var require_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = void 0;
    exports.callErrorFromStatus = callErrorFromStatus;
    var events_1 = __require("events");
    var stream_1 = __require("stream");
    var constants_1 = require_constants2();
    function callErrorFromStatus(status, callerStack) {
      const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`;
      const error = new Error(message);
      const stack = `${error.stack}
for call at
${callerStack}`;
      return Object.assign(new Error(message), status, { stack });
    }
    __name(callErrorFromStatus, "callErrorFromStatus");
    var ClientUnaryCallImpl = class extends events_1.EventEmitter {
      static {
        __name(this, "ClientUnaryCallImpl");
      }
      constructor() {
        super();
      }
      cancel() {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown";
      }
      getAuthContext() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null;
      }
    };
    exports.ClientUnaryCallImpl = ClientUnaryCallImpl;
    var ClientReadableStreamImpl = class extends stream_1.Readable {
      static {
        __name(this, "ClientReadableStreamImpl");
      }
      constructor(deserialize) {
        super({ objectMode: true });
        this.deserialize = deserialize;
      }
      cancel() {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown";
      }
      getAuthContext() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null;
      }
      _read(_size) {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead();
      }
    };
    exports.ClientReadableStreamImpl = ClientReadableStreamImpl;
    var ClientWritableStreamImpl = class extends stream_1.Writable {
      static {
        __name(this, "ClientWritableStreamImpl");
      }
      constructor(serialize) {
        super({ objectMode: true });
        this.serialize = serialize;
      }
      cancel() {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown";
      }
      getAuthContext() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null;
      }
      _write(chunk, encoding, cb) {
        var _a;
        const context2 = {
          callback: cb
        };
        const flags = Number(encoding);
        if (!Number.isNaN(flags)) {
          context2.flags = flags;
        }
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context2, chunk);
      }
      _final(cb) {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose();
        cb();
      }
    };
    exports.ClientWritableStreamImpl = ClientWritableStreamImpl;
    var ClientDuplexStreamImpl = class extends stream_1.Duplex {
      static {
        __name(this, "ClientDuplexStreamImpl");
      }
      constructor(serialize, deserialize) {
        super({ objectMode: true });
        this.serialize = serialize;
        this.deserialize = deserialize;
      }
      cancel() {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client");
      }
      getPeer() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : "unknown";
      }
      getAuthContext() {
        var _a, _b;
        return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null;
      }
      _read(_size) {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead();
      }
      _write(chunk, encoding, cb) {
        var _a;
        const context2 = {
          callback: cb
        };
        const flags = Number(encoding);
        if (!Number.isNaN(flags)) {
          context2.flags = flags;
        }
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context2, chunk);
      }
      _final(cb) {
        var _a;
        (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose();
        cb();
      }
    };
    exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl;
  }
});

// node_modules/@grpc/grpc-js/build/src/call-interface.js
var require_call_interface = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call-interface.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InterceptingListenerImpl = void 0;
    exports.statusOrFromValue = statusOrFromValue;
    exports.statusOrFromError = statusOrFromError;
    exports.isInterceptingListener = isInterceptingListener;
    var metadata_1 = require_metadata();
    function statusOrFromValue(value) {
      return {
        ok: true,
        value
      };
    }
    __name(statusOrFromValue, "statusOrFromValue");
    function statusOrFromError(error) {
      var _a;
      return {
        ok: false,
        error: Object.assign(Object.assign({}, error), { metadata: (_a = error.metadata) !== null && _a !== void 0 ? _a : new metadata_1.Metadata() })
      };
    }
    __name(statusOrFromError, "statusOrFromError");
    function isInterceptingListener(listener) {
      return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1;
    }
    __name(isInterceptingListener, "isInterceptingListener");
    var InterceptingListenerImpl = class {
      static {
        __name(this, "InterceptingListenerImpl");
      }
      constructor(listener, nextListener) {
        this.listener = listener;
        this.nextListener = nextListener;
        this.processingMetadata = false;
        this.hasPendingMessage = false;
        this.processingMessage = false;
        this.pendingStatus = null;
      }
      processPendingMessage() {
        if (this.hasPendingMessage) {
          this.nextListener.onReceiveMessage(this.pendingMessage);
          this.pendingMessage = null;
          this.hasPendingMessage = false;
        }
      }
      processPendingStatus() {
        if (this.pendingStatus) {
          this.nextListener.onReceiveStatus(this.pendingStatus);
        }
      }
      onReceiveMetadata(metadata) {
        this.processingMetadata = true;
        this.listener.onReceiveMetadata(metadata, (metadata2) => {
          this.processingMetadata = false;
          this.nextListener.onReceiveMetadata(metadata2);
          this.processPendingMessage();
          this.processPendingStatus();
        });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      onReceiveMessage(message) {
        this.processingMessage = true;
        this.listener.onReceiveMessage(message, (msg) => {
          this.processingMessage = false;
          if (this.processingMetadata) {
            this.pendingMessage = msg;
            this.hasPendingMessage = true;
          } else {
            this.nextListener.onReceiveMessage(msg);
            this.processPendingStatus();
          }
        });
      }
      onReceiveStatus(status) {
        this.listener.onReceiveStatus(status, (processedStatus) => {
          if (this.processingMetadata || this.processingMessage) {
            this.pendingStatus = processedStatus;
          } else {
            this.nextListener.onReceiveStatus(processedStatus);
          }
        });
      }
    };
    exports.InterceptingListenerImpl = InterceptingListenerImpl;
  }
});

// node_modules/@grpc/grpc-js/build/src/client-interceptors.js
var require_client_interceptors = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/client-interceptors.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = void 0;
    exports.getInterceptingCall = getInterceptingCall;
    var metadata_1 = require_metadata();
    var call_interface_1 = require_call_interface();
    var constants_1 = require_constants2();
    var error_1 = require_error();
    var InterceptorConfigurationError = class _InterceptorConfigurationError extends Error {
      static {
        __name(this, "InterceptorConfigurationError");
      }
      constructor(message) {
        super(message);
        this.name = "InterceptorConfigurationError";
        Error.captureStackTrace(this, _InterceptorConfigurationError);
      }
    };
    exports.InterceptorConfigurationError = InterceptorConfigurationError;
    var ListenerBuilder = class {
      static {
        __name(this, "ListenerBuilder");
      }
      constructor() {
        this.metadata = void 0;
        this.message = void 0;
        this.status = void 0;
      }
      withOnReceiveMetadata(onReceiveMetadata) {
        this.metadata = onReceiveMetadata;
        return this;
      }
      withOnReceiveMessage(onReceiveMessage) {
        this.message = onReceiveMessage;
        return this;
      }
      withOnReceiveStatus(onReceiveStatus) {
        this.status = onReceiveStatus;
        return this;
      }
      build() {
        return {
          onReceiveMetadata: this.metadata,
          onReceiveMessage: this.message,
          onReceiveStatus: this.status
        };
      }
    };
    exports.ListenerBuilder = ListenerBuilder;
    var RequesterBuilder = class {
      static {
        __name(this, "RequesterBuilder");
      }
      constructor() {
        this.start = void 0;
        this.message = void 0;
        this.halfClose = void 0;
        this.cancel = void 0;
      }
      withStart(start) {
        this.start = start;
        return this;
      }
      withSendMessage(sendMessage) {
        this.message = sendMessage;
        return this;
      }
      withHalfClose(halfClose) {
        this.halfClose = halfClose;
        return this;
      }
      withCancel(cancel) {
        this.cancel = cancel;
        return this;
      }
      build() {
        return {
          start: this.start,
          sendMessage: this.message,
          halfClose: this.halfClose,
          cancel: this.cancel
        };
      }
    };
    exports.RequesterBuilder = RequesterBuilder;
    var defaultListener = {
      onReceiveMetadata: /* @__PURE__ */ __name((metadata, next) => {
        next(metadata);
      }, "onReceiveMetadata"),
      onReceiveMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "onReceiveMessage"),
      onReceiveStatus: /* @__PURE__ */ __name((status, next) => {
        next(status);
      }, "onReceiveStatus")
    };
    var defaultRequester = {
      start: /* @__PURE__ */ __name((metadata, listener, next) => {
        next(metadata, listener);
      }, "start"),
      sendMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "sendMessage"),
      halfClose: /* @__PURE__ */ __name((next) => {
        next();
      }, "halfClose"),
      cancel: /* @__PURE__ */ __name((next) => {
        next();
      }, "cancel")
    };
    var InterceptingCall = class {
      static {
        __name(this, "InterceptingCall");
      }
      constructor(nextCall, requester) {
        var _a, _b, _c, _d;
        this.nextCall = nextCall;
        this.processingMetadata = false;
        this.pendingMessageContext = null;
        this.processingMessage = false;
        this.pendingHalfClose = false;
        if (requester) {
          this.requester = {
            start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start,
            sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage,
            halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose,
            cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel
          };
        } else {
          this.requester = defaultRequester;
        }
      }
      cancelWithStatus(status, details) {
        this.requester.cancel(() => {
          this.nextCall.cancelWithStatus(status, details);
        });
      }
      getPeer() {
        return this.nextCall.getPeer();
      }
      processPendingMessage() {
        if (this.pendingMessageContext) {
          this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage);
          this.pendingMessageContext = null;
          this.pendingMessage = null;
        }
      }
      processPendingHalfClose() {
        if (this.pendingHalfClose) {
          this.nextCall.halfClose();
        }
      }
      start(metadata, interceptingListener) {
        var _a, _b, _c, _d, _e, _f;
        const fullInterceptingListener = {
          onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : (metadata2) => {
          },
          onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : (message) => {
          },
          onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status) => {
          }
        };
        this.processingMetadata = true;
        this.requester.start(metadata, fullInterceptingListener, (md, listener) => {
          var _a2, _b2, _c2;
          this.processingMetadata = false;
          let finalInterceptingListener;
          if ((0, call_interface_1.isInterceptingListener)(listener)) {
            finalInterceptingListener = listener;
          } else {
            const fullListener = {
              onReceiveMetadata: (_a2 = listener.onReceiveMetadata) !== null && _a2 !== void 0 ? _a2 : defaultListener.onReceiveMetadata,
              onReceiveMessage: (_b2 = listener.onReceiveMessage) !== null && _b2 !== void 0 ? _b2 : defaultListener.onReceiveMessage,
              onReceiveStatus: (_c2 = listener.onReceiveStatus) !== null && _c2 !== void 0 ? _c2 : defaultListener.onReceiveStatus
            };
            finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener);
          }
          this.nextCall.start(md, finalInterceptingListener);
          this.processPendingMessage();
          this.processPendingHalfClose();
        });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessageWithContext(context2, message) {
        this.processingMessage = true;
        this.requester.sendMessage(message, (finalMessage) => {
          this.processingMessage = false;
          if (this.processingMetadata) {
            this.pendingMessageContext = context2;
            this.pendingMessage = message;
          } else {
            this.nextCall.sendMessageWithContext(context2, finalMessage);
            this.processPendingHalfClose();
          }
        });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessage(message) {
        this.sendMessageWithContext({}, message);
      }
      startRead() {
        this.nextCall.startRead();
      }
      halfClose() {
        this.requester.halfClose(() => {
          if (this.processingMetadata || this.processingMessage) {
            this.pendingHalfClose = true;
          } else {
            this.nextCall.halfClose();
          }
        });
      }
      getAuthContext() {
        return this.nextCall.getAuthContext();
      }
    };
    exports.InterceptingCall = InterceptingCall;
    function getCall(channel, path11, options) {
      var _a, _b;
      const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity;
      const host = options.host;
      const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null;
      const propagateFlags = options.propagate_flags;
      const credentials = options.credentials;
      const call = channel.createCall(path11, deadline, host, parent, propagateFlags);
      if (credentials) {
        call.setCredentials(credentials);
      }
      return call;
    }
    __name(getCall, "getCall");
    var BaseInterceptingCall = class {
      static {
        __name(this, "BaseInterceptingCall");
      }
      constructor(call, methodDefinition) {
        this.call = call;
        this.methodDefinition = methodDefinition;
      }
      cancelWithStatus(status, details) {
        this.call.cancelWithStatus(status, details);
      }
      getPeer() {
        return this.call.getPeer();
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessageWithContext(context2, message) {
        let serialized;
        try {
          serialized = this.methodDefinition.requestSerialize(message);
        } catch (e) {
          this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`);
          return;
        }
        this.call.sendMessageWithContext(context2, serialized);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      sendMessage(message) {
        this.sendMessageWithContext({}, message);
      }
      start(metadata, interceptingListener) {
        let readError = null;
        this.call.start(metadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata2) => {
            var _a;
            (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata2);
          }, "onReceiveMetadata"),
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            var _a;
            let deserialized;
            try {
              deserialized = this.methodDefinition.responseDeserialize(message);
            } catch (e) {
              readError = {
                code: constants_1.Status.INTERNAL,
                details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`,
                metadata: new metadata_1.Metadata()
              };
              this.call.cancelWithStatus(readError.code, readError.details);
              return;
            }
            (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized);
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            var _a, _b;
            if (readError) {
              (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError);
            } else {
              (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status);
            }
          }, "onReceiveStatus")
        });
      }
      startRead() {
        this.call.startRead();
      }
      halfClose() {
        this.call.halfClose();
      }
      getAuthContext() {
        return this.call.getAuthContext();
      }
    };
    var BaseUnaryInterceptingCall = class extends BaseInterceptingCall {
      static {
        __name(this, "BaseUnaryInterceptingCall");
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      constructor(call, methodDefinition) {
        super(call, methodDefinition);
      }
      start(metadata, listener) {
        var _a, _b;
        let receivedMessage = false;
        const wrapperListener = {
          onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : (metadata2) => {
          },
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            var _a2;
            receivedMessage = true;
            (_a2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a2 === void 0 ? void 0 : _a2.call(listener, message);
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            var _a2, _b2;
            if (!receivedMessage) {
              (_a2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a2 === void 0 ? void 0 : _a2.call(listener, null);
            }
            (_b2 = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b2 === void 0 ? void 0 : _b2.call(listener, status);
          }, "onReceiveStatus")
        };
        super.start(metadata, wrapperListener);
        this.call.startRead();
      }
    };
    var BaseStreamingInterceptingCall = class extends BaseInterceptingCall {
      static {
        __name(this, "BaseStreamingInterceptingCall");
      }
    };
    function getBottomInterceptingCall(channel, options, methodDefinition) {
      const call = getCall(channel, methodDefinition.path, options);
      if (methodDefinition.responseStream) {
        return new BaseStreamingInterceptingCall(call, methodDefinition);
      } else {
        return new BaseUnaryInterceptingCall(call, methodDefinition);
      }
    }
    __name(getBottomInterceptingCall, "getBottomInterceptingCall");
    function getInterceptingCall(interceptorArgs, methodDefinition, options, channel) {
      if (interceptorArgs.clientInterceptors.length > 0 && interceptorArgs.clientInterceptorProviders.length > 0) {
        throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");
      }
      if (interceptorArgs.callInterceptors.length > 0 && interceptorArgs.callInterceptorProviders.length > 0) {
        throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");
      }
      let interceptors = [];
      if (interceptorArgs.callInterceptors.length > 0 || interceptorArgs.callInterceptorProviders.length > 0) {
        interceptors = [].concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor);
      } else {
        interceptors = [].concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor);
      }
      const interceptorOptions = Object.assign({}, options, {
        method_definition: methodDefinition
      });
      const getCall2 = interceptors.reduceRight((nextCall, nextInterceptor) => {
        return (currentOptions) => nextInterceptor(currentOptions, nextCall);
      }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition));
      return getCall2(interceptorOptions);
    }
    __name(getInterceptingCall, "getInterceptingCall");
  }
});

// node_modules/@grpc/grpc-js/build/src/client.js
var require_client = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/client.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Client = void 0;
    var call_1 = require_call();
    var channel_1 = require_channel();
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants2();
    var metadata_1 = require_metadata();
    var client_interceptors_1 = require_client_interceptors();
    var CHANNEL_SYMBOL = Symbol();
    var INTERCEPTOR_SYMBOL = Symbol();
    var INTERCEPTOR_PROVIDER_SYMBOL = Symbol();
    var CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol();
    function isFunction(arg) {
      return typeof arg === "function";
    }
    __name(isFunction, "isFunction");
    function getErrorStackString(error) {
      var _a;
      return ((_a = error.stack) === null || _a === void 0 ? void 0 : _a.split("\n").slice(1).join("\n")) || "no stack trace available";
    }
    __name(getErrorStackString, "getErrorStackString");
    var Client = class {
      static {
        __name(this, "Client");
      }
      constructor(address, credentials, options = {}) {
        var _a, _b;
        options = Object.assign({}, options);
        this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : [];
        delete options.interceptors;
        this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : [];
        delete options.interceptor_providers;
        if (this[INTERCEPTOR_SYMBOL].length > 0 && this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) {
          throw new Error("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");
        }
        this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = options.callInvocationTransformer;
        delete options.callInvocationTransformer;
        if (options.channelOverride) {
          this[CHANNEL_SYMBOL] = options.channelOverride;
        } else if (options.channelFactoryOverride) {
          const channelFactoryOverride = options.channelFactoryOverride;
          delete options.channelFactoryOverride;
          this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options);
        } else {
          this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options);
        }
      }
      close() {
        this[CHANNEL_SYMBOL].close();
      }
      getChannel() {
        return this[CHANNEL_SYMBOL];
      }
      waitForReady(deadline, callback) {
        const checkState = /* @__PURE__ */ __name((err) => {
          if (err) {
            callback(new Error("Failed to connect before the deadline"));
            return;
          }
          let newState;
          try {
            newState = this[CHANNEL_SYMBOL].getConnectivityState(true);
          } catch (e) {
            callback(new Error("The channel has been closed"));
            return;
          }
          if (newState === connectivity_state_1.ConnectivityState.READY) {
            callback();
          } else {
            try {
              this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState);
            } catch (e) {
              callback(new Error("The channel has been closed"));
            }
          }
        }, "checkState");
        setImmediate(checkState);
      }
      checkOptionalUnaryResponseArguments(arg1, arg2, arg3) {
        if (isFunction(arg1)) {
          return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 };
        } else if (isFunction(arg2)) {
          if (arg1 instanceof metadata_1.Metadata) {
            return { metadata: arg1, options: {}, callback: arg2 };
          } else {
            return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 };
          }
        } else {
          if (!(arg1 instanceof metadata_1.Metadata && arg2 instanceof Object && isFunction(arg3))) {
            throw new Error("Incorrect arguments passed");
          }
          return { metadata: arg1, options: arg2, callback: arg3 };
        }
      }
      makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) {
        var _a, _b;
        const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback);
        const methodDefinition = {
          path: method,
          requestStream: false,
          responseStream: false,
          requestSerialize: serialize,
          responseDeserialize: deserialize
        };
        let callProperties = {
          argument,
          metadata: checkedArguments.metadata,
          call: new call_1.ClientUnaryCallImpl(),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options,
          callback: checkedArguments.callback
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const emitter = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],
          callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        emitter.call = call;
        let responseMessage = null;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata2) => {
            emitter.emit("metadata", metadata2);
          }, "onReceiveMetadata"),
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage(message) {
            if (responseMessage !== null) {
              call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received");
            }
            responseMessage = message;
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            if (status.code === constants_1.Status.OK) {
              if (responseMessage === null) {
                const callerStack = getErrorStackString(callerStackError);
                callProperties.callback((0, call_1.callErrorFromStatus)({
                  code: constants_1.Status.UNIMPLEMENTED,
                  details: "No message received",
                  metadata: status.metadata
                }, callerStack));
              } else {
                callProperties.callback(null, responseMessage);
              }
            } else {
              const callerStack = getErrorStackString(callerStackError);
              callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            emitter.emit("status", status);
          }
        });
        call.sendMessage(argument);
        call.halfClose();
        return emitter;
      }
      makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) {
        var _a, _b;
        const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback);
        const methodDefinition = {
          path: method,
          requestStream: true,
          responseStream: false,
          requestSerialize: serialize,
          responseDeserialize: deserialize
        };
        let callProperties = {
          metadata: checkedArguments.metadata,
          call: new call_1.ClientWritableStreamImpl(serialize),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options,
          callback: checkedArguments.callback
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const emitter = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],
          callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        emitter.call = call;
        let responseMessage = null;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata2) => {
            emitter.emit("metadata", metadata2);
          }, "onReceiveMetadata"),
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage(message) {
            if (responseMessage !== null) {
              call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received");
            }
            responseMessage = message;
            call.startRead();
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            if (status.code === constants_1.Status.OK) {
              if (responseMessage === null) {
                const callerStack = getErrorStackString(callerStackError);
                callProperties.callback((0, call_1.callErrorFromStatus)({
                  code: constants_1.Status.UNIMPLEMENTED,
                  details: "No message received",
                  metadata: status.metadata
                }, callerStack));
              } else {
                callProperties.callback(null, responseMessage);
              }
            } else {
              const callerStack = getErrorStackString(callerStackError);
              callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            emitter.emit("status", status);
          }
        });
        return emitter;
      }
      checkMetadataAndOptions(arg1, arg2) {
        let metadata;
        let options;
        if (arg1 instanceof metadata_1.Metadata) {
          metadata = arg1;
          if (arg2) {
            options = arg2;
          } else {
            options = {};
          }
        } else {
          if (arg1) {
            options = arg1;
          } else {
            options = {};
          }
          metadata = new metadata_1.Metadata();
        }
        return { metadata, options };
      }
      makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) {
        var _a, _b;
        const checkedArguments = this.checkMetadataAndOptions(metadata, options);
        const methodDefinition = {
          path: method,
          requestStream: false,
          responseStream: true,
          requestSerialize: serialize,
          responseDeserialize: deserialize
        };
        let callProperties = {
          argument,
          metadata: checkedArguments.metadata,
          call: new call_1.ClientReadableStreamImpl(deserialize),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const stream = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],
          callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        stream.call = call;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata(metadata2) {
            stream.emit("metadata", metadata2);
          },
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage(message) {
            stream.push(message);
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            stream.push(null);
            if (status.code !== constants_1.Status.OK) {
              const callerStack = getErrorStackString(callerStackError);
              stream.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            stream.emit("status", status);
          }
        });
        call.sendMessage(argument);
        call.halfClose();
        return stream;
      }
      makeBidiStreamRequest(method, serialize, deserialize, metadata, options) {
        var _a, _b;
        const checkedArguments = this.checkMetadataAndOptions(metadata, options);
        const methodDefinition = {
          path: method,
          requestStream: true,
          responseStream: true,
          requestSerialize: serialize,
          responseDeserialize: deserialize
        };
        let callProperties = {
          metadata: checkedArguments.metadata,
          call: new call_1.ClientDuplexStreamImpl(serialize, deserialize),
          channel: this[CHANNEL_SYMBOL],
          methodDefinition,
          callOptions: checkedArguments.options
        };
        if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) {
          callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties);
        }
        const stream = callProperties.call;
        const interceptorArgs = {
          clientInterceptors: this[INTERCEPTOR_SYMBOL],
          clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL],
          callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [],
          callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : []
        };
        const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel);
        stream.call = call;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata(metadata2) {
            stream.emit("metadata", metadata2);
          },
          onReceiveMessage(message) {
            stream.push(message);
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            stream.push(null);
            if (status.code !== constants_1.Status.OK) {
              const callerStack = getErrorStackString(callerStackError);
              stream.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            stream.emit("status", status);
          }
        });
        return stream;
      }
    };
    exports.Client = Client;
  }
});

// node_modules/@grpc/grpc-js/build/src/make-client.js
var require_make_client = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/make-client.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.makeClientConstructor = makeClientConstructor;
    exports.loadPackageDefinition = loadPackageDefinition;
    var client_1 = require_client();
    var requesterFuncs = {
      unary: client_1.Client.prototype.makeUnaryRequest,
      server_stream: client_1.Client.prototype.makeServerStreamRequest,
      client_stream: client_1.Client.prototype.makeClientStreamRequest,
      bidi: client_1.Client.prototype.makeBidiStreamRequest
    };
    function isPrototypePolluted(key) {
      return ["__proto__", "prototype", "constructor"].includes(key);
    }
    __name(isPrototypePolluted, "isPrototypePolluted");
    function makeClientConstructor(methods, serviceName, classOptions) {
      if (!classOptions) {
        classOptions = {};
      }
      class ServiceClientImpl extends client_1.Client {
        static {
          __name(this, "ServiceClientImpl");
        }
      }
      Object.keys(methods).forEach((name) => {
        if (isPrototypePolluted(name)) {
          return;
        }
        const attrs = methods[name];
        let methodType;
        if (typeof name === "string" && name.charAt(0) === "$") {
          throw new Error("Method names cannot start with $");
        }
        if (attrs.requestStream) {
          if (attrs.responseStream) {
            methodType = "bidi";
          } else {
            methodType = "client_stream";
          }
        } else {
          if (attrs.responseStream) {
            methodType = "server_stream";
          } else {
            methodType = "unary";
          }
        }
        const serialize = attrs.requestSerialize;
        const deserialize = attrs.responseDeserialize;
        const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize);
        ServiceClientImpl.prototype[name] = methodFunc;
        Object.assign(ServiceClientImpl.prototype[name], attrs);
        if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) {
          ServiceClientImpl.prototype[attrs.originalName] = ServiceClientImpl.prototype[name];
        }
      });
      ServiceClientImpl.service = methods;
      ServiceClientImpl.serviceName = serviceName;
      return ServiceClientImpl;
    }
    __name(makeClientConstructor, "makeClientConstructor");
    function partial(fn, path11, serialize, deserialize) {
      return function(...args) {
        return fn.call(this, path11, serialize, deserialize, ...args);
      };
    }
    __name(partial, "partial");
    function isProtobufTypeDefinition(obj) {
      return "format" in obj;
    }
    __name(isProtobufTypeDefinition, "isProtobufTypeDefinition");
    function loadPackageDefinition(packageDef) {
      const result = {};
      for (const serviceFqn in packageDef) {
        if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) {
          const service = packageDef[serviceFqn];
          const nameComponents = serviceFqn.split(".");
          if (nameComponents.some((comp) => isPrototypePolluted(comp))) {
            continue;
          }
          const serviceName = nameComponents[nameComponents.length - 1];
          let current = result;
          for (const packageName of nameComponents.slice(0, -1)) {
            if (!current[packageName]) {
              current[packageName] = {};
            }
            current = current[packageName];
          }
          if (isProtobufTypeDefinition(service)) {
            current[serviceName] = service;
          } else {
            current[serviceName] = makeClientConstructor(service, serviceName, {});
          }
        }
      }
      return result;
    }
    __name(loadPackageDefinition, "loadPackageDefinition");
  }
});

// node_modules/lodash.camelcase/index.js
var require_lodash = __commonJS({
  "node_modules/lodash.camelcase/index.js"(exports, module) {
    init_esbuild_shims();
    var INFINITY = 1 / 0;
    var symbolTag = "[object Symbol]";
    var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
    var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
    var rsAstralRange = "\\ud800-\\udfff";
    var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
    var rsComboSymbolsRange = "\\u20d0-\\u20f0";
    var rsDingbatRange = "\\u2700-\\u27bf";
    var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff";
    var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7";
    var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf";
    var rsPunctuationRange = "\\u2000-\\u206f";
    var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000";
    var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde";
    var rsVarRange = "\\ufe0e\\ufe0f";
    var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
    var rsApos = "['\u2019]";
    var rsAstral = "[" + rsAstralRange + "]";
    var rsBreak = "[" + rsBreakRange + "]";
    var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
    var rsDigits = "\\d+";
    var rsDingbat = "[" + rsDingbatRange + "]";
    var rsLower = "[" + rsLowerRange + "]";
    var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]";
    var rsFitz = "\\ud83c[\\udffb-\\udfff]";
    var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")";
    var rsNonAstral = "[^" + rsAstralRange + "]";
    var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
    var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
    var rsUpper = "[" + rsUpperRange + "]";
    var rsZWJ = "\\u200d";
    var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")";
    var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")";
    var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?";
    var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?";
    var reOptMod = rsModifier + "?";
    var rsOptVar = "[" + rsVarRange + "]?";
    var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*";
    var rsSeq = rsOptVar + reOptMod + rsOptJoin;
    var rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq;
    var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
    var reApos = RegExp(rsApos, "g");
    var reComboMark = RegExp(rsCombo, "g");
    var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
    var reUnicodeWord = RegExp([
      rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")",
      rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [rsBreak, rsUpper + rsLowerMisc, "$"].join("|") + ")",
      rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr,
      rsUpper + "+" + rsOptUpperContr,
      rsDigits,
      rsEmoji
    ].join("|"), "g");
    var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]");
    var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
    var deburredLetters = {
      // Latin-1 Supplement block.
      "\xC0": "A",
      "\xC1": "A",
      "\xC2": "A",
      "\xC3": "A",
      "\xC4": "A",
      "\xC5": "A",
      "\xE0": "a",
      "\xE1": "a",
      "\xE2": "a",
      "\xE3": "a",
      "\xE4": "a",
      "\xE5": "a",
      "\xC7": "C",
      "\xE7": "c",
      "\xD0": "D",
      "\xF0": "d",
      "\xC8": "E",
      "\xC9": "E",
      "\xCA": "E",
      "\xCB": "E",
      "\xE8": "e",
      "\xE9": "e",
      "\xEA": "e",
      "\xEB": "e",
      "\xCC": "I",
      "\xCD": "I",
      "\xCE": "I",
      "\xCF": "I",
      "\xEC": "i",
      "\xED": "i",
      "\xEE": "i",
      "\xEF": "i",
      "\xD1": "N",
      "\xF1": "n",
      "\xD2": "O",
      "\xD3": "O",
      "\xD4": "O",
      "\xD5": "O",
      "\xD6": "O",
      "\xD8": "O",
      "\xF2": "o",
      "\xF3": "o",
      "\xF4": "o",
      "\xF5": "o",
      "\xF6": "o",
      "\xF8": "o",
      "\xD9": "U",
      "\xDA": "U",
      "\xDB": "U",
      "\xDC": "U",
      "\xF9": "u",
      "\xFA": "u",
      "\xFB": "u",
      "\xFC": "u",
      "\xDD": "Y",
      "\xFD": "y",
      "\xFF": "y",
      "\xC6": "Ae",
      "\xE6": "ae",
      "\xDE": "Th",
      "\xFE": "th",
      "\xDF": "ss",
      // Latin Extended-A block.
      "\u0100": "A",
      "\u0102": "A",
      "\u0104": "A",
      "\u0101": "a",
      "\u0103": "a",
      "\u0105": "a",
      "\u0106": "C",
      "\u0108": "C",
      "\u010A": "C",
      "\u010C": "C",
      "\u0107": "c",
      "\u0109": "c",
      "\u010B": "c",
      "\u010D": "c",
      "\u010E": "D",
      "\u0110": "D",
      "\u010F": "d",
      "\u0111": "d",
      "\u0112": "E",
      "\u0114": "E",
      "\u0116": "E",
      "\u0118": "E",
      "\u011A": "E",
      "\u0113": "e",
      "\u0115": "e",
      "\u0117": "e",
      "\u0119": "e",
      "\u011B": "e",
      "\u011C": "G",
      "\u011E": "G",
      "\u0120": "G",
      "\u0122": "G",
      "\u011D": "g",
      "\u011F": "g",
      "\u0121": "g",
      "\u0123": "g",
      "\u0124": "H",
      "\u0126": "H",
      "\u0125": "h",
      "\u0127": "h",
      "\u0128": "I",
      "\u012A": "I",
      "\u012C": "I",
      "\u012E": "I",
      "\u0130": "I",
      "\u0129": "i",
      "\u012B": "i",
      "\u012D": "i",
      "\u012F": "i",
      "\u0131": "i",
      "\u0134": "J",
      "\u0135": "j",
      "\u0136": "K",
      "\u0137": "k",
      "\u0138": "k",
      "\u0139": "L",
      "\u013B": "L",
      "\u013D": "L",
      "\u013F": "L",
      "\u0141": "L",
      "\u013A": "l",
      "\u013C": "l",
      "\u013E": "l",
      "\u0140": "l",
      "\u0142": "l",
      "\u0143": "N",
      "\u0145": "N",
      "\u0147": "N",
      "\u014A": "N",
      "\u0144": "n",
      "\u0146": "n",
      "\u0148": "n",
      "\u014B": "n",
      "\u014C": "O",
      "\u014E": "O",
      "\u0150": "O",
      "\u014D": "o",
      "\u014F": "o",
      "\u0151": "o",
      "\u0154": "R",
      "\u0156": "R",
      "\u0158": "R",
      "\u0155": "r",
      "\u0157": "r",
      "\u0159": "r",
      "\u015A": "S",
      "\u015C": "S",
      "\u015E": "S",
      "\u0160": "S",
      "\u015B": "s",
      "\u015D": "s",
      "\u015F": "s",
      "\u0161": "s",
      "\u0162": "T",
      "\u0164": "T",
      "\u0166": "T",
      "\u0163": "t",
      "\u0165": "t",
      "\u0167": "t",
      "\u0168": "U",
      "\u016A": "U",
      "\u016C": "U",
      "\u016E": "U",
      "\u0170": "U",
      "\u0172": "U",
      "\u0169": "u",
      "\u016B": "u",
      "\u016D": "u",
      "\u016F": "u",
      "\u0171": "u",
      "\u0173": "u",
      "\u0174": "W",
      "\u0175": "w",
      "\u0176": "Y",
      "\u0177": "y",
      "\u0178": "Y",
      "\u0179": "Z",
      "\u017B": "Z",
      "\u017D": "Z",
      "\u017A": "z",
      "\u017C": "z",
      "\u017E": "z",
      "\u0132": "IJ",
      "\u0133": "ij",
      "\u0152": "Oe",
      "\u0153": "oe",
      "\u0149": "'n",
      "\u017F": "ss"
    };
    var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    function arrayReduce(array, iteratee, accumulator, initAccum) {
      var index = -1, length = array ? array.length : 0;
      if (initAccum && length) {
        accumulator = array[++index];
      }
      while (++index < length) {
        accumulator = iteratee(accumulator, array[index], index, array);
      }
      return accumulator;
    }
    __name(arrayReduce, "arrayReduce");
    function asciiToArray(string) {
      return string.split("");
    }
    __name(asciiToArray, "asciiToArray");
    function asciiWords(string) {
      return string.match(reAsciiWord) || [];
    }
    __name(asciiWords, "asciiWords");
    function basePropertyOf(object) {
      return function(key) {
        return object == null ? void 0 : object[key];
      };
    }
    __name(basePropertyOf, "basePropertyOf");
    var deburrLetter = basePropertyOf(deburredLetters);
    function hasUnicode(string) {
      return reHasUnicode.test(string);
    }
    __name(hasUnicode, "hasUnicode");
    function hasUnicodeWord(string) {
      return reHasUnicodeWord.test(string);
    }
    __name(hasUnicodeWord, "hasUnicodeWord");
    function stringToArray(string) {
      return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string);
    }
    __name(stringToArray, "stringToArray");
    function unicodeToArray(string) {
      return string.match(reUnicode) || [];
    }
    __name(unicodeToArray, "unicodeToArray");
    function unicodeWords(string) {
      return string.match(reUnicodeWord) || [];
    }
    __name(unicodeWords, "unicodeWords");
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var Symbol2 = root.Symbol;
    var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
    var symbolToString = symbolProto ? symbolProto.toString : void 0;
    function baseSlice(array, start, end) {
      var index = -1, length = array.length;
      if (start < 0) {
        start = -start > length ? 0 : length + start;
      }
      end = end > length ? length : end;
      if (end < 0) {
        end += length;
      }
      length = start > end ? 0 : end - start >>> 0;
      start >>>= 0;
      var result = Array(length);
      while (++index < length) {
        result[index] = array[index + start];
      }
      return result;
    }
    __name(baseSlice, "baseSlice");
    function baseToString(value) {
      if (typeof value == "string") {
        return value;
      }
      if (isSymbol(value)) {
        return symbolToString ? symbolToString.call(value) : "";
      }
      var result = value + "";
      return result == "0" && 1 / value == -INFINITY ? "-0" : result;
    }
    __name(baseToString, "baseToString");
    function castSlice(array, start, end) {
      var length = array.length;
      end = end === void 0 ? length : end;
      return !start && end >= length ? array : baseSlice(array, start, end);
    }
    __name(castSlice, "castSlice");
    function createCaseFirst(methodName) {
      return function(string) {
        string = toString(string);
        var strSymbols = hasUnicode(string) ? stringToArray(string) : void 0;
        var chr = strSymbols ? strSymbols[0] : string.charAt(0);
        var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1);
        return chr[methodName]() + trailing;
      };
    }
    __name(createCaseFirst, "createCaseFirst");
    function createCompounder(callback) {
      return function(string) {
        return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "");
      };
    }
    __name(createCompounder, "createCompounder");
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    __name(isObjectLike, "isObjectLike");
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    __name(isSymbol, "isSymbol");
    function toString(value) {
      return value == null ? "" : baseToString(value);
    }
    __name(toString, "toString");
    var camelCase = createCompounder(function(result, word, index) {
      word = word.toLowerCase();
      return result + (index ? capitalize(word) : word);
    });
    function capitalize(string) {
      return upperFirst(toString(string).toLowerCase());
    }
    __name(capitalize, "capitalize");
    function deburr(string) {
      string = toString(string);
      return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
    }
    __name(deburr, "deburr");
    var upperFirst = createCaseFirst("toUpperCase");
    function words(string, pattern, guard) {
      string = toString(string);
      pattern = guard ? void 0 : pattern;
      if (pattern === void 0) {
        return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
      }
      return string.match(pattern) || [];
    }
    __name(words, "words");
    module.exports = camelCase;
  }
});

// node_modules/@protobufjs/codegen/index.js
var require_codegen = __commonJS({
  "node_modules/@protobufjs/codegen/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = codegen;
    var reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/;
    function codegen(functionParams, functionName) {
      if (typeof functionParams === "string") {
        functionName = functionParams;
        functionParams = void 0;
      }
      var body = [];
      function Codegen(formatStringOrScope) {
        if (typeof formatStringOrScope !== "string") {
          var source = toString();
          if (codegen.verbose)
            console.log("codegen: " + source);
          source = "return " + source;
          if (formatStringOrScope) {
            var scopeKeys = Object.keys(formatStringOrScope), scopeParams = new Array(scopeKeys.length + 1), scopeValues = new Array(scopeKeys.length), scopeOffset = 0;
            while (scopeOffset < scopeKeys.length) {
              scopeParams[scopeOffset] = scopeKeys[scopeOffset];
              scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];
            }
            scopeParams[scopeOffset] = source;
            return Function.apply(null, scopeParams).apply(null, scopeValues);
          }
          return Function(source)();
        }
        var formatParams = new Array(arguments.length - 1), formatOffset = 0;
        while (formatOffset < formatParams.length)
          formatParams[formatOffset] = arguments[++formatOffset];
        formatOffset = 0;
        formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, /* @__PURE__ */ __name(function replace($0, $1) {
          var value = formatParams[formatOffset++];
          switch ($1) {
            case "d":
            case "f":
              return String(Number(value));
            case "i":
              return String(Math.floor(value));
            case "j":
              return JSON.stringify(value);
            case "s":
              return String(value);
          }
          return "%";
        }, "replace"));
        if (formatOffset !== formatParams.length)
          throw Error("parameter count mismatch");
        body.push(formatStringOrScope);
        return Codegen;
      }
      __name(Codegen, "Codegen");
      function toString(functionNameOverride) {
        return "function " + safeFunctionName(functionNameOverride || functionName) + "(" + (functionParams && functionParams.join(",") || "") + "){\n  " + body.join("\n  ") + "\n}";
      }
      __name(toString, "toString");
      Codegen.toString = toString;
      return Codegen;
    }
    __name(codegen, "codegen");
    codegen.verbose = false;
    function safeFunctionName(name) {
      if (!name)
        return "";
      name = String(name).replace(/[^\w$]/g, "");
      if (!name)
        return "";
      if (/^\d/.test(name))
        name = "_" + name;
      return reservedRe.test(name) ? name + "_" : name;
    }
    __name(safeFunctionName, "safeFunctionName");
  }
});

// node_modules/@protobufjs/fetch/util/fs.js
var require_fs = __commonJS({
  "node_modules/@protobufjs/fetch/util/fs.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var fs9 = null;
    try {
      fs9 = __require(
        /* webpackIgnore: true */
        "fs"
      );
      if (!fs9 || !fs9.readFile || !fs9.readFileSync)
        fs9 = null;
    } catch (e) {
    }
    module.exports = fs9;
  }
});

// node_modules/@protobufjs/fetch/index.js
var require_fetch = __commonJS({
  "node_modules/@protobufjs/fetch/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = fetch;
    var asPromise = require_aspromise();
    var fs9 = require_fs();
    function fetch(filename, options, callback) {
      if (typeof options === "function") {
        callback = options;
        options = {};
      } else if (!options)
        options = {};
      if (!callback)
        return asPromise(fetch, this, filename, options);
      if (!options.xhr && fs9 && fs9.readFile)
        return fs9.readFile(filename, /* @__PURE__ */ __name(function fetchReadFileCallback(err, contents) {
          return err && typeof XMLHttpRequest !== "undefined" ? fetch.xhr(filename, options, callback) : err ? callback(err) : callback(null, options.binary ? contents : contents.toString("utf8"));
        }, "fetchReadFileCallback"));
      return fetch.xhr(filename, options, callback);
    }
    __name(fetch, "fetch");
    fetch.xhr = /* @__PURE__ */ __name(function fetch_xhr(filename, options, callback) {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = /* @__PURE__ */ __name(function fetchOnReadyStateChange() {
        if (xhr.readyState !== 4)
          return void 0;
        if (xhr.status !== 0 && xhr.status !== 200)
          return callback(Error("status " + xhr.status));
        if (options.binary) {
          var buffer = xhr.response;
          if (!buffer) {
            buffer = [];
            for (var i = 0; i < xhr.responseText.length; ++i)
              buffer.push(xhr.responseText.charCodeAt(i) & 255);
          }
          return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);
        }
        return callback(null, xhr.responseText);
      }, "fetchOnReadyStateChange");
      if (options.binary) {
        if ("overrideMimeType" in xhr)
          xhr.overrideMimeType("text/plain; charset=x-user-defined");
        xhr.responseType = "arraybuffer";
      }
      xhr.open("GET", filename);
      xhr.send();
    }, "fetch_xhr");
  }
});

// node_modules/@protobufjs/path/index.js
var require_path = __commonJS({
  "node_modules/@protobufjs/path/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var path11 = exports;
    var isAbsolute3 = (
      /**
       * Tests if the specified path is absolute.
       * @param {string} path Path to test
       * @returns {boolean} `true` if path is absolute
       */
      path11.isAbsolute = /* @__PURE__ */ __name(function isAbsolute4(path12) {
        return /^(?:\/|\w+:)/.test(path12);
      }, "isAbsolute")
    );
    var normalize2 = (
      /**
       * Normalizes the specified path.
       * @param {string} path Path to normalize
       * @returns {string} Normalized path
       */
      path11.normalize = /* @__PURE__ */ __name(function normalize3(path12) {
        path12 = path12.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
        var parts = path12.split("/"), absolute = isAbsolute3(path12), prefix = "";
        if (absolute)
          prefix = parts.shift() + "/";
        for (var i = 0; i < parts.length; ) {
          if (parts[i] === "..") {
            if (i > 0 && parts[i - 1] !== "..")
              parts.splice(--i, 2);
            else if (absolute)
              parts.splice(i, 1);
            else
              ++i;
          } else if (parts[i] === ".")
            parts.splice(i, 1);
          else
            ++i;
        }
        return prefix + parts.join("/");
      }, "normalize")
    );
    path11.resolve = /* @__PURE__ */ __name(function resolve2(originPath, includePath, alreadyNormalized) {
      if (!alreadyNormalized)
        includePath = normalize2(includePath);
      if (isAbsolute3(includePath))
        return includePath;
      if (!alreadyNormalized)
        originPath = normalize2(originPath);
      return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize2(originPath + "/" + includePath) : includePath;
    }, "resolve");
  }
});

// node_modules/protobufjs/src/util/patterns.js
var require_patterns = __commonJS({
  "node_modules/protobufjs/src/util/patterns.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var patterns = exports;
    patterns.numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;
    patterns.typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;
    patterns.reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/;
  }
});

// node_modules/protobufjs/src/util/fs.js
var require_fs2 = __commonJS({
  "node_modules/protobufjs/src/util/fs.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var fs9 = null;
    try {
      fs9 = __require(
        /* webpackIgnore: true */
        "fs"
      );
      if (!fs9 || !fs9.readFile || !fs9.readFileSync)
        fs9 = null;
    } catch (e) {
    }
    module.exports = fs9;
  }
});

// node_modules/protobufjs/src/namespace.js
var require_namespace = __commonJS({
  "node_modules/protobufjs/src/namespace.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Namespace;
    var ReflectionObject = require_object();
    ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";
    var Field = require_field();
    var util = require_util();
    var OneOf = require_oneof();
    var Type;
    var Service;
    var Enum;
    Namespace.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json, depth) {
      depth = util.checkDepth(depth);
      return new Namespace(name, json.options).addJSON(json.nested, depth);
    }, "fromJSON");
    function arrayToJSON(array, toJSONOptions) {
      if (!(array && array.length))
        return void 0;
      var obj = {};
      for (var i = 0; i < array.length; ++i)
        obj[array[i].name] = array[i].toJSON(toJSONOptions);
      return obj;
    }
    __name(arrayToJSON, "arrayToJSON");
    Namespace.arrayToJSON = arrayToJSON;
    Namespace.isReservedId = /* @__PURE__ */ __name(function isReservedId(reserved, id) {
      if (reserved) {
        for (var i = 0; i < reserved.length; ++i)
          if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id)
            return true;
      }
      return false;
    }, "isReservedId");
    Namespace.isReservedName = /* @__PURE__ */ __name(function isReservedName(reserved, name) {
      if (reserved) {
        for (var i = 0; i < reserved.length; ++i)
          if (reserved[i] === name)
            return true;
      }
      return false;
    }, "isReservedName");
    function Namespace(name, options) {
      ReflectionObject.call(this, name, options);
      this.nested = void 0;
      this._nestedArray = null;
      this._lookupCache = /* @__PURE__ */ Object.create(null);
      this._needsRecursiveFeatureResolution = true;
      this._needsRecursiveResolve = true;
    }
    __name(Namespace, "Namespace");
    function clearCache(namespace) {
      namespace._nestedArray = null;
      namespace._lookupCache = /* @__PURE__ */ Object.create(null);
      var parent = namespace;
      while (parent = parent.parent) {
        parent._lookupCache = /* @__PURE__ */ Object.create(null);
      }
      return namespace;
    }
    __name(clearCache, "clearCache");
    Object.defineProperty(Namespace.prototype, "nestedArray", {
      get: /* @__PURE__ */ __name(function() {
        return this._nestedArray || (this._nestedArray = util.toArray(this.nested));
      }, "get")
    });
    Namespace.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      return util.toObject([
        "options",
        this.options,
        "nested",
        arrayToJSON(this.nestedArray, toJSONOptions)
      ]);
    }, "toJSON");
    Namespace.prototype.addJSON = /* @__PURE__ */ __name(function addJSON(nestedJson, depth) {
      depth = util.checkDepth(depth);
      var ns = this;
      if (nestedJson) {
        for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {
          nested = nestedJson[names[i]];
          ns.add(
            // most to least likely
            (nested.fields !== void 0 ? Type.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : nested.id !== void 0 ? Field.fromJSON : Namespace.fromJSON)(names[i], nested, depth + 1)
          );
        }
      }
      return this;
    }, "addJSON");
    Namespace.prototype.get = /* @__PURE__ */ __name(function get(name) {
      return this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) ? this.nested[name] : null;
    }, "get");
    Namespace.prototype.getEnum = /* @__PURE__ */ __name(function getEnum(name) {
      if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) && this.nested[name] instanceof Enum)
        return this.nested[name].values;
      throw Error("no such enum: " + name);
    }, "getEnum");
    Namespace.prototype.add = /* @__PURE__ */ __name(function add(object) {
      if (!(object instanceof Field && object.extend !== void 0 || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))
        throw TypeError("object must be a valid nested object");
      if (object.name === "__proto__")
        return this;
      if (!this.nested)
        this.nested = {};
      else {
        var prev = this.get(object.name);
        if (prev) {
          if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {
            var nested = prev.nestedArray;
            for (var i = 0; i < nested.length; ++i)
              object.add(nested[i]);
            this.remove(prev);
            if (!this.nested)
              this.nested = {};
            object.setOptions(prev.options, true);
          } else
            throw Error("duplicate name '" + object.name + "' in " + this);
        }
      }
      this.nested[object.name] = object;
      if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) {
        if (!object._edition) {
          object._edition = object._defaultEdition;
        }
      }
      this._needsRecursiveFeatureResolution = true;
      this._needsRecursiveResolve = true;
      var parent = this;
      while (parent = parent.parent) {
        parent._needsRecursiveFeatureResolution = true;
        parent._needsRecursiveResolve = true;
      }
      object.onAdd(this);
      return clearCache(this);
    }, "add");
    Namespace.prototype.remove = /* @__PURE__ */ __name(function remove(object) {
      if (!(object instanceof ReflectionObject))
        throw TypeError("object must be a ReflectionObject");
      if (object.parent !== this)
        throw Error(object + " is not a member of " + this);
      delete this.nested[object.name];
      if (!Object.keys(this.nested).length)
        this.nested = void 0;
      object.onRemove(this);
      return clearCache(this);
    }, "remove");
    Namespace.prototype.define = /* @__PURE__ */ __name(function define(path11, json) {
      if (util.isString(path11))
        path11 = path11.split(".");
      else if (!Array.isArray(path11))
        throw TypeError("illegal path");
      if (path11 && path11.length && path11[0] === "")
        throw Error("path must be relative");
      if (path11.length > util.recursionLimit)
        throw Error("max depth exceeded");
      var ptr = this;
      while (path11.length > 0) {
        var part = path11.shift();
        if (ptr.nested && ptr.nested[part]) {
          ptr = ptr.nested[part];
          if (!(ptr instanceof Namespace))
            throw Error("path conflicts with non-namespace objects");
        } else
          ptr.add(ptr = new Namespace(part));
      }
      if (json)
        ptr.addJSON(json);
      return ptr;
    }, "define");
    Namespace.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      this._resolveFeaturesRecursive(this._edition);
      var nested = this.nestedArray, i = 0;
      this.resolve();
      while (i < nested.length)
        if (nested[i] instanceof Namespace)
          nested[i++].resolveAll();
        else
          nested[i++].resolve();
      this._needsRecursiveResolve = false;
      return this;
    }, "resolveAll");
    Namespace.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      if (!this._needsRecursiveFeatureResolution) return this;
      this._needsRecursiveFeatureResolution = false;
      edition = this._edition || edition;
      ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition);
      this.nestedArray.forEach((nested) => {
        nested._resolveFeaturesRecursive(edition);
      });
      return this;
    }, "_resolveFeaturesRecursive");
    Namespace.prototype.lookup = /* @__PURE__ */ __name(function lookup(path11, filterTypes, parentAlreadyChecked) {
      if (typeof filterTypes === "boolean") {
        parentAlreadyChecked = filterTypes;
        filterTypes = void 0;
      } else if (filterTypes && !Array.isArray(filterTypes))
        filterTypes = [filterTypes];
      if (util.isString(path11) && path11.length) {
        if (path11 === ".")
          return this.root;
        path11 = path11.split(".");
      } else if (!path11.length)
        return this;
      var flatPath = path11.join(".");
      if (path11[0] === "")
        return this.root.lookup(path11.slice(1), filterTypes);
      var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath];
      if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
        return found;
      }
      found = this._lookupImpl(path11, flatPath);
      if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
        return found;
      }
      if (parentAlreadyChecked)
        return null;
      var current = this;
      while (current.parent) {
        found = current.parent._lookupImpl(path11, flatPath);
        if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
          return found;
        }
        current = current.parent;
      }
      return null;
    }, "lookup");
    Namespace.prototype._lookupImpl = /* @__PURE__ */ __name(function lookup(path11, flatPath) {
      if (Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {
        return this._lookupCache[flatPath];
      }
      var found = this.get(path11[0]);
      var exact = null;
      if (found) {
        if (path11.length === 1) {
          exact = found;
        } else if (found instanceof Namespace) {
          path11 = path11.slice(1);
          exact = found._lookupImpl(path11, path11.join("."));
        }
      } else {
        for (var i = 0; i < this.nestedArray.length; ++i)
          if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path11, flatPath))) {
            exact = found;
            break;
          }
      }
      this._lookupCache[flatPath] = exact;
      return exact;
    }, "lookup");
    Namespace.prototype.lookupType = /* @__PURE__ */ __name(function lookupType(path11) {
      var found = this.lookup(path11, [Type]);
      if (!found)
        throw Error("no such type: " + path11);
      return found;
    }, "lookupType");
    Namespace.prototype.lookupEnum = /* @__PURE__ */ __name(function lookupEnum(path11) {
      var found = this.lookup(path11, [Enum]);
      if (!found)
        throw Error("no such Enum '" + path11 + "' in " + this);
      return found;
    }, "lookupEnum");
    Namespace.prototype.lookupTypeOrEnum = /* @__PURE__ */ __name(function lookupTypeOrEnum(path11) {
      var found = this.lookup(path11, [Type, Enum]);
      if (!found)
        throw Error("no such Type or Enum '" + path11 + "' in " + this);
      return found;
    }, "lookupTypeOrEnum");
    Namespace.prototype.lookupService = /* @__PURE__ */ __name(function lookupService(path11) {
      var found = this.lookup(path11, [Service]);
      if (!found)
        throw Error("no such Service '" + path11 + "' in " + this);
      return found;
    }, "lookupService");
    Namespace._configure = function(Type_, Service_, Enum_) {
      Type = Type_;
      Service = Service_;
      Enum = Enum_;
    };
  }
});

// node_modules/protobufjs/src/mapfield.js
var require_mapfield = __commonJS({
  "node_modules/protobufjs/src/mapfield.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = MapField;
    var Field = require_field();
    ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
    var types2 = require_types();
    var util = require_util();
    function MapField(name, id, keyType, type, options, comment) {
      Field.call(this, name, id, type, void 0, void 0, options, comment);
      if (!util.isString(keyType))
        throw TypeError("keyType must be a string");
      this.keyType = keyType;
      this.resolvedKeyType = null;
      this.map = true;
    }
    __name(MapField, "MapField");
    MapField.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json) {
      return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);
    }, "fromJSON");
    MapField.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util.toObject([
        "keyType",
        this.keyType,
        "type",
        this.type,
        "id",
        this.id,
        "extend",
        this.extend,
        "options",
        this.options,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    MapField.prototype.resolve = /* @__PURE__ */ __name(function resolve2() {
      if (this.resolved)
        return this;
      if (types2.mapKey[this.keyType] === void 0)
        throw Error("invalid key type: " + this.keyType);
      return Field.prototype.resolve.call(this);
    }, "resolve");
    MapField.d = /* @__PURE__ */ __name(function decorateMapField(fieldId, fieldKeyType, fieldValueType) {
      if (typeof fieldValueType === "function")
        fieldValueType = util.decorateType(fieldValueType).name;
      else if (fieldValueType && typeof fieldValueType === "object")
        fieldValueType = util.decorateEnum(fieldValueType).name;
      return /* @__PURE__ */ __name(function mapFieldDecorator(prototype, fieldName) {
        util.decorateType(prototype.constructor).add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));
      }, "mapFieldDecorator");
    }, "decorateMapField");
  }
});

// node_modules/protobufjs/src/method.js
var require_method = __commonJS({
  "node_modules/protobufjs/src/method.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Method;
    var ReflectionObject = require_object();
    ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";
    var util = require_util();
    function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {
      if (util.isObject(requestStream)) {
        options = requestStream;
        requestStream = responseStream = void 0;
      } else if (util.isObject(responseStream)) {
        options = responseStream;
        responseStream = void 0;
      }
      if (!(type === void 0 || util.isString(type)))
        throw TypeError("type must be a string");
      if (!util.isString(requestType))
        throw TypeError("requestType must be a string");
      if (!util.isString(responseType))
        throw TypeError("responseType must be a string");
      ReflectionObject.call(this, name, options);
      this.type = type || "rpc";
      this.requestType = requestType;
      this.requestStream = requestStream ? true : void 0;
      this.responseType = responseType;
      this.responseStream = responseStream ? true : void 0;
      this.resolvedRequestType = null;
      this.resolvedResponseType = null;
      this.comment = comment;
      this.parsedOptions = parsedOptions;
    }
    __name(Method, "Method");
    Method.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json) {
      return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);
    }, "fromJSON");
    Method.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util.toObject([
        "type",
        this.type !== "rpc" && /* istanbul ignore next */
        this.type || void 0,
        "requestType",
        this.requestType,
        "requestStream",
        this.requestStream,
        "responseType",
        this.responseType,
        "responseStream",
        this.responseStream,
        "options",
        this.options,
        "comment",
        keepComments ? this.comment : void 0,
        "parsedOptions",
        this.parsedOptions
      ]);
    }, "toJSON");
    Method.prototype.resolve = /* @__PURE__ */ __name(function resolve2() {
      if (this.resolved)
        return this;
      this.resolvedRequestType = this.parent.lookupType(this.requestType);
      this.resolvedResponseType = this.parent.lookupType(this.responseType);
      return ReflectionObject.prototype.resolve.call(this);
    }, "resolve");
  }
});

// node_modules/protobufjs/src/service.js
var require_service = __commonJS({
  "node_modules/protobufjs/src/service.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Service;
    var Namespace = require_namespace();
    ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";
    var Method = require_method();
    var util = require_util();
    var rpc = require_rpc();
    function Service(name, options) {
      Namespace.call(this, name, options);
      this.methods = {};
      this._methodsArray = null;
    }
    __name(Service, "Service");
    Service.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json, depth) {
      depth = util.checkDepth(depth);
      var service = new Service(name, json.options);
      if (json.methods)
        for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)
          service.add(Method.fromJSON(names[i], json.methods[names[i]]));
      if (json.nested)
        service.addJSON(json.nested, depth);
      if (json.edition)
        service._edition = json.edition;
      service.comment = json.comment;
      service._defaultEdition = "proto3";
      return service;
    }, "fromJSON");
    Service.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util.toObject([
        "edition",
        this._editionToJSON(),
        "options",
        inherited && inherited.options || void 0,
        "methods",
        Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */
        {},
        "nested",
        inherited && inherited.nested || void 0,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    Object.defineProperty(Service.prototype, "methodsArray", {
      get: /* @__PURE__ */ __name(function() {
        return this._methodsArray || (this._methodsArray = util.toArray(this.methods));
      }, "get")
    });
    function clearCache(service) {
      service._methodsArray = null;
      return service;
    }
    __name(clearCache, "clearCache");
    Service.prototype.get = /* @__PURE__ */ __name(function get(name) {
      return Object.prototype.hasOwnProperty.call(this.methods, name) ? this.methods[name] : Namespace.prototype.get.call(this, name);
    }, "get");
    Service.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      Namespace.prototype.resolve.call(this);
      var methods = this.methodsArray;
      for (var i = 0; i < methods.length; ++i)
        methods[i].resolve();
      return this;
    }, "resolveAll");
    Service.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      if (!this._needsRecursiveFeatureResolution) return this;
      edition = this._edition || edition;
      Namespace.prototype._resolveFeaturesRecursive.call(this, edition);
      this.methodsArray.forEach((method) => {
        method._resolveFeaturesRecursive(edition);
      });
      return this;
    }, "_resolveFeaturesRecursive");
    Service.prototype.add = /* @__PURE__ */ __name(function add(object) {
      if (this.get(object.name))
        throw Error("duplicate name '" + object.name + "' in " + this);
      if (object instanceof Method) {
        if (object.name === "__proto__")
          return this;
        this.methods[object.name] = object;
        object.parent = this;
        return clearCache(this);
      }
      return Namespace.prototype.add.call(this, object);
    }, "add");
    Service.prototype.remove = /* @__PURE__ */ __name(function remove(object) {
      if (object instanceof Method) {
        if (this.methods[object.name] !== object)
          throw Error(object + " is not a member of " + this);
        delete this.methods[object.name];
        object.parent = null;
        return clearCache(this);
      }
      return Namespace.prototype.remove.call(this, object);
    }, "remove");
    Service.prototype.create = /* @__PURE__ */ __name(function create(rpcImpl, requestDelimited, responseDelimited) {
      var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
      for (var i = 0, method; i < /* initializes */
      this.methodsArray.length; ++i) {
        var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");
        rpcService[methodName] = /* @__PURE__ */ function(method2, requestType, responseType) {
          return /* @__PURE__ */ __name(function rpcMethod(request4, callback) {
            return rpc.Service.prototype.rpcCall.call(this, method2, requestType, responseType, request4, callback);
          }, "rpcMethod");
        }(method, method.resolvedRequestType.ctor, method.resolvedResponseType.ctor);
      }
      return rpcService;
    }, "create");
  }
});

// node_modules/protobufjs/src/message.js
var require_message = __commonJS({
  "node_modules/protobufjs/src/message.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Message;
    var util = require_minimal();
    function Message(properties) {
      if (properties)
        for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
          var key = keys[i];
          if (key === "__proto__")
            continue;
          this[key] = properties[key];
        }
    }
    __name(Message, "Message");
    Message.create = /* @__PURE__ */ __name(function create(properties) {
      return this.$type.create(properties);
    }, "create");
    Message.encode = /* @__PURE__ */ __name(function encode(message, writer) {
      return this.$type.encode(message, writer);
    }, "encode");
    Message.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
      return this.$type.encodeDelimited(message, writer);
    }, "encodeDelimited");
    Message.decode = /* @__PURE__ */ __name(function decode(reader) {
      return this.$type.decode(reader);
    }, "decode");
    Message.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
      return this.$type.decodeDelimited(reader);
    }, "decodeDelimited");
    Message.verify = /* @__PURE__ */ __name(function verify(message) {
      return this.$type.verify(message);
    }, "verify");
    Message.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
      return this.$type.fromObject(object);
    }, "fromObject");
    Message.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
      return this.$type.toObject(message, options);
    }, "toObject");
    Message.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
      return this.$type.toObject(this, util.toJSONOptions);
    }, "toJSON");
  }
});

// node_modules/protobufjs/src/decoder.js
var require_decoder = __commonJS({
  "node_modules/protobufjs/src/decoder.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = decoder;
    var Enum = require_enum();
    var types2 = require_types();
    var util = require_util();
    function missing(field) {
      return "missing required '" + field.name + "'";
    }
    __name(missing, "missing");
    function decoder(mtype) {
      var gen = util.codegen(["r", "l", "e", "n"], mtype.name + "$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field2) {
        return field2.map;
      }).length ? ",k,value" : ""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){");
      var i = 0;
      for (; i < /* initializes */
      mtype.fieldsArray.length; ++i) {
        var field = mtype._fieldsArray[i].resolve(), type = field.resolvedType instanceof Enum ? "int32" : field.type, ref = "m" + util.safeProp(field.name);
        gen("case %i: {", field.id);
        if (field.map) {
          gen("if(%s===util.emptyObject)", ref)("%s={}", ref)("var c2 = r.uint32()+r.pos");
          if (types2.defaults[field.keyType] !== void 0) gen("k=%j", types2.defaults[field.keyType]);
          else gen("k=null");
          if (types2.defaults[type] !== void 0) gen("value=%j", types2.defaults[type]);
          else gen("value=null");
          gen("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break", field.keyType)("case 2:");
          if (types2.basic[type] === void 0) gen("value=types[%i].decode(r,r.uint32(),undefined,n+1)", i);
          else gen("value=r.%s()", type);
          gen("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}");
          if (types2.long[field.keyType] !== void 0) gen('%s[typeof k==="object"?util.longToHash(k):k]=value', ref);
          else {
            if (field.keyType === "string") gen('if(k==="__proto__")')("util.makeProp(%s,k)", ref);
            gen("%s[k]=value", ref);
          }
        } else if (field.repeated) {
          gen("if(!(%s&&%s.length))", ref, ref)("%s=[]", ref);
          if (types2.packed[type] !== void 0) gen("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())", ref, type)("}else");
          if (types2.basic[type] === void 0) gen(field.delimited ? "%s.push(types[%i].decode(r,undefined,((t&~7)|4),n+1))" : "%s.push(types[%i].decode(r,r.uint32(),undefined,n+1))", ref, i);
          else gen("%s.push(r.%s())", ref, type);
        } else if (types2.basic[type] === void 0) gen(field.delimited ? "%s=types[%i].decode(r,undefined,((t&~7)|4),n+1)" : "%s=types[%i].decode(r,r.uint32(),undefined,n+1)", ref, i);
        else gen("%s=r.%s()", ref, type);
        gen("break")("}");
      }
      gen("default:")("r.skipType(t&7,n)")("break")("}")("}");
      for (i = 0; i < mtype._fieldsArray.length; ++i) {
        var rfield = mtype._fieldsArray[i];
        if (rfield.required) gen("if(!Object.hasOwnProperty.call(m,%j))", rfield.name)("throw util.ProtocolError(%j,{instance:m})", missing(rfield));
      }
      return gen("return m");
    }
    __name(decoder, "decoder");
  }
});

// node_modules/protobufjs/src/verifier.js
var require_verifier = __commonJS({
  "node_modules/protobufjs/src/verifier.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = verifier;
    var Enum = require_enum();
    var util = require_util();
    function invalid(field, expected) {
      return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:" + field.keyType + "}" : "") + " expected";
    }
    __name(invalid, "invalid");
    function genVerifyValue(gen, field, fieldIndex, ref) {
      if (field.resolvedType) {
        if (field.resolvedType instanceof Enum) {
          gen("switch(%s){", ref)("default:")("return%j", invalid(field, "enum value"));
          for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen("case %i:", field.resolvedType.values[keys[j]]);
          gen("break")("}");
        } else {
          gen("{")("var e=types[%i].verify(%s,n+1);", fieldIndex, ref)("if(e)")("return%j+e", field.name + ".")("}");
        }
      } else {
        switch (field.type) {
          case "int32":
          case "uint32":
          case "sint32":
          case "fixed32":
          case "sfixed32":
            gen("if(!util.isInteger(%s))", ref)("return%j", invalid(field, "integer"));
            break;
          case "int64":
          case "uint64":
          case "sint64":
          case "fixed64":
          case "sfixed64":
            gen("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)("return%j", invalid(field, "integer|Long"));
            break;
          case "float":
          case "double":
            gen('if(typeof %s!=="number")', ref)("return%j", invalid(field, "number"));
            break;
          case "bool":
            gen('if(typeof %s!=="boolean")', ref)("return%j", invalid(field, "boolean"));
            break;
          case "string":
            gen("if(!util.isString(%s))", ref)("return%j", invalid(field, "string"));
            break;
          case "bytes":
            gen('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))', ref, ref, ref)("return%j", invalid(field, "buffer"));
            break;
        }
      }
      return gen;
    }
    __name(genVerifyValue, "genVerifyValue");
    function genVerifyKey(gen, field, ref) {
      switch (field.keyType) {
        case "int32":
        case "uint32":
        case "sint32":
        case "fixed32":
        case "sfixed32":
          gen("if(!util.key32Re.test(%s))", ref)("return%j", invalid(field, "integer key"));
          break;
        case "int64":
        case "uint64":
        case "sint64":
        case "fixed64":
        case "sfixed64":
          gen("if(!util.key64Re.test(%s))", ref)("return%j", invalid(field, "integer|Long key"));
          break;
        case "bool":
          gen("if(!util.key2Re.test(%s))", ref)("return%j", invalid(field, "boolean key"));
          break;
      }
      return gen;
    }
    __name(genVerifyKey, "genVerifyKey");
    function verifier(mtype) {
      var gen = util.codegen(["m", "n"], mtype.name + "$verify")('if(typeof m!=="object"||m===null)')("return%j", "object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")("return%j", "maximum nesting depth exceeded");
      var oneofs = mtype.oneofsArray, seenFirstField = {};
      if (oneofs.length) gen("var p={}");
      for (var i = 0; i < /* initializes */
      mtype.fieldsArray.length; ++i) {
        var field = mtype._fieldsArray[i].resolve(), ref = "m" + util.safeProp(field.name);
        if (field.optional) gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name);
        if (field.map) {
          gen("if(!util.isObject(%s))", ref)("return%j", invalid(field, "object"))("var k=Object.keys(%s)", ref)("for(var i=0;i<k.length;++i){");
          genVerifyKey(gen, field, "k[i]");
          genVerifyValue(gen, field, i, ref + "[k[i]]")("}");
        } else if (field.repeated) {
          gen("if(!Array.isArray(%s))", ref)("return%j", invalid(field, "array"))("for(var i=0;i<%s.length;++i){", ref);
          genVerifyValue(gen, field, i, ref + "[i]")("}");
        } else {
          if (field.partOf) {
            var oneofProp = util.safeProp(field.partOf.name);
            if (seenFirstField[field.partOf.name] === 1) gen("if(p%s===1)", oneofProp)("return%j", field.partOf.name + ": multiple values");
            seenFirstField[field.partOf.name] = 1;
            gen("p%s=1", oneofProp);
          }
          genVerifyValue(gen, field, i, ref);
        }
        if (field.optional) gen("}");
      }
      return gen("return null");
    }
    __name(verifier, "verifier");
  }
});

// node_modules/protobufjs/src/converter.js
var require_converter = __commonJS({
  "node_modules/protobufjs/src/converter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var converter = exports;
    var Enum = require_enum();
    var util = require_util();
    function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
      var defaultAlreadyEmitted = false;
      if (field.resolvedType) {
        if (field.resolvedType instanceof Enum) {
          gen("switch(d%s){", prop);
          for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
            if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) {
              gen("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}', prop, prop, prop);
              if (!field.repeated) gen("break");
              defaultAlreadyEmitted = true;
            }
            gen("case%j:", keys[i])("case %i:", values[keys[i]])("m%s=%j", prop, values[keys[i]])("break");
          }
          gen("}");
        } else gen("if(!util.isObject(d%s))", prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s=types[%i].fromObject(d%s,n+1)", prop, fieldIndex, prop);
      } else {
        var isUnsigned = false;
        switch (field.type) {
          case "double":
          case "float":
            gen("m%s=Number(d%s)", prop, prop);
            break;
          case "uint32":
          case "fixed32":
            gen("m%s=d%s>>>0", prop, prop);
            break;
          case "int32":
          case "sint32":
          case "sfixed32":
            gen("m%s=d%s|0", prop, prop);
            break;
          case "uint64":
          case "fixed64":
            isUnsigned = true;
          // eslint-disable-next-line no-fallthrough
          case "int64":
          case "sint64":
          case "sfixed64":
            gen("if(util.Long)")("m%s=util.Long.fromValue(d%s,%j)", prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)("m%s=parseInt(d%s,10)", prop, prop)('else if(typeof d%s==="number")', prop)("m%s=d%s", prop, prop)('else if(typeof d%s==="object")', prop)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");
            break;
          case "bytes":
            gen('if(typeof d%s==="string")', prop)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)("else if(d%s.length >= 0)", prop)("m%s=d%s", prop, prop);
            break;
          case "string":
            gen("m%s=String(d%s)", prop, prop);
            break;
          case "bool":
            gen("m%s=Boolean(d%s)", prop, prop);
            break;
        }
      }
      return gen;
    }
    __name(genValuePartial_fromObject, "genValuePartial_fromObject");
    converter.fromObject = /* @__PURE__ */ __name(function fromObject(mtype) {
      var fields = mtype.fieldsArray;
      var gen = util.codegen(["d", "n"], mtype.name + "$fromObject")("if(d instanceof this.ctor)")("return d");
      if (!fields.length) return gen("return new this.ctor");
      gen("if(!util.isObject(d))")("throw TypeError(%j)", mtype.fullName + ": object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")');
      gen("var m=new this.ctor");
      for (var i = 0; i < fields.length; ++i) {
        var field = fields[i].resolve(), prop = util.safeProp(field.name);
        if (field.map) {
          gen("if(d%s){", prop)("if(!util.isObject(d%s))", prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s={}", prop)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);
          gen('if(ks[i]==="__proto__")')("util.makeProp(m%s,ks[i])", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i,
            prop + "[ks[i]]"
          )("}")("}");
        } else if (field.repeated) {
          gen("if(d%s){", prop)("if(!Array.isArray(d%s))", prop)("throw TypeError(%j)", field.fullName + ": array expected")("m%s=[]", prop)("for(var i=0;i<d%s.length;++i){", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i,
            prop + "[i]"
          )("}")("}");
        } else {
          if (!(field.resolvedType instanceof Enum)) gen("if(d%s!=null){", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i,
            prop
          );
          if (!(field.resolvedType instanceof Enum)) gen("}");
        }
      }
      return gen("return m");
    }, "fromObject");
    function genValuePartial_toObject(gen, field, fieldIndex, prop) {
      if (field.resolvedType) {
        if (field.resolvedType instanceof Enum) gen("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s", prop, fieldIndex, prop, prop, fieldIndex, prop, prop);
        else gen("d%s=types[%i].toObject(m%s,o,q+1)", prop, fieldIndex, prop);
      } else {
        var isUnsigned = false;
        switch (field.type) {
          case "double":
          case "float":
            gen("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop);
            break;
          case "uint64":
          case "fixed64":
            isUnsigned = true;
          // eslint-disable-next-line no-fallthrough
          case "int64":
          case "sint64":
          case "sfixed64":
            gen('if(typeof BigInt!=="undefined"&&o.longs===BigInt)')('d%s=typeof m%s==="number"?BigInt(m%s):util.Long.fromBits(m%s.low>>>0,m%s.high>>>0,%j).toBigInt()', prop, prop, prop, prop, prop, isUnsigned)('else if(typeof m%s==="number")', prop)("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true" : "", prop);
            break;
          case "bytes":
            gen("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop);
            break;
          default:
            gen("d%s=m%s", prop, prop);
            break;
        }
      }
      return gen;
    }
    __name(genValuePartial_toObject, "genValuePartial_toObject");
    converter.toObject = /* @__PURE__ */ __name(function toObject(mtype) {
      var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);
      if (!fields.length)
        return util.codegen()("return {}");
      var gen = util.codegen(["m", "o", "q"], mtype.name + "$toObject")("if(!o)")("o={}")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")')("var d={}");
      var repeatedFields = [], mapFields = [], normalFields = [], i = 0;
      for (; i < fields.length; ++i)
        if (!fields[i].partOf)
          (fields[i].resolve().repeated ? repeatedFields : fields[i].map ? mapFields : normalFields).push(fields[i]);
      if (repeatedFields.length) {
        gen("if(o.arrays||o.defaults){");
        for (i = 0; i < repeatedFields.length; ++i) gen("d%s=[]", util.safeProp(repeatedFields[i].name));
        gen("}");
      }
      if (mapFields.length) {
        gen("if(o.objects||o.defaults){");
        for (i = 0; i < mapFields.length; ++i) gen("d%s={}", util.safeProp(mapFields[i].name));
        gen("}");
      }
      if (normalFields.length) {
        gen("if(o.defaults){");
        for (i = 0; i < normalFields.length; ++i) {
          var field = normalFields[i], prop = util.safeProp(field.name);
          if (field.resolvedType instanceof Enum) gen("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);
          else if (field.long) gen("if(util.Long){")("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)('d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!=="undefined"&&o.longs===BigInt?n.toBigInt():n', prop)("}else")('d%s=o.longs===String?%j:typeof BigInt!=="undefined"&&o.longs===BigInt?BigInt(%j):%i', prop, field.typeDefault.toString(), field.typeDefault.toString(), field.typeDefault.toNumber());
          else if (field.bytes) {
            var arrayDefault = Array.prototype.slice.call(field.typeDefault);
            gen("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))("else{")("d%s=%j", prop, arrayDefault)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)("}");
          } else gen("d%s=%j", prop, field.typeDefault);
        }
        gen("}");
      }
      var hasKs2 = false;
      for (i = 0; i < fields.length; ++i) {
        var field = fields[i], index = mtype._fieldsArray.indexOf(field), prop = util.safeProp(field.name);
        if (field.map) {
          if (!hasKs2) {
            hasKs2 = true;
            gen("var ks2");
          }
          gen("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)("d%s={}", prop)("for(var j=0;j<ks2.length;++j){");
          gen('if(ks2[j]==="__proto__")')("util.makeProp(d%s,ks2[j])", prop);
          genValuePartial_toObject(
            gen,
            field,
            /* sorted */
            index,
            prop + "[ks2[j]]"
          )("}");
        } else if (field.repeated) {
          gen("if(m%s&&m%s.length){", prop, prop)("d%s=[]", prop)("for(var j=0;j<m%s.length;++j){", prop);
          genValuePartial_toObject(
            gen,
            field,
            /* sorted */
            index,
            prop + "[j]"
          )("}");
        } else {
          gen("if(m%s!=null&&Object.hasOwnProperty.call(m,%j)){", prop, field.name);
          genValuePartial_toObject(
            gen,
            field,
            /* sorted */
            index,
            prop
          );
          if (field.partOf) gen("if(o.oneofs)")("d%s=%j", util.safeProp(field.partOf.name), field.name);
        }
        gen("}");
      }
      return gen("return d");
    }, "toObject");
  }
});

// node_modules/protobufjs/src/wrappers.js
var require_wrappers = __commonJS({
  "node_modules/protobufjs/src/wrappers.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var wrappers = exports;
    var Message = require_message();
    var util = require_minimal();
    wrappers[".google.protobuf.Any"] = {
      fromObject: /* @__PURE__ */ __name(function(object, depth) {
        if (object && object["@type"]) {
          var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1);
          var type = this.lookup(name);
          if (type) {
            var type_url = object["@type"].charAt(0) === "." ? object["@type"].slice(1) : object["@type"];
            if (type_url.indexOf("/") === -1) {
              type_url = "/" + type_url;
            }
            return this.create({
              type_url,
              value: type.encode(type.fromObject(object, depth === void 0 ? 1 : depth + 1)).finish()
            });
          }
        }
        return this.fromObject(object, depth);
      }, "fromObject"),
      toObject: /* @__PURE__ */ __name(function(message, options, depth) {
        if (depth === void 0)
          depth = 0;
        if (depth > util.recursionLimit)
          throw Error("max depth exceeded");
        var googleApi = "type.googleapis.com/";
        var prefix = "";
        var name = "";
        if (options && options.json && message.type_url && message.value) {
          name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
          prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1);
          var type = this.lookup(name);
          if (type)
            message = type.decode(message.value, void 0, void 0, depth + 1);
        }
        if (!(message instanceof this.ctor) && message instanceof Message) {
          var object = message.$type.toObject(message, options, depth + 1);
          var messageName = message.$type.fullName[0] === "." ? message.$type.fullName.slice(1) : message.$type.fullName;
          if (prefix === "") {
            prefix = googleApi;
          }
          name = prefix + messageName;
          object["@type"] = name;
          return object;
        }
        return this.toObject(message, options, depth);
      }, "toObject")
    };
  }
});

// node_modules/protobufjs/src/type.js
var require_type = __commonJS({
  "node_modules/protobufjs/src/type.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Type;
    var Namespace = require_namespace();
    ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type";
    var Enum = require_enum();
    var OneOf = require_oneof();
    var Field = require_field();
    var MapField = require_mapfield();
    var Service = require_service();
    var Message = require_message();
    var Reader = require_reader();
    var Writer = require_writer();
    var util = require_util();
    var encoder = require_encoder();
    var decoder = require_decoder();
    var verifier = require_verifier();
    var converter = require_converter();
    var wrappers = require_wrappers();
    function Type(name, options) {
      name = name.replace(/\W/g, "");
      Namespace.call(this, name, options);
      this.fields = {};
      this.oneofs = void 0;
      this.extensions = void 0;
      this.reserved = void 0;
      this.group = void 0;
      this._fieldsById = null;
      this._fieldsArray = null;
      this._oneofsArray = null;
      this._ctor = null;
    }
    __name(Type, "Type");
    Object.defineProperties(Type.prototype, {
      /**
       * Message fields by id.
       * @name Type#fieldsById
       * @type {Object.<number,Field>}
       * @readonly
       */
      fieldsById: {
        get: /* @__PURE__ */ __name(function() {
          if (this._fieldsById)
            return this._fieldsById;
          this._fieldsById = {};
          for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {
            var field = this.fields[names[i]], id = field.id;
            if (this._fieldsById[id])
              throw Error("duplicate id " + id + " in " + this);
            this._fieldsById[id] = field;
          }
          return this._fieldsById;
        }, "get")
      },
      /**
       * Fields of this message as an array for iteration.
       * @name Type#fieldsArray
       * @type {Field[]}
       * @readonly
       */
      fieldsArray: {
        get: /* @__PURE__ */ __name(function() {
          return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));
        }, "get")
      },
      /**
       * Oneofs of this message as an array for iteration.
       * @name Type#oneofsArray
       * @type {OneOf[]}
       * @readonly
       */
      oneofsArray: {
        get: /* @__PURE__ */ __name(function() {
          return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));
        }, "get")
      },
      /**
       * The registered constructor, if any registered, otherwise a generic constructor.
       * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.
       * @name Type#ctor
       * @type {Constructor<{}>}
       */
      ctor: {
        get: /* @__PURE__ */ __name(function() {
          return this._ctor || (this.ctor = Type.generateConstructor(this)());
        }, "get"),
        set: /* @__PURE__ */ __name(function(ctor) {
          var prototype = ctor.prototype;
          if (!(prototype instanceof Message)) {
            (ctor.prototype = new Message()).constructor = ctor;
            util.merge(ctor.prototype, prototype);
          }
          ctor.$type = ctor.prototype.$type = this;
          util.merge(ctor, Message, true);
          this._ctor = ctor;
          var i = 0;
          for (; i < /* initializes */
          this.fieldsArray.length; ++i)
            this._fieldsArray[i].resolve();
          var ctorProperties = {};
          for (i = 0; i < /* initializes */
          this.oneofsArray.length; ++i)
            ctorProperties[this._oneofsArray[i].resolve().name] = {
              get: util.oneOfGetter(this._oneofsArray[i].oneof),
              set: util.oneOfSetter(this._oneofsArray[i].oneof)
            };
          if (i)
            Object.defineProperties(ctor.prototype, ctorProperties);
        }, "set")
      }
    });
    Type.generateConstructor = /* @__PURE__ */ __name(function generateConstructor(mtype) {
      var gen = util.codegen(["p"], mtype.name);
      for (var i = 0, field; i < mtype.fieldsArray.length; ++i)
        if ((field = mtype._fieldsArray[i]).map) gen("this%s={}", util.safeProp(field.name));
        else if (field.repeated) gen("this%s=[]", util.safeProp(field.name));
      return gen('if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null&&ks[i]!=="__proto__")')("this[ks[i]]=p[ks[i]]");
    }, "generateConstructor");
    function clearCache(type) {
      type._fieldsById = type._fieldsArray = type._oneofsArray = null;
      delete type.encode;
      delete type.decode;
      delete type.verify;
      return type;
    }
    __name(clearCache, "clearCache");
    Type.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json, depth) {
      if (depth === void 0)
        depth = 0;
      if (depth > util.nestingLimit)
        throw Error("max depth exceeded");
      var type = new Type(name, json.options);
      type.extensions = json.extensions;
      type.reserved = json.reserved;
      var names = Object.keys(json.fields), i = 0;
      for (; i < names.length; ++i)
        type.add(
          (typeof json.fields[names[i]].keyType !== "undefined" ? MapField.fromJSON : Field.fromJSON)(names[i], json.fields[names[i]])
        );
      if (json.oneofs)
        for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)
          type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));
      if (json.nested)
        for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {
          var nested = json.nested[names[i]];
          type.add(
            // most to least likely
            (nested.id !== void 0 ? Field.fromJSON : nested.fields !== void 0 ? Type.fromJSON : nested.values !== void 0 ? Enum.fromJSON : nested.methods !== void 0 ? Service.fromJSON : Namespace.fromJSON)(names[i], nested, depth + 1)
          );
        }
      if (json.extensions && json.extensions.length)
        type.extensions = json.extensions;
      if (json.reserved && json.reserved.length)
        type.reserved = json.reserved;
      if (json.group)
        type.group = true;
      if (json.comment)
        type.comment = json.comment;
      if (json.edition)
        type._edition = json.edition;
      type._defaultEdition = "proto3";
      return type;
    }, "fromJSON");
    Type.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util.toObject([
        "edition",
        this._editionToJSON(),
        "options",
        inherited && inherited.options || void 0,
        "oneofs",
        Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),
        "fields",
        Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) {
          return !obj.declaringField;
        }), toJSONOptions) || {},
        "extensions",
        this.extensions && this.extensions.length ? this.extensions : void 0,
        "reserved",
        this.reserved && this.reserved.length ? this.reserved : void 0,
        "group",
        this.group || void 0,
        "nested",
        inherited && inherited.nested || void 0,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    Type.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      Namespace.prototype.resolveAll.call(this);
      var oneofs = this.oneofsArray;
      i = 0;
      while (i < oneofs.length)
        oneofs[i++].resolve();
      var fields = this.fieldsArray, i = 0;
      while (i < fields.length)
        fields[i++].resolve();
      return this;
    }, "resolveAll");
    Type.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      if (!this._needsRecursiveFeatureResolution) return this;
      edition = this._edition || edition;
      Namespace.prototype._resolveFeaturesRecursive.call(this, edition);
      this.oneofsArray.forEach((oneof) => {
        oneof._resolveFeatures(edition);
      });
      this.fieldsArray.forEach((field) => {
        field._resolveFeatures(edition);
      });
      return this;
    }, "_resolveFeaturesRecursive");
    Type.prototype.get = /* @__PURE__ */ __name(function get(name) {
      if (Object.prototype.hasOwnProperty.call(this.fields, name))
        return this.fields[name];
      if (this.oneofs && Object.prototype.hasOwnProperty.call(this.oneofs, name))
        return this.oneofs[name];
      if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name))
        return this.nested[name];
      return null;
    }, "get");
    Type.prototype.add = /* @__PURE__ */ __name(function add(object) {
      if (this.get(object.name))
        throw Error("duplicate name '" + object.name + "' in " + this);
      if (object instanceof Field && object.extend === void 0) {
        if (this._fieldsById ? (
          /* istanbul ignore next */
          this._fieldsById[object.id]
        ) : this.fieldsById[object.id])
          throw Error("duplicate id " + object.id + " in " + this);
        if (this.isReservedId(object.id))
          throw Error("id " + object.id + " is reserved in " + this);
        if (this.isReservedName(object.name) || object.name.charAt(0) === "$")
          throw Error("name '" + object.name + "' is reserved in " + this);
        if (object.name === "__proto__")
          return this;
        if (object.parent)
          object.parent.remove(object);
        this.fields[object.name] = object;
        object.message = this;
        object.onAdd(this);
        return clearCache(this);
      }
      if (object instanceof OneOf) {
        if (object.name.charAt(0) === "$")
          throw Error("name '" + object.name + "' is reserved in " + this);
        if (object.name === "__proto__")
          return this;
        if (!this.oneofs)
          this.oneofs = {};
        this.oneofs[object.name] = object;
        object.onAdd(this);
        return clearCache(this);
      }
      return Namespace.prototype.add.call(this, object);
    }, "add");
    Type.prototype.remove = /* @__PURE__ */ __name(function remove(object) {
      if (object instanceof Field && object.extend === void 0) {
        if (!this.fields || this.fields[object.name] !== object)
          throw Error(object + " is not a member of " + this);
        delete this.fields[object.name];
        object.parent = null;
        object.onRemove(this);
        return clearCache(this);
      }
      if (object instanceof OneOf) {
        if (!this.oneofs || this.oneofs[object.name] !== object)
          throw Error(object + " is not a member of " + this);
        delete this.oneofs[object.name];
        object.parent = null;
        object.onRemove(this);
        return clearCache(this);
      }
      return Namespace.prototype.remove.call(this, object);
    }, "remove");
    Type.prototype.isReservedId = /* @__PURE__ */ __name(function isReservedId(id) {
      return Namespace.isReservedId(this.reserved, id);
    }, "isReservedId");
    Type.prototype.isReservedName = /* @__PURE__ */ __name(function isReservedName(name) {
      return Namespace.isReservedName(this.reserved, name);
    }, "isReservedName");
    Type.prototype.create = /* @__PURE__ */ __name(function create(properties) {
      return new this.ctor(properties);
    }, "create");
    Type.prototype.setup = /* @__PURE__ */ __name(function setup() {
      var fullName = this.fullName, types2 = [];
      for (var i = 0; i < /* initializes */
      this.fieldsArray.length; ++i)
        types2.push(this._fieldsArray[i].resolve().resolvedType);
      this.encode = encoder(this)({
        Writer,
        types: types2,
        util
      });
      this.decode = decoder(this)({
        Reader,
        types: types2,
        util
      });
      this.verify = verifier(this)({
        types: types2,
        util
      });
      this.fromObject = converter.fromObject(this)({
        types: types2,
        util
      });
      this.toObject = converter.toObject(this)({
        types: types2,
        util
      });
      var wrapper = wrappers[fullName];
      if (wrapper) {
        var originalThis = Object.create(this);
        originalThis.fromObject = this.fromObject;
        this.fromObject = wrapper.fromObject.bind(originalThis);
        originalThis.toObject = this.toObject;
        this.toObject = wrapper.toObject.bind(originalThis);
      }
      return this;
    }, "setup");
    Type.prototype.encode = /* @__PURE__ */ __name(function encode_setup(message, writer) {
      return this.setup().encode.apply(this, arguments);
    }, "encode_setup");
    Type.prototype.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
      return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();
    }, "encodeDelimited");
    Type.prototype.decode = /* @__PURE__ */ __name(function decode_setup(reader, length, end, depth) {
      return this.setup().decode(reader, length, end, depth);
    }, "decode_setup");
    Type.prototype.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
      if (!(reader instanceof Reader))
        reader = Reader.create(reader);
      return this.decode(reader, reader.uint32());
    }, "decodeDelimited");
    Type.prototype.verify = /* @__PURE__ */ __name(function verify_setup(message, depth) {
      return this.setup().verify(message, depth);
    }, "verify_setup");
    Type.prototype.fromObject = /* @__PURE__ */ __name(function fromObject(object, depth) {
      return this.setup().fromObject(object, depth);
    }, "fromObject");
    Type.prototype.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
      return this.setup().toObject.apply(this, arguments);
    }, "toObject");
    Type.d = /* @__PURE__ */ __name(function decorateType(typeName) {
      return /* @__PURE__ */ __name(function typeDecorator(target) {
        util.decorateType(target, typeName);
      }, "typeDecorator");
    }, "decorateType");
  }
});

// node_modules/protobufjs/src/root.js
var require_root = __commonJS({
  "node_modules/protobufjs/src/root.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Root;
    var Namespace = require_namespace();
    ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root";
    var Field = require_field();
    var Enum = require_enum();
    var OneOf = require_oneof();
    var util = require_util();
    var Type;
    var parse;
    var common;
    function Root(options) {
      Namespace.call(this, "", options);
      this.deferred = [];
      this.files = [];
      this._edition = "proto2";
      this._fullyQualifiedObjects = {};
    }
    __name(Root, "Root");
    Root.fromJSON = /* @__PURE__ */ __name(function fromJSON(json, root, depth) {
      depth = util.checkDepth(depth);
      if (!root)
        root = new Root();
      if (json.options)
        root.setOptions(json.options);
      return root.addJSON(json.nested, depth).resolveAll();
    }, "fromJSON");
    Root.prototype.resolvePath = util.path.resolve;
    Root.prototype.fetch = util.fetch;
    function SYNC() {
    }
    __name(SYNC, "SYNC");
    Root.prototype.load = /* @__PURE__ */ __name(function load(filename, options, callback) {
      if (typeof options === "function") {
        callback = options;
        options = void 0;
      }
      var self2 = this;
      if (!callback) {
        return util.asPromise(load, self2, filename, options);
      }
      var sync = callback === SYNC;
      function finish(err, root) {
        if (!callback) {
          return;
        }
        if (sync) {
          throw err;
        }
        if (root) {
          root.resolveAll();
        }
        var cb = callback;
        callback = null;
        cb(err, root);
      }
      __name(finish, "finish");
      function getBundledFileName(filename2) {
        var idx = filename2.lastIndexOf("google/protobuf/");
        if (idx > -1) {
          var altname = filename2.substring(idx);
          if (altname in common) return altname;
        }
        return null;
      }
      __name(getBundledFileName, "getBundledFileName");
      function process2(filename2, source, depth) {
        if (depth === void 0)
          depth = 0;
        try {
          if (depth > util.recursionLimit)
            throw Error("max depth exceeded");
          if (util.isString(source) && source.charAt(0) === "{")
            source = JSON.parse(source);
          if (!util.isString(source))
            self2.setOptions(source.options).addJSON(source.nested);
          else {
            parse.filename = filename2;
            var parsed = parse(source, self2, options), resolved2, i2 = 0;
            if (parsed.imports) {
              for (; i2 < parsed.imports.length; ++i2)
                if (resolved2 = getBundledFileName(parsed.imports[i2]) || self2.resolvePath(filename2, parsed.imports[i2]))
                  fetch(resolved2, false, depth + 1);
            }
            if (parsed.weakImports) {
              for (i2 = 0; i2 < parsed.weakImports.length; ++i2)
                if (resolved2 = getBundledFileName(parsed.weakImports[i2]) || self2.resolvePath(filename2, parsed.weakImports[i2]))
                  fetch(resolved2, true, depth + 1);
            }
          }
        } catch (err) {
          finish(err);
        }
        if (!sync && !queued) {
          finish(null, self2);
        }
      }
      __name(process2, "process");
      function fetch(filename2, weak, depth) {
        if (depth === void 0)
          depth = 0;
        filename2 = getBundledFileName(filename2) || filename2;
        if (self2.files.indexOf(filename2) > -1) {
          return;
        }
        self2.files.push(filename2);
        if (filename2 in common) {
          if (sync) {
            process2(filename2, common[filename2], depth);
          } else {
            ++queued;
            setTimeout(function() {
              --queued;
              process2(filename2, common[filename2], depth);
            });
          }
          return;
        }
        if (sync) {
          var source;
          try {
            source = util.fs.readFileSync(filename2).toString("utf8");
          } catch (err) {
            if (!weak)
              finish(err);
            return;
          }
          process2(filename2, source, depth);
        } else {
          ++queued;
          self2.fetch(filename2, function(err, source2) {
            --queued;
            if (!callback) {
              return;
            }
            if (err) {
              if (!weak)
                finish(err);
              else if (!queued)
                finish(null, self2);
              return;
            }
            process2(filename2, source2, depth);
          });
        }
      }
      __name(fetch, "fetch");
      var queued = 0;
      if (util.isString(filename)) {
        filename = [filename];
      }
      for (var i = 0, resolved; i < filename.length; ++i)
        if (resolved = self2.resolvePath("", filename[i]))
          fetch(resolved);
      if (sync) {
        self2.resolveAll();
        return self2;
      }
      if (!queued) {
        finish(null, self2);
      }
      return self2;
    }, "load");
    Root.prototype.loadSync = /* @__PURE__ */ __name(function loadSync(filename, options) {
      if (!util.isNode)
        throw Error("not supported");
      return this.load(filename, options, SYNC);
    }, "loadSync");
    Root.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      if (this.deferred.length)
        throw Error("unresolvable extensions: " + this.deferred.map(function(field) {
          return "'extend " + field.extend + "' in " + field.parent.fullName;
        }).join(", "));
      return Namespace.prototype.resolveAll.call(this);
    }, "resolveAll");
    var exposeRe = /^[A-Z]/;
    function tryHandleExtension(root, field) {
      var extendedType = field.parent.lookup(field.extend);
      if (extendedType) {
        var sisterField = new Field(field.fullName, field.id, field.type, field.rule, void 0, field.options);
        if (extendedType.get(sisterField.name)) {
          return true;
        }
        sisterField.declaringField = field;
        field.extensionField = sisterField;
        extendedType.add(sisterField);
        return true;
      }
      return false;
    }
    __name(tryHandleExtension, "tryHandleExtension");
    Root.prototype._handleAdd = /* @__PURE__ */ __name(function _handleAdd(object) {
      if (object instanceof Field) {
        if (
          /* an extension field (implies not part of a oneof) */
          object.extend !== void 0 && /* not already handled */
          !object.extensionField
        ) {
          if (!tryHandleExtension(this, object))
            this.deferred.push(object);
        }
      } else if (object instanceof Enum) {
        if (exposeRe.test(object.name))
          object.parent[object.name] = object.values;
      } else if (!(object instanceof OneOf)) {
        if (object instanceof Type)
          for (var i = 0; i < this.deferred.length; )
            if (tryHandleExtension(this, this.deferred[i]))
              this.deferred.splice(i, 1);
            else
              ++i;
        for (var j = 0; j < /* initializes */
        object.nestedArray.length; ++j)
          this._handleAdd(object._nestedArray[j]);
        if (exposeRe.test(object.name))
          object.parent[object.name] = object;
      }
      if (object instanceof Type || object instanceof Enum || object instanceof Field) {
        this._fullyQualifiedObjects[object.fullName] = object;
      }
    }, "_handleAdd");
    Root.prototype._handleRemove = /* @__PURE__ */ __name(function _handleRemove(object) {
      if (object instanceof Field) {
        if (
          /* an extension field */
          object.extend !== void 0
        ) {
          if (
            /* already handled */
            object.extensionField
          ) {
            object.extensionField.parent.remove(object.extensionField);
            object.extensionField = null;
          } else {
            var index = this.deferred.indexOf(object);
            if (index > -1)
              this.deferred.splice(index, 1);
          }
        }
      } else if (object instanceof Enum) {
        if (exposeRe.test(object.name))
          delete object.parent[object.name];
      } else if (object instanceof Namespace) {
        for (var i = 0; i < /* initializes */
        object.nestedArray.length; ++i)
          this._handleRemove(object._nestedArray[i]);
        if (exposeRe.test(object.name))
          delete object.parent[object.name];
      }
      delete this._fullyQualifiedObjects[object.fullName];
    }, "_handleRemove");
    Root._configure = function(Type_, parse_, common_) {
      Type = Type_;
      parse = parse_;
      common = common_;
    };
  }
});

// node_modules/protobufjs/src/util.js
var require_util = __commonJS({
  "node_modules/protobufjs/src/util.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var util = module.exports = require_minimal();
    var roots = require_roots();
    var Type;
    var Enum;
    util.codegen = require_codegen();
    util.fetch = require_fetch();
    util.path = require_path();
    util.patterns = require_patterns();
    var reservedRe = util.patterns.reservedRe;
    util.fs = require_fs2();
    util.checkDepth = /* @__PURE__ */ __name(function checkDepth(depth) {
      if (depth === void 0)
        depth = 0;
      if (depth > util.recursionLimit)
        throw Error("max depth exceeded");
      return depth;
    }, "checkDepth");
    util.toArray = /* @__PURE__ */ __name(function toArray(object) {
      if (object) {
        var keys = Object.keys(object), array = new Array(keys.length), index = 0;
        while (index < keys.length)
          array[index] = object[keys[index++]];
        return array;
      }
      return [];
    }, "toArray");
    util.toObject = /* @__PURE__ */ __name(function toObject(array) {
      var object = {}, index = 0;
      while (index < array.length) {
        var key = array[index++], val = array[index++];
        if (val !== void 0)
          object[key] = val;
      }
      return object;
    }, "toObject");
    util.isReserved = /* @__PURE__ */ __name(function isReserved(name) {
      return reservedRe.test(name);
    }, "isReserved");
    util.safeProp = /* @__PURE__ */ __name(function safeProp(prop) {
      if (!/^[$\w_]+$/.test(prop) || reservedRe.test(prop))
        return "[" + JSON.stringify(prop) + "]";
      return "." + prop;
    }, "safeProp");
    util.ucFirst = /* @__PURE__ */ __name(function ucFirst(str) {
      return str.charAt(0).toUpperCase() + str.substring(1);
    }, "ucFirst");
    var camelCaseRe = /_([a-z])/g;
    util.camelCase = /* @__PURE__ */ __name(function camelCase(str) {
      return str.substring(0, 1) + str.substring(1).replace(camelCaseRe, function($0, $1) {
        return $1.toUpperCase();
      });
    }, "camelCase");
    util.compareFieldsById = /* @__PURE__ */ __name(function compareFieldsById(a, b) {
      return a.id - b.id;
    }, "compareFieldsById");
    util.decorateType = /* @__PURE__ */ __name(function decorateType(ctor, typeName) {
      if (ctor.$type) {
        if (typeName && ctor.$type.name !== typeName) {
          util.decorateRoot.remove(ctor.$type);
          ctor.$type.name = typeName;
          util.decorateRoot.add(ctor.$type);
        }
        return ctor.$type;
      }
      if (!Type)
        Type = require_type();
      var type = new Type(typeName || ctor.name);
      util.decorateRoot.add(type);
      type.ctor = ctor;
      Object.defineProperty(ctor, "$type", { value: type, enumerable: false });
      Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });
      return type;
    }, "decorateType");
    var decorateEnumIndex = 0;
    util.decorateEnum = /* @__PURE__ */ __name(function decorateEnum(object) {
      if (object.$type)
        return object.$type;
      if (!Enum)
        Enum = require_enum();
      var enm = new Enum("Enum" + decorateEnumIndex++, object);
      util.decorateRoot.add(enm);
      Object.defineProperty(object, "$type", { value: enm, enumerable: false });
      return enm;
    }, "decorateEnum");
    util.setProperty = /* @__PURE__ */ __name(function setProperty(dst, path11, value, ifNotSet) {
      function setProp(dst2, path12, value2) {
        var part = path12.shift();
        if (util.isUnsafeProperty(part))
          return dst2;
        if (path12.length > 0) {
          dst2[part] = setProp(dst2[part] || {}, path12, value2);
        } else {
          var prevValue = dst2[part];
          if (prevValue && ifNotSet)
            return dst2;
          if (prevValue)
            value2 = [].concat(prevValue).concat(value2);
          dst2[part] = value2;
        }
        return dst2;
      }
      __name(setProp, "setProp");
      if (typeof dst !== "object")
        throw TypeError("dst must be an object");
      if (!path11)
        throw TypeError("path must be specified");
      path11 = path11.split(".");
      if (path11.length > util.recursionLimit)
        throw Error("max depth exceeded");
      return setProp(dst, path11, value);
    }, "setProperty");
    Object.defineProperty(util, "decorateRoot", {
      get: /* @__PURE__ */ __name(function() {
        return roots["decorated"] || (roots["decorated"] = new (require_root())());
      }, "get")
    });
  }
});

// node_modules/protobufjs/src/types.js
var require_types = __commonJS({
  "node_modules/protobufjs/src/types.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var types2 = exports;
    var util = require_util();
    var s = [
      "double",
      // 0
      "float",
      // 1
      "int32",
      // 2
      "uint32",
      // 3
      "sint32",
      // 4
      "fixed32",
      // 5
      "sfixed32",
      // 6
      "int64",
      // 7
      "uint64",
      // 8
      "sint64",
      // 9
      "fixed64",
      // 10
      "sfixed64",
      // 11
      "bool",
      // 12
      "string",
      // 13
      "bytes"
      // 14
    ];
    function bake(values, offset) {
      var i = 0, o = /* @__PURE__ */ Object.create(null);
      offset |= 0;
      while (i < values.length) o[s[i + offset]] = values[i++];
      return o;
    }
    __name(bake, "bake");
    types2.basic = bake([
      /* double   */
      1,
      /* float    */
      5,
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      5,
      /* sfixed32 */
      5,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1,
      /* bool     */
      0,
      /* string   */
      2,
      /* bytes    */
      2
    ]);
    types2.defaults = bake([
      /* double   */
      0,
      /* float    */
      0,
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      0,
      /* sfixed32 */
      0,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      0,
      /* sfixed64 */
      0,
      /* bool     */
      false,
      /* string   */
      "",
      /* bytes    */
      util.emptyArray,
      /* message  */
      null
    ]);
    types2.long = bake([
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1
    ], 7);
    types2.mapKey = bake([
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      5,
      /* sfixed32 */
      5,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1,
      /* bool     */
      0,
      /* string   */
      2
    ], 2);
    types2.packed = bake([
      /* double   */
      1,
      /* float    */
      5,
      /* int32    */
      0,
      /* uint32   */
      0,
      /* sint32   */
      0,
      /* fixed32  */
      5,
      /* sfixed32 */
      5,
      /* int64    */
      0,
      /* uint64   */
      0,
      /* sint64   */
      0,
      /* fixed64  */
      1,
      /* sfixed64 */
      1,
      /* bool     */
      0
    ]);
  }
});

// node_modules/protobufjs/src/field.js
var require_field = __commonJS({
  "node_modules/protobufjs/src/field.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Field;
    var ReflectionObject = require_object();
    ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";
    var Enum = require_enum();
    var types2 = require_types();
    var util = require_util();
    var Type;
    var ruleRe = /^required|optional|repeated$/;
    Field.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json) {
      var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);
      if (json.edition)
        field._edition = json.edition;
      field._defaultEdition = "proto3";
      return field;
    }, "fromJSON");
    function Field(name, id, type, rule, extend, options, comment) {
      if (util.isObject(rule)) {
        comment = extend;
        options = rule;
        rule = extend = void 0;
      } else if (util.isObject(extend)) {
        comment = options;
        options = extend;
        extend = void 0;
      }
      ReflectionObject.call(this, name, options);
      if (!util.isInteger(id) || id < 0)
        throw TypeError("id must be a non-negative integer");
      if (!util.isString(type))
        throw TypeError("type must be a string");
      if (rule !== void 0 && !ruleRe.test(rule = rule.toString().toLowerCase()))
        throw TypeError("rule must be a string rule");
      if (extend !== void 0 && !util.isString(extend))
        throw TypeError("extend must be a string");
      if (rule === "proto3_optional") {
        rule = "optional";
      }
      this.rule = rule && rule !== "optional" ? rule : void 0;
      this.type = type;
      this.id = id;
      this.extend = extend || void 0;
      this.repeated = rule === "repeated";
      this.map = false;
      this.message = null;
      this.partOf = null;
      this.typeDefault = null;
      this.defaultValue = null;
      this.long = util.Long ? types2.long[type] !== void 0 : (
        /* istanbul ignore next */
        false
      );
      this.bytes = type === "bytes";
      this.resolvedType = null;
      this.extensionField = null;
      this.declaringField = null;
      this.comment = comment;
    }
    __name(Field, "Field");
    Object.defineProperty(Field.prototype, "required", {
      get: /* @__PURE__ */ __name(function() {
        return this._features.field_presence === "LEGACY_REQUIRED";
      }, "get")
    });
    Object.defineProperty(Field.prototype, "optional", {
      get: /* @__PURE__ */ __name(function() {
        return !this.required;
      }, "get")
    });
    Object.defineProperty(Field.prototype, "delimited", {
      get: /* @__PURE__ */ __name(function() {
        return this.resolvedType instanceof Type && this._features.message_encoding === "DELIMITED";
      }, "get")
    });
    Object.defineProperty(Field.prototype, "packed", {
      get: /* @__PURE__ */ __name(function() {
        return this._features.repeated_field_encoding === "PACKED";
      }, "get")
    });
    Object.defineProperty(Field.prototype, "hasPresence", {
      get: /* @__PURE__ */ __name(function() {
        if (this.repeated || this.map) {
          return false;
        }
        return this.partOf || // oneofs
        this.declaringField || this.extensionField || // extensions
        this._features.field_presence !== "IMPLICIT";
      }, "get")
    });
    Field.prototype.setOption = /* @__PURE__ */ __name(function setOption(name, value, ifNotSet) {
      return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);
    }, "setOption");
    Field.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util.toObject([
        "edition",
        this._editionToJSON(),
        "rule",
        this.rule !== "optional" && this.rule || void 0,
        "type",
        this.type,
        "id",
        this.id,
        "extend",
        this.extend,
        "options",
        this.options,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    Field.prototype.resolve = /* @__PURE__ */ __name(function resolve2() {
      if (this.resolved)
        return this;
      if ((this.typeDefault = types2.defaults[this.type]) === void 0) {
        this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
        if (this.resolvedType instanceof Type)
          this.typeDefault = null;
        else
          this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]];
      } else if (this.options && this.options.proto3_optional) {
        this.typeDefault = null;
      }
      if (this.options && this.options["default"] != null) {
        this.typeDefault = this.options["default"];
        if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")
          this.typeDefault = this.resolvedType.values[this.typeDefault];
      }
      if (this.options) {
        if (this.options.packed !== void 0 && this.resolvedType && !(this.resolvedType instanceof Enum))
          delete this.options.packed;
        if (!Object.keys(this.options).length)
          this.options = void 0;
      }
      if (this.long) {
        this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type === "uint64" || this.type === "fixed64");
        if (Object.freeze)
          Object.freeze(this.typeDefault);
      } else if (this.bytes && typeof this.typeDefault === "string") {
        var buf;
        if (util.base64.test(this.typeDefault))
          util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);
        else
          util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);
        this.typeDefault = buf;
      }
      if (this.map)
        this.defaultValue = util.emptyObject;
      else if (this.repeated)
        this.defaultValue = util.emptyArray;
      else
        this.defaultValue = this.typeDefault;
      if (this.parent instanceof Type)
        this.parent.ctor.prototype[this.name] = this.defaultValue;
      return ReflectionObject.prototype.resolve.call(this);
    }, "resolve");
    Field.prototype._inferLegacyProtoFeatures = /* @__PURE__ */ __name(function _inferLegacyProtoFeatures(edition) {
      if (edition !== "proto2" && edition !== "proto3") {
        return {};
      }
      var features = {};
      if (this.rule === "required") {
        features.field_presence = "LEGACY_REQUIRED";
      }
      if (this.parent && types2.defaults[this.type] === void 0) {
        var type = this.parent.get(this.type.split(".").pop());
        if (type && type instanceof Type && type.group) {
          features.message_encoding = "DELIMITED";
        }
      }
      if (this.getOption("packed") === true) {
        features.repeated_field_encoding = "PACKED";
      } else if (this.getOption("packed") === false) {
        features.repeated_field_encoding = "EXPANDED";
      }
      return features;
    }, "_inferLegacyProtoFeatures");
    Field.prototype._resolveFeatures = /* @__PURE__ */ __name(function _resolveFeatures(edition) {
      return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition);
    }, "_resolveFeatures");
    Field.d = /* @__PURE__ */ __name(function decorateField(fieldId, fieldType, fieldRule, defaultValue) {
      if (typeof fieldType === "function")
        fieldType = util.decorateType(fieldType).name;
      else if (fieldType && typeof fieldType === "object")
        fieldType = util.decorateEnum(fieldType).name;
      return /* @__PURE__ */ __name(function fieldDecorator(prototype, fieldName) {
        util.decorateType(prototype.constructor).add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));
      }, "fieldDecorator");
    }, "decorateField");
    Field._configure = /* @__PURE__ */ __name(function configure(Type_) {
      Type = Type_;
    }, "configure");
  }
});

// node_modules/protobufjs/src/oneof.js
var require_oneof = __commonJS({
  "node_modules/protobufjs/src/oneof.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = OneOf;
    var ReflectionObject = require_object();
    ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";
    var Field = require_field();
    var util = require_util();
    function OneOf(name, fieldNames, options, comment) {
      if (!Array.isArray(fieldNames)) {
        options = fieldNames;
        fieldNames = void 0;
      }
      ReflectionObject.call(this, name, options);
      if (!(fieldNames === void 0 || Array.isArray(fieldNames)))
        throw TypeError("fieldNames must be an Array");
      this.oneof = fieldNames || [];
      this.fieldsArray = [];
      this.comment = comment;
    }
    __name(OneOf, "OneOf");
    OneOf.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json) {
      return new OneOf(name, json.oneof, json.options, json.comment);
    }, "fromJSON");
    OneOf.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util.toObject([
        "options",
        this.options,
        "oneof",
        this.oneof,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    function addFieldsToParent(oneof) {
      if (oneof.parent) {
        for (var i = 0; i < oneof.fieldsArray.length; ++i)
          if (!oneof.fieldsArray[i].parent)
            oneof.parent.add(oneof.fieldsArray[i]);
      }
    }
    __name(addFieldsToParent, "addFieldsToParent");
    OneOf.prototype.add = /* @__PURE__ */ __name(function add(field) {
      if (!(field instanceof Field))
        throw TypeError("field must be a Field");
      if (field.parent && field.parent !== this.parent)
        field.parent.remove(field);
      this.oneof.push(field.name);
      this.fieldsArray.push(field);
      field.partOf = this;
      addFieldsToParent(this);
      return this;
    }, "add");
    OneOf.prototype.remove = /* @__PURE__ */ __name(function remove(field) {
      if (!(field instanceof Field))
        throw TypeError("field must be a Field");
      var index = this.fieldsArray.indexOf(field);
      if (index < 0)
        throw Error(field + " is not a member of " + this);
      this.fieldsArray.splice(index, 1);
      index = this.oneof.indexOf(field.name);
      if (index > -1)
        this.oneof.splice(index, 1);
      field.partOf = null;
      return this;
    }, "remove");
    OneOf.prototype.onAdd = /* @__PURE__ */ __name(function onAdd(parent) {
      ReflectionObject.prototype.onAdd.call(this, parent);
      var self2 = this;
      for (var i = 0; i < this.oneof.length; ++i) {
        var field = parent.get(this.oneof[i]);
        if (field && !field.partOf) {
          field.partOf = self2;
          self2.fieldsArray.push(field);
        }
      }
      addFieldsToParent(this);
    }, "onAdd");
    OneOf.prototype.onRemove = /* @__PURE__ */ __name(function onRemove(parent) {
      for (var i = 0, field; i < this.fieldsArray.length; ++i)
        if ((field = this.fieldsArray[i]).parent)
          field.parent.remove(field);
      ReflectionObject.prototype.onRemove.call(this, parent);
    }, "onRemove");
    Object.defineProperty(OneOf.prototype, "isProto3Optional", {
      get: /* @__PURE__ */ __name(function() {
        if (this.fieldsArray == null || this.fieldsArray.length !== 1) {
          return false;
        }
        var field = this.fieldsArray[0];
        return field.options != null && field.options["proto3_optional"] === true;
      }, "get")
    });
    OneOf.d = /* @__PURE__ */ __name(function decorateOneOf() {
      var fieldNames = new Array(arguments.length), index = 0;
      while (index < arguments.length)
        fieldNames[index] = arguments[index++];
      return /* @__PURE__ */ __name(function oneOfDecorator(prototype, oneofName) {
        util.decorateType(prototype.constructor).add(new OneOf(oneofName, fieldNames));
        Object.defineProperty(prototype, oneofName, {
          get: util.oneOfGetter(fieldNames),
          set: util.oneOfSetter(fieldNames)
        });
      }, "oneOfDecorator");
    }, "decorateOneOf");
  }
});

// node_modules/protobufjs/src/object.js
var require_object = __commonJS({
  "node_modules/protobufjs/src/object.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = ReflectionObject;
    ReflectionObject.className = "ReflectionObject";
    var OneOf = require_oneof();
    var util = require_util();
    var Root;
    var editions2023Defaults = { enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" };
    var proto2Defaults = { enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE" };
    var proto3Defaults = { enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" };
    function ReflectionObject(name, options) {
      if (!util.isString(name))
        throw TypeError("name must be a string");
      if (options && !util.isObject(options))
        throw TypeError("options must be an object");
      this.options = options;
      this.parsedOptions = null;
      this.name = name;
      this._edition = null;
      this._defaultEdition = "proto2";
      this._features = {};
      this._featuresResolved = false;
      this.parent = null;
      this.resolved = false;
      this.comment = null;
      this.filename = null;
    }
    __name(ReflectionObject, "ReflectionObject");
    Object.defineProperties(ReflectionObject.prototype, {
      /**
       * Reference to the root namespace.
       * @name ReflectionObject#root
       * @type {Root}
       * @readonly
       */
      root: {
        get: /* @__PURE__ */ __name(function() {
          var ptr = this;
          while (ptr.parent !== null)
            ptr = ptr.parent;
          return ptr;
        }, "get")
      },
      /**
       * Full name including leading dot.
       * @name ReflectionObject#fullName
       * @type {string}
       * @readonly
       */
      fullName: {
        get: /* @__PURE__ */ __name(function() {
          var path11 = [this.name], ptr = this.parent;
          while (ptr) {
            path11.unshift(ptr.name);
            ptr = ptr.parent;
          }
          return path11.join(".");
        }, "get")
      }
    });
    ReflectionObject.prototype.toJSON = /* istanbul ignore next */
    /* @__PURE__ */ __name(function toJSON() {
      throw Error();
    }, "toJSON");
    ReflectionObject.prototype.onAdd = /* @__PURE__ */ __name(function onAdd(parent) {
      if (this.parent && this.parent !== parent)
        this.parent.remove(this);
      this.parent = parent;
      this.resolved = false;
      var root = parent.root;
      if (root instanceof Root)
        root._handleAdd(this);
    }, "onAdd");
    ReflectionObject.prototype.onRemove = /* @__PURE__ */ __name(function onRemove(parent) {
      var root = parent.root;
      if (root instanceof Root)
        root._handleRemove(this);
      this.parent = null;
      this.resolved = false;
    }, "onRemove");
    ReflectionObject.prototype.resolve = /* @__PURE__ */ __name(function resolve2() {
      if (this.resolved)
        return this;
      if (this.root instanceof Root)
        this.resolved = true;
      return this;
    }, "resolve");
    ReflectionObject.prototype._resolveFeaturesRecursive = /* @__PURE__ */ __name(function _resolveFeaturesRecursive(edition) {
      return this._resolveFeatures(this._edition || edition);
    }, "_resolveFeaturesRecursive");
    ReflectionObject.prototype._resolveFeatures = /* @__PURE__ */ __name(function _resolveFeatures(edition) {
      if (this._featuresResolved) {
        return;
      }
      var defaults = {};
      if (!edition) {
        throw new Error("Unknown edition for " + this.fullName);
      }
      var protoFeatures = util.merge(
        {},
        this.options && this.options.features,
        this._inferLegacyProtoFeatures(edition)
      );
      if (this._edition) {
        if (edition === "proto2") {
          defaults = Object.assign({}, proto2Defaults);
        } else if (edition === "proto3") {
          defaults = Object.assign({}, proto3Defaults);
        } else if (edition === "2023") {
          defaults = Object.assign({}, editions2023Defaults);
        } else {
          throw new Error("Unknown edition: " + edition);
        }
        this._features = util.merge(defaults, protoFeatures);
        this._featuresResolved = true;
        return;
      }
      if (this.partOf instanceof OneOf) {
        var lexicalParentFeaturesCopy = util.merge({}, this.partOf._features);
        this._features = util.merge(lexicalParentFeaturesCopy, protoFeatures);
      } else if (this.declaringField) {
      } else if (this.parent) {
        var parentFeaturesCopy = util.merge({}, this.parent._features);
        this._features = util.merge(parentFeaturesCopy, protoFeatures);
      } else {
        throw new Error("Unable to find a parent for " + this.fullName);
      }
      if (this.extensionField) {
        this.extensionField._features = this._features;
      }
      this._featuresResolved = true;
    }, "_resolveFeatures");
    ReflectionObject.prototype._inferLegacyProtoFeatures = /* @__PURE__ */ __name(function _inferLegacyProtoFeatures() {
      return {};
    }, "_inferLegacyProtoFeatures");
    ReflectionObject.prototype.getOption = /* @__PURE__ */ __name(function getOption(name) {
      if (this.options)
        return this.options[name];
      return void 0;
    }, "getOption");
    ReflectionObject.prototype.setOption = /* @__PURE__ */ __name(function setOption(name, value, ifNotSet) {
      if (name === "__proto__")
        return this;
      if (!this.options)
        this.options = {};
      if (/^features\./.test(name)) {
        util.setProperty(this.options, name, value, ifNotSet);
      } else if (!ifNotSet || this.options[name] === void 0) {
        if (this.getOption(name) !== value) this.resolved = false;
        this.options[name] = value;
      }
      return this;
    }, "setOption");
    ReflectionObject.prototype.setParsedOption = /* @__PURE__ */ __name(function setParsedOption(name, value, propName) {
      if (name === "__proto__")
        return this;
      if (!this.parsedOptions) {
        this.parsedOptions = [];
      }
      var parsedOptions = this.parsedOptions;
      if (propName) {
        var opt = parsedOptions.find(function(opt2) {
          return Object.prototype.hasOwnProperty.call(opt2, name);
        });
        if (opt) {
          var newValue = opt[name];
          util.setProperty(newValue, propName, value);
        } else {
          opt = {};
          opt[name] = util.setProperty({}, propName, value);
          parsedOptions.push(opt);
        }
      } else {
        var newOpt = {};
        newOpt[name] = value;
        parsedOptions.push(newOpt);
      }
      return this;
    }, "setParsedOption");
    ReflectionObject.prototype.setOptions = /* @__PURE__ */ __name(function setOptions(options, ifNotSet) {
      if (options)
        for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)
          this.setOption(keys[i], options[keys[i]], ifNotSet);
      return this;
    }, "setOptions");
    ReflectionObject.prototype.toString = /* @__PURE__ */ __name(function toString() {
      var className = this.constructor.className, fullName = this.fullName;
      if (fullName.length)
        return className + " " + fullName;
      return className;
    }, "toString");
    ReflectionObject.prototype._editionToJSON = /* @__PURE__ */ __name(function _editionToJSON() {
      if (!this._edition || this._edition === "proto3") {
        return void 0;
      }
      return this._edition;
    }, "_editionToJSON");
    ReflectionObject._configure = function(Root_) {
      Root = Root_;
    };
  }
});

// node_modules/protobufjs/src/enum.js
var require_enum = __commonJS({
  "node_modules/protobufjs/src/enum.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = Enum;
    var ReflectionObject = require_object();
    ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";
    var Namespace = require_namespace();
    var util = require_util();
    function Enum(name, values, options, comment, comments, valuesOptions) {
      ReflectionObject.call(this, name, options);
      if (values && typeof values !== "object")
        throw TypeError("values must be an object");
      this.valuesById = {};
      this.values = Object.create(this.valuesById);
      this.comment = comment;
      this.comments = comments || {};
      this.valuesOptions = valuesOptions;
      this._valuesFeatures = {};
      this.reserved = void 0;
      if (values) {
        for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)
          if (keys[i] !== "__proto__" && typeof values[keys[i]] === "number")
            this.valuesById[this.values[keys[i]] = values[keys[i]]] = keys[i];
      }
    }
    __name(Enum, "Enum");
    Enum.prototype._resolveFeatures = /* @__PURE__ */ __name(function _resolveFeatures(edition) {
      edition = this._edition || edition;
      ReflectionObject.prototype._resolveFeatures.call(this, edition);
      Object.keys(this.values).forEach((key) => {
        var parentFeaturesCopy = util.merge({}, this._features);
        this._valuesFeatures[key] = util.merge(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features || {});
      });
      return this;
    }, "_resolveFeatures");
    Enum.fromJSON = /* @__PURE__ */ __name(function fromJSON(name, json) {
      var enm = new Enum(name, json.values, json.options, json.comment, json.comments);
      enm.reserved = json.reserved;
      if (json.edition)
        enm._edition = json.edition;
      enm._defaultEdition = "proto3";
      return enm;
    }, "fromJSON");
    Enum.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util.toObject([
        "edition",
        this._editionToJSON(),
        "options",
        this.options,
        "valuesOptions",
        this.valuesOptions,
        "values",
        this.values,
        "reserved",
        this.reserved && this.reserved.length ? this.reserved : void 0,
        "comment",
        keepComments ? this.comment : void 0,
        "comments",
        keepComments ? this.comments : void 0
      ]);
    }, "toJSON");
    Enum.prototype.add = /* @__PURE__ */ __name(function add(name, id, comment, options) {
      if (!util.isString(name))
        throw TypeError("name must be a string");
      if (!util.isInteger(id))
        throw TypeError("id must be an integer");
      if (name === "__proto__")
        return this;
      if (this.values[name] !== void 0)
        throw Error("duplicate name '" + name + "' in " + this);
      if (this.isReservedId(id))
        throw Error("id " + id + " is reserved in " + this);
      if (this.isReservedName(name))
        throw Error("name '" + name + "' is reserved in " + this);
      if (this.valuesById[id] !== void 0) {
        if (!(this.options && this.options.allow_alias))
          throw Error("duplicate id " + id + " in " + this);
        this.values[name] = id;
      } else
        this.valuesById[this.values[name] = id] = name;
      if (options) {
        if (this.valuesOptions === void 0)
          this.valuesOptions = {};
        this.valuesOptions[name] = options || null;
      }
      this.comments[name] = comment || null;
      return this;
    }, "add");
    Enum.prototype.remove = /* @__PURE__ */ __name(function remove(name) {
      if (!util.isString(name))
        throw TypeError("name must be a string");
      var val = this.values[name];
      if (val == null)
        throw Error("name '" + name + "' does not exist in " + this);
      delete this.valuesById[val];
      delete this.values[name];
      delete this.comments[name];
      if (this.valuesOptions)
        delete this.valuesOptions[name];
      return this;
    }, "remove");
    Enum.prototype.isReservedId = /* @__PURE__ */ __name(function isReservedId(id) {
      return Namespace.isReservedId(this.reserved, id);
    }, "isReservedId");
    Enum.prototype.isReservedName = /* @__PURE__ */ __name(function isReservedName(name) {
      return Namespace.isReservedName(this.reserved, name);
    }, "isReservedName");
  }
});

// node_modules/protobufjs/src/encoder.js
var require_encoder = __commonJS({
  "node_modules/protobufjs/src/encoder.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = encoder;
    var Enum = require_enum();
    var types2 = require_types();
    var util = require_util();
    function genTypePartial(gen, field, fieldIndex, ref) {
      return field.delimited ? gen("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) : gen("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);
    }
    __name(genTypePartial, "genTypePartial");
    function encoder(mtype) {
      var gen = util.codegen(["m", "w", "q"], mtype.name + "$encode")("if(!w)")("w=Writer.create()")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")');
      var i, ref;
      var fields = (
        /* initializes */
        mtype.fieldsArray.slice().sort(util.compareFieldsById)
      );
      for (var i = 0; i < fields.length; ++i) {
        var field = fields[i].resolve(), index = mtype._fieldsArray.indexOf(field), type = field.resolvedType instanceof Enum ? "int32" : field.type, wireType = types2.basic[type];
        ref = "m" + util.safeProp(field.name);
        if (field.map) {
          gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types2.mapKey[field.keyType], field.keyType);
          if (wireType === void 0) gen("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()", index, ref);
          else gen(".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
          gen("}")("}");
        } else if (field.repeated) {
          gen("if(%s!=null&&%s.length){", ref, ref);
          if (field.packed && types2.packed[type] !== void 0) {
            gen("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)("for(var i=0;i<%s.length;++i)", ref)("w.%s(%s[i])", type, ref)("w.ldelim()");
          } else {
            gen("for(var i=0;i<%s.length;++i)", ref);
            if (wireType === void 0)
              genTypePartial(gen, field, index, ref + "[i]");
            else gen("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
          }
          gen("}");
        } else {
          if (field.optional) gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name);
          if (wireType === void 0)
            genTypePartial(gen, field, index, ref);
          else gen("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);
        }
      }
      return gen("return w");
    }
    __name(encoder, "encoder");
  }
});

// node_modules/protobufjs/src/index-light.js
var require_index_light = __commonJS({
  "node_modules/protobufjs/src/index-light.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var protobuf = module.exports = require_index_minimal();
    protobuf.build = "light";
    function load(filename, root, callback) {
      if (typeof root === "function") {
        callback = root;
        root = new protobuf.Root();
      } else if (!root)
        root = new protobuf.Root();
      return root.load(filename, callback);
    }
    __name(load, "load");
    protobuf.load = load;
    function loadSync(filename, root) {
      if (!root)
        root = new protobuf.Root();
      return root.loadSync(filename);
    }
    __name(loadSync, "loadSync");
    protobuf.loadSync = loadSync;
    protobuf.encoder = require_encoder();
    protobuf.decoder = require_decoder();
    protobuf.verifier = require_verifier();
    protobuf.converter = require_converter();
    protobuf.ReflectionObject = require_object();
    protobuf.Namespace = require_namespace();
    protobuf.Root = require_root();
    protobuf.Enum = require_enum();
    protobuf.Type = require_type();
    protobuf.Field = require_field();
    protobuf.OneOf = require_oneof();
    protobuf.MapField = require_mapfield();
    protobuf.Service = require_service();
    protobuf.Method = require_method();
    protobuf.Message = require_message();
    protobuf.wrappers = require_wrappers();
    protobuf.types = require_types();
    protobuf.util = require_util();
    protobuf.ReflectionObject._configure(protobuf.Root);
    protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);
    protobuf.Root._configure(protobuf.Type);
    protobuf.Field._configure(protobuf.Type);
  }
});

// node_modules/protobufjs/src/tokenize.js
var require_tokenize = __commonJS({
  "node_modules/protobufjs/src/tokenize.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = tokenize;
    var delimRe = /[\s{}=;:[\],'"()<>]/g;
    var stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g;
    var stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;
    var setCommentRe = /^ *[*/]+ */;
    var setCommentAltRe = /^\s*\*?\/*/;
    var setCommentSplitRe = /\n/g;
    var whitespaceRe = /\s/;
    var unescapeRe = /\\(.?)/g;
    var unescapeMap = {
      "0": "\0",
      "r": "\r",
      "n": "\n",
      "t": "	"
    };
    function unescape(str) {
      return str.replace(unescapeRe, function($0, $1) {
        switch ($1) {
          case "\\":
          case "":
            return $1;
          default:
            return unescapeMap[$1] || "";
        }
      });
    }
    __name(unescape, "unescape");
    tokenize.unescape = unescape;
    function tokenize(source, alternateCommentMode) {
      source = source.toString();
      var offset = 0, length = source.length, line = 1, lastCommentLine = 0, comments = {};
      var stack = [];
      var stringDelim = null;
      function illegal(subject) {
        return Error("illegal " + subject + " (line " + line + ")");
      }
      __name(illegal, "illegal");
      function readString() {
        var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe;
        re.lastIndex = offset - 1;
        var match = re.exec(source);
        if (!match)
          throw illegal("string");
        offset = re.lastIndex;
        push(stringDelim);
        stringDelim = null;
        return unescape(match[1]);
      }
      __name(readString, "readString");
      function charAt(pos) {
        return source.charAt(pos);
      }
      __name(charAt, "charAt");
      function setComment(start, end, isLeading) {
        var comment = {
          type: source.charAt(start++),
          lineEmpty: false,
          leading: isLeading
        };
        var lookback;
        if (alternateCommentMode) {
          lookback = 2;
        } else {
          lookback = 3;
        }
        var commentOffset = start - lookback, c;
        do {
          if (--commentOffset < 0 || (c = source.charAt(commentOffset)) === "\n") {
            comment.lineEmpty = true;
            break;
          }
        } while (c === " " || c === "	");
        var lines = source.substring(start, end).split(setCommentSplitRe);
        for (var i = 0; i < lines.length; ++i)
          lines[i] = lines[i].replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "").trim();
        comment.text = lines.join("\n").trim();
        comments[line] = comment;
        lastCommentLine = line;
      }
      __name(setComment, "setComment");
      function isDoubleSlashCommentLine(startOffset) {
        var endOffset = findEndOfLine(startOffset);
        var lineText = source.substring(startOffset, endOffset);
        var isComment = /^\s*\/\//.test(lineText);
        return isComment;
      }
      __name(isDoubleSlashCommentLine, "isDoubleSlashCommentLine");
      function findEndOfLine(cursor) {
        var endOffset = cursor;
        while (endOffset < length && charAt(endOffset) !== "\n") {
          endOffset++;
        }
        return endOffset;
      }
      __name(findEndOfLine, "findEndOfLine");
      function next() {
        if (stack.length > 0)
          return stack.shift();
        if (stringDelim)
          return readString();
        var repeat, prev, curr, start, isDoc, isLeadingComment = offset === 0;
        do {
          if (offset === length)
            return null;
          repeat = false;
          while (whitespaceRe.test(curr = charAt(offset))) {
            if (curr === "\n") {
              isLeadingComment = true;
              ++line;
            }
            if (++offset === length)
              return null;
          }
          if (charAt(offset) === "/") {
            if (++offset === length) {
              throw illegal("comment");
            }
            if (charAt(offset) === "/") {
              if (!alternateCommentMode) {
                isDoc = charAt(start = offset + 1) === "/";
                while (charAt(++offset) !== "\n") {
                  if (offset === length) {
                    return null;
                  }
                }
                ++offset;
                if (isDoc) {
                  setComment(start, offset - 1, isLeadingComment);
                  isLeadingComment = true;
                }
                ++line;
                repeat = true;
              } else {
                start = offset;
                isDoc = false;
                if (isDoubleSlashCommentLine(offset - 1)) {
                  isDoc = true;
                  do {
                    offset = findEndOfLine(offset);
                    if (offset === length) {
                      break;
                    }
                    offset++;
                    if (!isLeadingComment) {
                      break;
                    }
                  } while (isDoubleSlashCommentLine(offset));
                } else {
                  offset = Math.min(length, findEndOfLine(offset) + 1);
                }
                if (isDoc) {
                  setComment(start, offset, isLeadingComment);
                  isLeadingComment = true;
                }
                line++;
                repeat = true;
              }
            } else if ((curr = charAt(offset)) === "*") {
              start = offset + 1;
              isDoc = alternateCommentMode || charAt(start) === "*";
              do {
                if (curr === "\n") {
                  ++line;
                }
                if (++offset === length) {
                  throw illegal("comment");
                }
                prev = curr;
                curr = charAt(offset);
              } while (prev !== "*" || curr !== "/");
              ++offset;
              if (isDoc) {
                setComment(start, offset - 2, isLeadingComment);
                isLeadingComment = true;
              }
              repeat = true;
            } else {
              return "/";
            }
          }
        } while (repeat);
        var end = offset;
        delimRe.lastIndex = 0;
        var delim = delimRe.test(charAt(end++));
        if (!delim)
          while (end < length && !delimRe.test(charAt(end)))
            ++end;
        var token = source.substring(offset, offset = end);
        if (token === '"' || token === "'")
          stringDelim = token;
        return token;
      }
      __name(next, "next");
      function push(token) {
        stack.push(token);
      }
      __name(push, "push");
      function peek() {
        if (!stack.length) {
          var token = next();
          if (token === null)
            return null;
          push(token);
        }
        return stack[0];
      }
      __name(peek, "peek");
      function skip(expected, optional) {
        var actual = peek(), equals = actual === expected;
        if (equals) {
          next();
          return true;
        }
        if (!optional)
          throw illegal("token '" + actual + "', '" + expected + "' expected");
        return false;
      }
      __name(skip, "skip");
      function cmnt(trailingLine) {
        var ret = null;
        var comment;
        if (trailingLine === void 0) {
          comment = comments[line - 1];
          delete comments[line - 1];
          if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) {
            ret = comment.leading ? comment.text : null;
          }
        } else {
          if (lastCommentLine < trailingLine) {
            peek();
          }
          comment = comments[trailingLine];
          delete comments[trailingLine];
          if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) {
            ret = comment.leading ? null : comment.text;
          }
        }
        return ret;
      }
      __name(cmnt, "cmnt");
      return Object.defineProperty({
        next,
        peek,
        push,
        skip,
        cmnt
      }, "line", {
        get: /* @__PURE__ */ __name(function() {
          return line;
        }, "get")
      });
    }
    __name(tokenize, "tokenize");
  }
});

// node_modules/protobufjs/src/parse.js
var require_parse = __commonJS({
  "node_modules/protobufjs/src/parse.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = parse;
    parse.filename = null;
    parse.defaults = { keepCase: false };
    var tokenize = require_tokenize();
    var Root = require_root();
    var Type = require_type();
    var Field = require_field();
    var MapField = require_mapfield();
    var OneOf = require_oneof();
    var Enum = require_enum();
    var Service = require_service();
    var Method = require_method();
    var ReflectionObject = require_object();
    var types2 = require_types();
    var util = require_util();
    var base10Re = /^[1-9][0-9]*$/;
    var base10NegRe = /^-?[1-9][0-9]*$/;
    var base16Re = /^0[x][0-9a-fA-F]+$/;
    var base16NegRe = /^-?0[x][0-9a-fA-F]+$/;
    var base8Re = /^0[0-7]+$/;
    var base8NegRe = /^-?0[0-7]+$/;
    var numberRe = util.patterns.numberRe;
    var nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
    var typeRefRe = util.patterns.typeRefRe;
    function parse(source, root, options) {
      if (!(root instanceof Root)) {
        options = root;
        root = new Root();
      }
      if (!options)
        options = parse.defaults;
      var preferTrailingComment = options.preferTrailingComment || false;
      var tn = tokenize(source, options.alternateCommentMode || false), next = tn.next, push = tn.push, peek = tn.peek, skip = tn.skip, cmnt = tn.cmnt;
      var head = true, pkg, imports, weakImports, edition = "proto2";
      var ptr = root;
      var topLevelObjects = [];
      var topLevelOptions = {};
      var applyCase = options.keepCase ? function(name) {
        return name;
      } : util.camelCase;
      function resolveFileFeatures() {
        topLevelObjects.forEach((obj) => {
          obj._edition = edition;
          Object.keys(topLevelOptions).forEach((opt) => {
            if (obj.getOption(opt) !== void 0) return;
            obj.setOption(opt, topLevelOptions[opt], true);
          });
        });
      }
      __name(resolveFileFeatures, "resolveFileFeatures");
      function illegal(token2, name, insideTryCatch) {
        var filename = parse.filename;
        if (!insideTryCatch)
          parse.filename = null;
        return Error("illegal " + (name || "token") + " '" + token2 + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")");
      }
      __name(illegal, "illegal");
      function readString() {
        var values = [], token2;
        do {
          if ((token2 = next()) !== '"' && token2 !== "'")
            throw illegal(token2);
          values.push(next());
          skip(token2);
          token2 = peek();
        } while (token2 === '"' || token2 === "'");
        return values.join("");
      }
      __name(readString, "readString");
      function readValue(acceptTypeRef) {
        var token2 = next();
        switch (token2) {
          case "'":
          case '"':
            push(token2);
            return readString();
          case "true":
          case "TRUE":
            return true;
          case "false":
          case "FALSE":
            return false;
        }
        try {
          return parseNumber(
            token2,
            /* insideTryCatch */
            true
          );
        } catch (e) {
          if (acceptTypeRef && typeRefRe.test(token2))
            return token2;
          throw illegal(token2, "value");
        }
      }
      __name(readValue, "readValue");
      function readRanges(target, acceptStrings) {
        var token2, start;
        do {
          if (acceptStrings && ((token2 = peek()) === '"' || token2 === "'")) {
            var str = readString();
            target.push(str);
            if (edition >= 2023) {
              throw illegal(str, "id");
            }
          } else {
            try {
              target.push([start = parseId(next()), skip("to", true) ? parseId(next()) : start]);
            } catch (err) {
              if (acceptStrings && typeRefRe.test(token2) && edition >= 2023) {
                target.push(token2);
              } else {
                throw err;
              }
            }
          }
        } while (skip(",", true));
        var dummy = { options: void 0 };
        dummy.setOption = function(name, value) {
          if (this.options === void 0) this.options = {};
          this.options[name] = value;
        };
        ifBlock(
          dummy,
          /* @__PURE__ */ __name(function parseRange_block(token3) {
            if (token3 === "option") {
              parseOption(dummy, token3);
              skip(";");
            } else
              throw illegal(token3);
          }, "parseRange_block"),
          /* @__PURE__ */ __name(function parseRange_line() {
            parseInlineOptions(dummy);
          }, "parseRange_line")
        );
      }
      __name(readRanges, "readRanges");
      function parseNumber(token2, insideTryCatch) {
        var sign = 1;
        if (token2.charAt(0) === "-") {
          sign = -1;
          token2 = token2.substring(1);
        }
        switch (token2) {
          case "inf":
          case "INF":
          case "Inf":
            return sign * Infinity;
          case "nan":
          case "NAN":
          case "Nan":
          case "NaN":
            return NaN;
          case "0":
            return 0;
        }
        if (base10Re.test(token2))
          return sign * parseInt(token2, 10);
        if (base16Re.test(token2))
          return sign * parseInt(token2, 16);
        if (base8Re.test(token2))
          return sign * parseInt(token2, 8);
        if (numberRe.test(token2))
          return sign * parseFloat(token2);
        throw illegal(token2, "number", insideTryCatch);
      }
      __name(parseNumber, "parseNumber");
      function parseId(token2, acceptNegative) {
        switch (token2) {
          case "max":
          case "MAX":
          case "Max":
            return 536870911;
          case "0":
            return 0;
        }
        if (!acceptNegative && token2.charAt(0) === "-")
          throw illegal(token2, "id");
        if (base10NegRe.test(token2))
          return parseInt(token2, 10);
        if (base16NegRe.test(token2))
          return parseInt(token2, 16);
        if (base8NegRe.test(token2))
          return parseInt(token2, 8);
        throw illegal(token2, "id");
      }
      __name(parseId, "parseId");
      function parsePackage() {
        if (pkg !== void 0)
          throw illegal("package");
        pkg = next();
        if (!typeRefRe.test(pkg))
          throw illegal(pkg, "name");
        ptr = ptr.define(pkg);
        skip(";");
      }
      __name(parsePackage, "parsePackage");
      function parseImport() {
        var token2 = peek();
        var whichImports;
        switch (token2) {
          case "weak":
            whichImports = weakImports || (weakImports = []);
            next();
            break;
          case "public":
            next();
          // eslint-disable-next-line no-fallthrough
          default:
            whichImports = imports || (imports = []);
            break;
        }
        token2 = readString();
        skip(";");
        whichImports.push(token2);
      }
      __name(parseImport, "parseImport");
      function parseSyntax() {
        skip("=");
        edition = readString();
        if (edition < 2023)
          throw illegal(edition, "syntax");
        skip(";");
      }
      __name(parseSyntax, "parseSyntax");
      function parseEdition() {
        skip("=");
        edition = readString();
        const supportedEditions = ["2023"];
        if (!supportedEditions.includes(edition))
          throw illegal(edition, "edition");
        skip(";");
      }
      __name(parseEdition, "parseEdition");
      function parseCommon(parent, token2, depth) {
        if (depth === void 0)
          depth = 0;
        switch (token2) {
          case "option":
            parseOption(parent, token2);
            skip(";");
            return true;
          case "message":
            parseType(parent, token2, depth + 1);
            return true;
          case "enum":
            parseEnum(parent, token2);
            return true;
          case "service":
            parseService(parent, token2, depth + 1);
            return true;
          case "extend":
            parseExtension(parent, token2, depth);
            return true;
        }
        return false;
      }
      __name(parseCommon, "parseCommon");
      function ifBlock(obj, fnIf, fnElse) {
        var trailingLine = tn.line;
        if (obj) {
          if (typeof obj.comment !== "string") {
            obj.comment = cmnt();
          }
          obj.filename = parse.filename;
        }
        if (skip("{", true)) {
          var token2;
          while ((token2 = next()) !== "}")
            fnIf(token2);
          skip(";", true);
        } else {
          if (fnElse)
            fnElse();
          skip(";");
          if (obj && (typeof obj.comment !== "string" || preferTrailingComment))
            obj.comment = cmnt(trailingLine) || obj.comment;
        }
      }
      __name(ifBlock, "ifBlock");
      function parseType(parent, token2, depth) {
        if (depth === void 0)
          depth = 0;
        if (depth > util.nestingLimit)
          throw Error("max depth exceeded");
        if (!nameRe.test(token2 = next()))
          throw illegal(token2, "type name");
        var type = new Type(token2);
        ifBlock(type, /* @__PURE__ */ __name(function parseType_block(token3) {
          if (parseCommon(type, token3, depth))
            return;
          switch (token3) {
            case "map":
              parseMapField(type, token3);
              break;
            case "required":
              if (edition !== "proto2")
                throw illegal(token3);
            /* eslint-disable no-fallthrough */
            case "repeated":
              parseField(type, token3, void 0, depth + 1);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField(type, "proto3_optional", void 0, depth + 1);
              } else if (edition !== "proto2") {
                throw illegal(token3);
              } else {
                parseField(type, "optional", void 0, depth + 1);
              }
              break;
            case "oneof":
              parseOneOf(type, token3, depth + 1);
              break;
            case "extensions":
              readRanges(type.extensions || (type.extensions = []));
              break;
            case "reserved":
              readRanges(type.reserved || (type.reserved = []), true);
              break;
            default:
              if (edition === "proto2" || !typeRefRe.test(token3)) {
                throw illegal(token3);
              }
              push(token3);
              parseField(type, "optional", void 0, depth + 1);
              break;
          }
        }, "parseType_block"));
        parent.add(type);
        if (parent === ptr) {
          topLevelObjects.push(type);
        }
      }
      __name(parseType, "parseType");
      function parseField(parent, rule, extend, depth) {
        var type = next();
        if (type === "group") {
          parseGroup(parent, rule, depth);
          return;
        }
        while (type.endsWith(".") || peek().startsWith(".")) {
          type += next();
        }
        if (!typeRefRe.test(type))
          throw illegal(type, "type");
        var name = next();
        if (!nameRe.test(name))
          throw illegal(name, "name");
        name = applyCase(name);
        skip("=");
        var field = new Field(name, parseId(next()), type, rule, extend);
        ifBlock(field, /* @__PURE__ */ __name(function parseField_block(token2) {
          if (token2 === "option") {
            parseOption(field, token2);
            skip(";");
          } else
            throw illegal(token2);
        }, "parseField_block"), /* @__PURE__ */ __name(function parseField_line() {
          parseInlineOptions(field);
        }, "parseField_line"));
        if (rule === "proto3_optional") {
          var oneof = new OneOf("_" + name);
          field.setOption("proto3_optional", true);
          oneof.add(field);
          parent.add(oneof);
        } else {
          parent.add(field);
        }
        if (parent === ptr) {
          topLevelObjects.push(field);
        }
      }
      __name(parseField, "parseField");
      function parseGroup(parent, rule, depth) {
        if (depth === void 0)
          depth = 0;
        if (depth > util.nestingLimit)
          throw Error("max depth exceeded");
        if (edition >= 2023) {
          throw illegal("group");
        }
        var name = next();
        if (!nameRe.test(name))
          throw illegal(name, "name");
        var fieldName = util.lcFirst(name);
        if (name === fieldName)
          name = util.ucFirst(name);
        skip("=");
        var id = parseId(next());
        var type = new Type(name);
        type.group = true;
        var field = new Field(fieldName, id, name, rule);
        field.filename = parse.filename;
        ifBlock(type, /* @__PURE__ */ __name(function parseGroup_block(token2) {
          switch (token2) {
            case "option":
              parseOption(type, token2);
              skip(";");
              break;
            case "required":
            case "repeated":
              parseField(type, token2, void 0, depth + 1);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField(type, "proto3_optional", void 0, depth + 1);
              } else {
                parseField(type, "optional", void 0, depth + 1);
              }
              break;
            case "message":
              parseType(type, token2, depth + 1);
              break;
            case "enum":
              parseEnum(type, token2);
              break;
            case "reserved":
              readRanges(type.reserved || (type.reserved = []), true);
              break;
            /* istanbul ignore next */
            default:
              throw illegal(token2);
          }
        }, "parseGroup_block"));
        parent.add(type).add(field);
      }
      __name(parseGroup, "parseGroup");
      function parseMapField(parent) {
        skip("<");
        var keyType = next();
        if (types2.mapKey[keyType] === void 0)
          throw illegal(keyType, "type");
        skip(",");
        var valueType = next();
        if (!typeRefRe.test(valueType))
          throw illegal(valueType, "type");
        skip(">");
        var name = next();
        if (!nameRe.test(name))
          throw illegal(name, "name");
        skip("=");
        var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);
        ifBlock(field, /* @__PURE__ */ __name(function parseMapField_block(token2) {
          if (token2 === "option") {
            parseOption(field, token2);
            skip(";");
          } else
            throw illegal(token2);
        }, "parseMapField_block"), /* @__PURE__ */ __name(function parseMapField_line() {
          parseInlineOptions(field);
        }, "parseMapField_line"));
        parent.add(field);
      }
      __name(parseMapField, "parseMapField");
      function parseOneOf(parent, token2, depth) {
        if (!nameRe.test(token2 = next()))
          throw illegal(token2, "name");
        var oneof = new OneOf(applyCase(token2));
        ifBlock(oneof, /* @__PURE__ */ __name(function parseOneOf_block(token3) {
          if (token3 === "option") {
            parseOption(oneof, token3);
            skip(";");
          } else {
            push(token3);
            parseField(oneof, "optional", void 0, depth);
          }
        }, "parseOneOf_block"));
        parent.add(oneof);
      }
      __name(parseOneOf, "parseOneOf");
      function parseEnum(parent, token2) {
        if (!nameRe.test(token2 = next()))
          throw illegal(token2, "name");
        var enm = new Enum(token2);
        ifBlock(enm, /* @__PURE__ */ __name(function parseEnum_block(token3) {
          switch (token3) {
            case "option":
              parseOption(enm, token3);
              skip(";");
              break;
            case "reserved":
              readRanges(enm.reserved || (enm.reserved = []), true);
              if (enm.reserved === void 0) enm.reserved = [];
              break;
            default:
              parseEnumValue(enm, token3);
          }
        }, "parseEnum_block"));
        parent.add(enm);
        if (parent === ptr) {
          topLevelObjects.push(enm);
        }
      }
      __name(parseEnum, "parseEnum");
      function parseEnumValue(parent, token2) {
        if (!nameRe.test(token2))
          throw illegal(token2, "name");
        skip("=");
        var value = parseId(next(), true), dummy = {
          options: void 0
        };
        dummy.getOption = function(name) {
          return this.options[name];
        };
        dummy.setOption = function(name, value2) {
          ReflectionObject.prototype.setOption.call(dummy, name, value2);
        };
        dummy.setParsedOption = function() {
          return void 0;
        };
        ifBlock(dummy, /* @__PURE__ */ __name(function parseEnumValue_block(token3) {
          if (token3 === "option") {
            parseOption(dummy, token3);
            skip(";");
          } else
            throw illegal(token3);
        }, "parseEnumValue_block"), /* @__PURE__ */ __name(function parseEnumValue_line() {
          parseInlineOptions(dummy);
        }, "parseEnumValue_line"));
        parent.add(token2, value, dummy.comment, dummy.parsedOptions || dummy.options);
      }
      __name(parseEnumValue, "parseEnumValue");
      function parseOption(parent, token2) {
        var option;
        var propName;
        var isOption = true;
        if (token2 === "option") {
          token2 = next();
        }
        while (token2 !== "=") {
          if (token2 === "(") {
            var parensValue = next();
            skip(")");
            token2 = "(" + parensValue + ")";
          }
          if (isOption) {
            isOption = false;
            if (token2.includes(".") && !token2.includes("(")) {
              var tokens = token2.split(".");
              option = tokens[0] + ".";
              token2 = tokens[1];
              continue;
            }
            option = token2;
          } else {
            propName = propName ? propName += token2 : token2;
          }
          token2 = next();
        }
        var name = propName ? option.concat(propName) : option;
        var optionValue = parseOptionValue(parent, name);
        propName = propName && propName[0] === "." ? propName.slice(1) : propName;
        option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option;
        setParsedOption(parent, option, optionValue, propName);
      }
      __name(parseOption, "parseOption");
      function parseOptionValue(parent, name, depth) {
        if (depth === void 0)
          depth = 0;
        if (depth > util.recursionLimit)
          throw Error("max depth exceeded");
        if (skip("{", true)) {
          var objectResult = {};
          while (!skip("}", true)) {
            if (!nameRe.test(token = next())) {
              throw illegal(token, "name");
            }
            if (token === null) {
              throw illegal(token, "end of input");
            }
            var value;
            var propName = token;
            skip(":", true);
            if (peek() === "{") {
              value = parseOptionValue(parent, name + "." + token, depth + 1);
            } else if (peek() === "[") {
              value = [];
              var lastValue;
              if (skip("[", true)) {
                do {
                  lastValue = readValue(true);
                  value.push(lastValue);
                } while (skip(",", true));
                skip("]");
                if (typeof lastValue !== "undefined") {
                  setOption(parent, name + "." + token, lastValue);
                }
              }
            } else {
              value = readValue(true);
              setOption(parent, name + "." + token, value);
            }
            var prevValue = objectResult[propName];
            if (prevValue)
              value = [].concat(prevValue).concat(value);
            if (propName !== "__proto__")
              objectResult[propName] = value;
            skip(",", true);
            skip(";", true);
          }
          return objectResult;
        }
        var simpleValue = readValue(true);
        setOption(parent, name, simpleValue);
        return simpleValue;
      }
      __name(parseOptionValue, "parseOptionValue");
      function setOption(parent, name, value) {
        if (ptr === parent && /^features\./.test(name)) {
          topLevelOptions[name] = value;
          return;
        }
        if (parent.setOption)
          parent.setOption(name, value);
      }
      __name(setOption, "setOption");
      function setParsedOption(parent, name, value, propName) {
        if (parent.setParsedOption)
          parent.setParsedOption(name, value, propName);
      }
      __name(setParsedOption, "setParsedOption");
      function parseInlineOptions(parent) {
        if (skip("[", true)) {
          do {
            parseOption(parent, "option");
          } while (skip(",", true));
          skip("]");
        }
        return parent;
      }
      __name(parseInlineOptions, "parseInlineOptions");
      function parseService(parent, token2, depth) {
        if (depth === void 0)
          depth = 0;
        if (depth > util.recursionLimit)
          throw Error("max depth exceeded");
        if (!nameRe.test(token2 = next()))
          throw illegal(token2, "service name");
        var service = new Service(token2);
        ifBlock(service, /* @__PURE__ */ __name(function parseService_block(token3) {
          if (parseCommon(service, token3, depth)) {
            return;
          }
          if (token3 === "rpc")
            parseMethod(service, token3);
          else
            throw illegal(token3);
        }, "parseService_block"));
        parent.add(service);
        if (parent === ptr) {
          topLevelObjects.push(service);
        }
      }
      __name(parseService, "parseService");
      function parseMethod(parent, token2) {
        var commentText = cmnt();
        var type = token2;
        if (!nameRe.test(token2 = next()))
          throw illegal(token2, "name");
        var name = token2, requestType, requestStream, responseType, responseStream;
        skip("(");
        if (skip("stream", true))
          requestStream = true;
        if (!typeRefRe.test(token2 = next()))
          throw illegal(token2);
        requestType = token2;
        skip(")");
        skip("returns");
        skip("(");
        if (skip("stream", true))
          responseStream = true;
        if (!typeRefRe.test(token2 = next()))
          throw illegal(token2);
        responseType = token2;
        skip(")");
        var method = new Method(name, type, requestType, responseType, requestStream, responseStream);
        method.comment = commentText;
        ifBlock(method, /* @__PURE__ */ __name(function parseMethod_block(token3) {
          if (token3 === "option") {
            parseOption(method, token3);
            skip(";");
          } else
            throw illegal(token3);
        }, "parseMethod_block"));
        parent.add(method);
      }
      __name(parseMethod, "parseMethod");
      function parseExtension(parent, token2, depth) {
        if (!typeRefRe.test(token2 = next()))
          throw illegal(token2, "reference");
        var reference = token2;
        ifBlock(null, /* @__PURE__ */ __name(function parseExtension_block(token3) {
          switch (token3) {
            case "required":
            case "repeated":
              parseField(parent, token3, reference, depth + 1);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField(parent, "proto3_optional", reference, depth + 1);
              } else {
                parseField(parent, "optional", reference, depth + 1);
              }
              break;
            default:
              if (edition === "proto2" || !typeRefRe.test(token3))
                throw illegal(token3);
              push(token3);
              parseField(parent, "optional", reference, depth + 1);
              break;
          }
        }, "parseExtension_block"));
      }
      __name(parseExtension, "parseExtension");
      var token;
      while ((token = next()) !== null) {
        switch (token) {
          case "package":
            if (!head)
              throw illegal(token);
            parsePackage();
            break;
          case "import":
            if (!head)
              throw illegal(token);
            parseImport();
            break;
          case "syntax":
            if (!head)
              throw illegal(token);
            parseSyntax();
            break;
          case "edition":
            if (!head)
              throw illegal(token);
            parseEdition();
            break;
          case "option":
            parseOption(ptr, token);
            skip(";", true);
            break;
          default:
            if (parseCommon(ptr, token, 0)) {
              head = false;
              continue;
            }
            throw illegal(token);
        }
      }
      resolveFileFeatures();
      parse.filename = null;
      return {
        "package": pkg,
        "imports": imports,
        weakImports,
        root
      };
    }
    __name(parse, "parse");
  }
});

// node_modules/protobufjs/src/common.js
var require_common = __commonJS({
  "node_modules/protobufjs/src/common.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = common;
    var commonRe = /\/|\./;
    function common(name, json) {
      if (!commonRe.test(name)) {
        name = "google/protobuf/" + name + ".proto";
        json = { nested: { google: { nested: { protobuf: { nested: json } } } } };
      }
      common[name] = json;
    }
    __name(common, "common");
    common("any", {
      /**
       * Properties of a google.protobuf.Any message.
       * @interface IAny
       * @type {Object}
       * @property {string} [typeUrl]
       * @property {Uint8Array} [bytes]
       * @memberof common
       */
      Any: {
        fields: {
          type_url: {
            type: "string",
            id: 1
          },
          value: {
            type: "bytes",
            id: 2
          }
        }
      }
    });
    var timeType;
    common("duration", {
      /**
       * Properties of a google.protobuf.Duration message.
       * @interface IDuration
       * @type {Object}
       * @property {number|Long} [seconds]
       * @property {number} [nanos]
       * @memberof common
       */
      Duration: timeType = {
        fields: {
          seconds: {
            type: "int64",
            id: 1
          },
          nanos: {
            type: "int32",
            id: 2
          }
        }
      }
    });
    common("timestamp", {
      /**
       * Properties of a google.protobuf.Timestamp message.
       * @interface ITimestamp
       * @type {Object}
       * @property {number|Long} [seconds]
       * @property {number} [nanos]
       * @memberof common
       */
      Timestamp: timeType
    });
    common("empty", {
      /**
       * Properties of a google.protobuf.Empty message.
       * @interface IEmpty
       * @memberof common
       */
      Empty: {
        fields: {}
      }
    });
    common("struct", {
      /**
       * Properties of a google.protobuf.Struct message.
       * @interface IStruct
       * @type {Object}
       * @property {Object.<string,IValue>} [fields]
       * @memberof common
       */
      Struct: {
        fields: {
          fields: {
            keyType: "string",
            type: "Value",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.Value message.
       * @interface IValue
       * @type {Object}
       * @property {string} [kind]
       * @property {0} [nullValue]
       * @property {number} [numberValue]
       * @property {string} [stringValue]
       * @property {boolean} [boolValue]
       * @property {IStruct} [structValue]
       * @property {IListValue} [listValue]
       * @memberof common
       */
      Value: {
        oneofs: {
          kind: {
            oneof: [
              "nullValue",
              "numberValue",
              "stringValue",
              "boolValue",
              "structValue",
              "listValue"
            ]
          }
        },
        fields: {
          nullValue: {
            type: "NullValue",
            id: 1
          },
          numberValue: {
            type: "double",
            id: 2
          },
          stringValue: {
            type: "string",
            id: 3
          },
          boolValue: {
            type: "bool",
            id: 4
          },
          structValue: {
            type: "Struct",
            id: 5
          },
          listValue: {
            type: "ListValue",
            id: 6
          }
        }
      },
      NullValue: {
        values: {
          NULL_VALUE: 0
        }
      },
      /**
       * Properties of a google.protobuf.ListValue message.
       * @interface IListValue
       * @type {Object}
       * @property {Array.<IValue>} [values]
       * @memberof common
       */
      ListValue: {
        fields: {
          values: {
            rule: "repeated",
            type: "Value",
            id: 1
          }
        }
      }
    });
    common("wrappers", {
      /**
       * Properties of a google.protobuf.DoubleValue message.
       * @interface IDoubleValue
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      DoubleValue: {
        fields: {
          value: {
            type: "double",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.FloatValue message.
       * @interface IFloatValue
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      FloatValue: {
        fields: {
          value: {
            type: "float",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.Int64Value message.
       * @interface IInt64Value
       * @type {Object}
       * @property {number|Long} [value]
       * @memberof common
       */
      Int64Value: {
        fields: {
          value: {
            type: "int64",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.UInt64Value message.
       * @interface IUInt64Value
       * @type {Object}
       * @property {number|Long} [value]
       * @memberof common
       */
      UInt64Value: {
        fields: {
          value: {
            type: "uint64",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.Int32Value message.
       * @interface IInt32Value
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      Int32Value: {
        fields: {
          value: {
            type: "int32",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.UInt32Value message.
       * @interface IUInt32Value
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      UInt32Value: {
        fields: {
          value: {
            type: "uint32",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.BoolValue message.
       * @interface IBoolValue
       * @type {Object}
       * @property {boolean} [value]
       * @memberof common
       */
      BoolValue: {
        fields: {
          value: {
            type: "bool",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.StringValue message.
       * @interface IStringValue
       * @type {Object}
       * @property {string} [value]
       * @memberof common
       */
      StringValue: {
        fields: {
          value: {
            type: "string",
            id: 1
          }
        }
      },
      /**
       * Properties of a google.protobuf.BytesValue message.
       * @interface IBytesValue
       * @type {Object}
       * @property {Uint8Array} [value]
       * @memberof common
       */
      BytesValue: {
        fields: {
          value: {
            type: "bytes",
            id: 1
          }
        }
      }
    });
    common("field_mask", {
      /**
       * Properties of a google.protobuf.FieldMask message.
       * @interface IDoubleValue
       * @type {Object}
       * @property {number} [value]
       * @memberof common
       */
      FieldMask: {
        fields: {
          paths: {
            rule: "repeated",
            type: "string",
            id: 1
          }
        }
      }
    });
    common.get = /* @__PURE__ */ __name(function get(file) {
      return common[file] || null;
    }, "get");
  }
});

// node_modules/protobufjs/src/index.js
var require_src4 = __commonJS({
  "node_modules/protobufjs/src/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var protobuf = module.exports = require_index_light();
    protobuf.build = "full";
    protobuf.tokenize = require_tokenize();
    protobuf.parse = require_parse();
    protobuf.common = require_common();
    protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);
  }
});

// node_modules/protobufjs/index.js
var require_protobufjs = __commonJS({
  "node_modules/protobufjs/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = require_src4();
  }
});

// node_modules/protobufjs/google/protobuf/descriptor.json
var require_descriptor = __commonJS({
  "node_modules/protobufjs/google/protobuf/descriptor.json"(exports, module) {
    module.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              options: {
                go_package: "google.golang.org/protobuf/types/descriptorpb",
                java_package: "com.google.protobuf",
                java_outer_classname: "DescriptorProtos",
                csharp_namespace: "Google.Protobuf.Reflection",
                objc_class_prefix: "GPB",
                cc_enable_arenas: true,
                optimize_for: "SPEED"
              },
              nested: {
                FileDescriptorSet: {
                  edition: "proto2",
                  fields: {
                    file: {
                      rule: "repeated",
                      type: "FileDescriptorProto",
                      id: 1
                    }
                  },
                  extensions: [
                    [
                      536e6,
                      536e6
                    ]
                  ]
                },
                Edition: {
                  edition: "proto2",
                  values: {
                    EDITION_UNKNOWN: 0,
                    EDITION_LEGACY: 900,
                    EDITION_PROTO2: 998,
                    EDITION_PROTO3: 999,
                    EDITION_2023: 1e3,
                    EDITION_2024: 1001,
                    EDITION_1_TEST_ONLY: 1,
                    EDITION_2_TEST_ONLY: 2,
                    EDITION_99997_TEST_ONLY: 99997,
                    EDITION_99998_TEST_ONLY: 99998,
                    EDITION_99999_TEST_ONLY: 99999,
                    EDITION_MAX: 2147483647
                  }
                },
                FileDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    package: {
                      type: "string",
                      id: 2
                    },
                    dependency: {
                      rule: "repeated",
                      type: "string",
                      id: 3
                    },
                    publicDependency: {
                      rule: "repeated",
                      type: "int32",
                      id: 10
                    },
                    weakDependency: {
                      rule: "repeated",
                      type: "int32",
                      id: 11
                    },
                    optionDependency: {
                      rule: "repeated",
                      type: "string",
                      id: 15
                    },
                    messageType: {
                      rule: "repeated",
                      type: "DescriptorProto",
                      id: 4
                    },
                    enumType: {
                      rule: "repeated",
                      type: "EnumDescriptorProto",
                      id: 5
                    },
                    service: {
                      rule: "repeated",
                      type: "ServiceDescriptorProto",
                      id: 6
                    },
                    extension: {
                      rule: "repeated",
                      type: "FieldDescriptorProto",
                      id: 7
                    },
                    options: {
                      type: "FileOptions",
                      id: 8
                    },
                    sourceCodeInfo: {
                      type: "SourceCodeInfo",
                      id: 9
                    },
                    syntax: {
                      type: "string",
                      id: 12
                    },
                    edition: {
                      type: "Edition",
                      id: 14
                    }
                  }
                },
                DescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    field: {
                      rule: "repeated",
                      type: "FieldDescriptorProto",
                      id: 2
                    },
                    extension: {
                      rule: "repeated",
                      type: "FieldDescriptorProto",
                      id: 6
                    },
                    nestedType: {
                      rule: "repeated",
                      type: "DescriptorProto",
                      id: 3
                    },
                    enumType: {
                      rule: "repeated",
                      type: "EnumDescriptorProto",
                      id: 4
                    },
                    extensionRange: {
                      rule: "repeated",
                      type: "ExtensionRange",
                      id: 5
                    },
                    oneofDecl: {
                      rule: "repeated",
                      type: "OneofDescriptorProto",
                      id: 8
                    },
                    options: {
                      type: "MessageOptions",
                      id: 7
                    },
                    reservedRange: {
                      rule: "repeated",
                      type: "ReservedRange",
                      id: 9
                    },
                    reservedName: {
                      rule: "repeated",
                      type: "string",
                      id: 10
                    },
                    visibility: {
                      type: "SymbolVisibility",
                      id: 11
                    }
                  },
                  nested: {
                    ExtensionRange: {
                      fields: {
                        start: {
                          type: "int32",
                          id: 1
                        },
                        end: {
                          type: "int32",
                          id: 2
                        },
                        options: {
                          type: "ExtensionRangeOptions",
                          id: 3
                        }
                      }
                    },
                    ReservedRange: {
                      fields: {
                        start: {
                          type: "int32",
                          id: 1
                        },
                        end: {
                          type: "int32",
                          id: 2
                        }
                      }
                    }
                  }
                },
                ExtensionRangeOptions: {
                  edition: "proto2",
                  fields: {
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    },
                    declaration: {
                      rule: "repeated",
                      type: "Declaration",
                      id: 2,
                      options: {
                        retention: "RETENTION_SOURCE"
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 50
                    },
                    verification: {
                      type: "VerificationState",
                      id: 3,
                      options: {
                        default: "UNVERIFIED",
                        retention: "RETENTION_SOURCE"
                      }
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  nested: {
                    Declaration: {
                      fields: {
                        number: {
                          type: "int32",
                          id: 1
                        },
                        fullName: {
                          type: "string",
                          id: 2
                        },
                        type: {
                          type: "string",
                          id: 3
                        },
                        reserved: {
                          type: "bool",
                          id: 5
                        },
                        repeated: {
                          type: "bool",
                          id: 6
                        }
                      },
                      reserved: [
                        [
                          4,
                          4
                        ]
                      ]
                    },
                    VerificationState: {
                      values: {
                        DECLARATION: 0,
                        UNVERIFIED: 1
                      }
                    }
                  }
                },
                FieldDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    number: {
                      type: "int32",
                      id: 3
                    },
                    label: {
                      type: "Label",
                      id: 4
                    },
                    type: {
                      type: "Type",
                      id: 5
                    },
                    typeName: {
                      type: "string",
                      id: 6
                    },
                    extendee: {
                      type: "string",
                      id: 2
                    },
                    defaultValue: {
                      type: "string",
                      id: 7
                    },
                    oneofIndex: {
                      type: "int32",
                      id: 9
                    },
                    jsonName: {
                      type: "string",
                      id: 10
                    },
                    options: {
                      type: "FieldOptions",
                      id: 8
                    },
                    proto3Optional: {
                      type: "bool",
                      id: 17
                    }
                  },
                  nested: {
                    Type: {
                      values: {
                        TYPE_DOUBLE: 1,
                        TYPE_FLOAT: 2,
                        TYPE_INT64: 3,
                        TYPE_UINT64: 4,
                        TYPE_INT32: 5,
                        TYPE_FIXED64: 6,
                        TYPE_FIXED32: 7,
                        TYPE_BOOL: 8,
                        TYPE_STRING: 9,
                        TYPE_GROUP: 10,
                        TYPE_MESSAGE: 11,
                        TYPE_BYTES: 12,
                        TYPE_UINT32: 13,
                        TYPE_ENUM: 14,
                        TYPE_SFIXED32: 15,
                        TYPE_SFIXED64: 16,
                        TYPE_SINT32: 17,
                        TYPE_SINT64: 18
                      }
                    },
                    Label: {
                      values: {
                        LABEL_OPTIONAL: 1,
                        LABEL_REPEATED: 3,
                        LABEL_REQUIRED: 2
                      }
                    }
                  }
                },
                OneofDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    options: {
                      type: "OneofOptions",
                      id: 2
                    }
                  }
                },
                EnumDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      rule: "repeated",
                      type: "EnumValueDescriptorProto",
                      id: 2
                    },
                    options: {
                      type: "EnumOptions",
                      id: 3
                    },
                    reservedRange: {
                      rule: "repeated",
                      type: "EnumReservedRange",
                      id: 4
                    },
                    reservedName: {
                      rule: "repeated",
                      type: "string",
                      id: 5
                    },
                    visibility: {
                      type: "SymbolVisibility",
                      id: 6
                    }
                  },
                  nested: {
                    EnumReservedRange: {
                      fields: {
                        start: {
                          type: "int32",
                          id: 1
                        },
                        end: {
                          type: "int32",
                          id: 2
                        }
                      }
                    }
                  }
                },
                EnumValueDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    number: {
                      type: "int32",
                      id: 2
                    },
                    options: {
                      type: "EnumValueOptions",
                      id: 3
                    }
                  }
                },
                ServiceDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    method: {
                      rule: "repeated",
                      type: "MethodDescriptorProto",
                      id: 2
                    },
                    options: {
                      type: "ServiceOptions",
                      id: 3
                    }
                  }
                },
                MethodDescriptorProto: {
                  edition: "proto2",
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    inputType: {
                      type: "string",
                      id: 2
                    },
                    outputType: {
                      type: "string",
                      id: 3
                    },
                    options: {
                      type: "MethodOptions",
                      id: 4
                    },
                    clientStreaming: {
                      type: "bool",
                      id: 5
                    },
                    serverStreaming: {
                      type: "bool",
                      id: 6
                    }
                  }
                },
                FileOptions: {
                  edition: "proto2",
                  fields: {
                    javaPackage: {
                      type: "string",
                      id: 1
                    },
                    javaOuterClassname: {
                      type: "string",
                      id: 8
                    },
                    javaMultipleFiles: {
                      type: "bool",
                      id: 10
                    },
                    javaGenerateEqualsAndHash: {
                      type: "bool",
                      id: 20,
                      options: {
                        deprecated: true
                      }
                    },
                    javaStringCheckUtf8: {
                      type: "bool",
                      id: 27
                    },
                    optimizeFor: {
                      type: "OptimizeMode",
                      id: 9,
                      options: {
                        default: "SPEED"
                      }
                    },
                    goPackage: {
                      type: "string",
                      id: 11
                    },
                    ccGenericServices: {
                      type: "bool",
                      id: 16
                    },
                    javaGenericServices: {
                      type: "bool",
                      id: 17
                    },
                    pyGenericServices: {
                      type: "bool",
                      id: 18
                    },
                    deprecated: {
                      type: "bool",
                      id: 23
                    },
                    ccEnableArenas: {
                      type: "bool",
                      id: 31,
                      options: {
                        default: true
                      }
                    },
                    objcClassPrefix: {
                      type: "string",
                      id: 36
                    },
                    csharpNamespace: {
                      type: "string",
                      id: 37
                    },
                    swiftPrefix: {
                      type: "string",
                      id: 39
                    },
                    phpClassPrefix: {
                      type: "string",
                      id: 40
                    },
                    phpNamespace: {
                      type: "string",
                      id: 41
                    },
                    phpMetadataNamespace: {
                      type: "string",
                      id: 44
                    },
                    rubyPackage: {
                      type: "string",
                      id: 45
                    },
                    features: {
                      type: "FeatureSet",
                      id: 50
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      42,
                      42
                    ],
                    [
                      38,
                      38
                    ],
                    "php_generic_services"
                  ],
                  nested: {
                    OptimizeMode: {
                      values: {
                        SPEED: 1,
                        CODE_SIZE: 2,
                        LITE_RUNTIME: 3
                      }
                    }
                  }
                },
                MessageOptions: {
                  edition: "proto2",
                  fields: {
                    messageSetWireFormat: {
                      type: "bool",
                      id: 1
                    },
                    noStandardDescriptorAccessor: {
                      type: "bool",
                      id: 2
                    },
                    deprecated: {
                      type: "bool",
                      id: 3
                    },
                    mapEntry: {
                      type: "bool",
                      id: 7
                    },
                    deprecatedLegacyJsonFieldConflicts: {
                      type: "bool",
                      id: 11,
                      options: {
                        deprecated: true
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 12
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      4,
                      4
                    ],
                    [
                      5,
                      5
                    ],
                    [
                      6,
                      6
                    ],
                    [
                      8,
                      8
                    ],
                    [
                      9,
                      9
                    ]
                  ]
                },
                FieldOptions: {
                  edition: "proto2",
                  fields: {
                    ctype: {
                      type: "CType",
                      id: 1,
                      options: {
                        default: "STRING"
                      }
                    },
                    packed: {
                      type: "bool",
                      id: 2
                    },
                    jstype: {
                      type: "JSType",
                      id: 6,
                      options: {
                        default: "JS_NORMAL"
                      }
                    },
                    lazy: {
                      type: "bool",
                      id: 5
                    },
                    unverifiedLazy: {
                      type: "bool",
                      id: 15
                    },
                    deprecated: {
                      type: "bool",
                      id: 3
                    },
                    weak: {
                      type: "bool",
                      id: 10,
                      options: {
                        deprecated: true
                      }
                    },
                    debugRedact: {
                      type: "bool",
                      id: 16
                    },
                    retention: {
                      type: "OptionRetention",
                      id: 17
                    },
                    targets: {
                      rule: "repeated",
                      type: "OptionTargetType",
                      id: 19
                    },
                    editionDefaults: {
                      rule: "repeated",
                      type: "EditionDefault",
                      id: 20
                    },
                    features: {
                      type: "FeatureSet",
                      id: 21
                    },
                    featureSupport: {
                      type: "FeatureSupport",
                      id: 22
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      4,
                      4
                    ],
                    [
                      18,
                      18
                    ]
                  ],
                  nested: {
                    CType: {
                      values: {
                        STRING: 0,
                        CORD: 1,
                        STRING_PIECE: 2
                      }
                    },
                    JSType: {
                      values: {
                        JS_NORMAL: 0,
                        JS_STRING: 1,
                        JS_NUMBER: 2
                      }
                    },
                    OptionRetention: {
                      values: {
                        RETENTION_UNKNOWN: 0,
                        RETENTION_RUNTIME: 1,
                        RETENTION_SOURCE: 2
                      }
                    },
                    OptionTargetType: {
                      values: {
                        TARGET_TYPE_UNKNOWN: 0,
                        TARGET_TYPE_FILE: 1,
                        TARGET_TYPE_EXTENSION_RANGE: 2,
                        TARGET_TYPE_MESSAGE: 3,
                        TARGET_TYPE_FIELD: 4,
                        TARGET_TYPE_ONEOF: 5,
                        TARGET_TYPE_ENUM: 6,
                        TARGET_TYPE_ENUM_ENTRY: 7,
                        TARGET_TYPE_SERVICE: 8,
                        TARGET_TYPE_METHOD: 9
                      }
                    },
                    EditionDefault: {
                      fields: {
                        edition: {
                          type: "Edition",
                          id: 3
                        },
                        value: {
                          type: "string",
                          id: 2
                        }
                      }
                    },
                    FeatureSupport: {
                      fields: {
                        editionIntroduced: {
                          type: "Edition",
                          id: 1
                        },
                        editionDeprecated: {
                          type: "Edition",
                          id: 2
                        },
                        deprecationWarning: {
                          type: "string",
                          id: 3
                        },
                        editionRemoved: {
                          type: "Edition",
                          id: 4
                        }
                      }
                    }
                  }
                },
                OneofOptions: {
                  edition: "proto2",
                  fields: {
                    features: {
                      type: "FeatureSet",
                      id: 1
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ]
                },
                EnumOptions: {
                  edition: "proto2",
                  fields: {
                    allowAlias: {
                      type: "bool",
                      id: 2
                    },
                    deprecated: {
                      type: "bool",
                      id: 3
                    },
                    deprecatedLegacyJsonFieldConflicts: {
                      type: "bool",
                      id: 6,
                      options: {
                        deprecated: true
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 7
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  reserved: [
                    [
                      5,
                      5
                    ]
                  ]
                },
                EnumValueOptions: {
                  edition: "proto2",
                  fields: {
                    deprecated: {
                      type: "bool",
                      id: 1
                    },
                    features: {
                      type: "FeatureSet",
                      id: 2
                    },
                    debugRedact: {
                      type: "bool",
                      id: 3
                    },
                    featureSupport: {
                      type: "FieldOptions.FeatureSupport",
                      id: 4
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ]
                },
                ServiceOptions: {
                  edition: "proto2",
                  fields: {
                    features: {
                      type: "FeatureSet",
                      id: 34
                    },
                    deprecated: {
                      type: "bool",
                      id: 33
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ]
                },
                MethodOptions: {
                  edition: "proto2",
                  fields: {
                    deprecated: {
                      type: "bool",
                      id: 33
                    },
                    idempotencyLevel: {
                      type: "IdempotencyLevel",
                      id: 34,
                      options: {
                        default: "IDEMPOTENCY_UNKNOWN"
                      }
                    },
                    features: {
                      type: "FeatureSet",
                      id: 35
                    },
                    uninterpretedOption: {
                      rule: "repeated",
                      type: "UninterpretedOption",
                      id: 999
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      536870911
                    ]
                  ],
                  nested: {
                    IdempotencyLevel: {
                      values: {
                        IDEMPOTENCY_UNKNOWN: 0,
                        NO_SIDE_EFFECTS: 1,
                        IDEMPOTENT: 2
                      }
                    }
                  }
                },
                UninterpretedOption: {
                  edition: "proto2",
                  fields: {
                    name: {
                      rule: "repeated",
                      type: "NamePart",
                      id: 2
                    },
                    identifierValue: {
                      type: "string",
                      id: 3
                    },
                    positiveIntValue: {
                      type: "uint64",
                      id: 4
                    },
                    negativeIntValue: {
                      type: "int64",
                      id: 5
                    },
                    doubleValue: {
                      type: "double",
                      id: 6
                    },
                    stringValue: {
                      type: "bytes",
                      id: 7
                    },
                    aggregateValue: {
                      type: "string",
                      id: 8
                    }
                  },
                  nested: {
                    NamePart: {
                      fields: {
                        namePart: {
                          rule: "required",
                          type: "string",
                          id: 1
                        },
                        isExtension: {
                          rule: "required",
                          type: "bool",
                          id: 2
                        }
                      }
                    }
                  }
                },
                FeatureSet: {
                  edition: "proto2",
                  fields: {
                    fieldPresence: {
                      type: "FieldPresence",
                      id: 1,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_2023",
                        "edition_defaults.value": "EXPLICIT"
                      }
                    },
                    enumType: {
                      type: "EnumType",
                      id: 2,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "OPEN"
                      }
                    },
                    repeatedFieldEncoding: {
                      type: "RepeatedFieldEncoding",
                      id: 3,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "PACKED"
                      }
                    },
                    utf8Validation: {
                      type: "Utf8Validation",
                      id: 4,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "VERIFY"
                      }
                    },
                    messageEncoding: {
                      type: "MessageEncoding",
                      id: 5,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_LEGACY",
                        "edition_defaults.value": "LENGTH_PREFIXED"
                      }
                    },
                    jsonFormat: {
                      type: "JsonFormat",
                      id: 6,
                      options: {
                        retention: "RETENTION_RUNTIME",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2023",
                        "edition_defaults.edition": "EDITION_PROTO3",
                        "edition_defaults.value": "ALLOW"
                      }
                    },
                    enforceNamingStyle: {
                      type: "EnforceNamingStyle",
                      id: 7,
                      options: {
                        retention: "RETENTION_SOURCE",
                        targets: "TARGET_TYPE_METHOD",
                        "feature_support.edition_introduced": "EDITION_2024",
                        "edition_defaults.edition": "EDITION_2024",
                        "edition_defaults.value": "STYLE2024"
                      }
                    },
                    defaultSymbolVisibility: {
                      type: "VisibilityFeature.DefaultSymbolVisibility",
                      id: 8,
                      options: {
                        retention: "RETENTION_SOURCE",
                        targets: "TARGET_TYPE_FILE",
                        "feature_support.edition_introduced": "EDITION_2024",
                        "edition_defaults.edition": "EDITION_2024",
                        "edition_defaults.value": "EXPORT_TOP_LEVEL"
                      }
                    }
                  },
                  extensions: [
                    [
                      1e3,
                      9994
                    ],
                    [
                      9995,
                      9999
                    ],
                    [
                      1e4,
                      1e4
                    ]
                  ],
                  reserved: [
                    [
                      999,
                      999
                    ]
                  ],
                  nested: {
                    FieldPresence: {
                      values: {
                        FIELD_PRESENCE_UNKNOWN: 0,
                        EXPLICIT: 1,
                        IMPLICIT: 2,
                        LEGACY_REQUIRED: 3
                      }
                    },
                    EnumType: {
                      values: {
                        ENUM_TYPE_UNKNOWN: 0,
                        OPEN: 1,
                        CLOSED: 2
                      }
                    },
                    RepeatedFieldEncoding: {
                      values: {
                        REPEATED_FIELD_ENCODING_UNKNOWN: 0,
                        PACKED: 1,
                        EXPANDED: 2
                      }
                    },
                    Utf8Validation: {
                      values: {
                        UTF8_VALIDATION_UNKNOWN: 0,
                        VERIFY: 2,
                        NONE: 3
                      }
                    },
                    MessageEncoding: {
                      values: {
                        MESSAGE_ENCODING_UNKNOWN: 0,
                        LENGTH_PREFIXED: 1,
                        DELIMITED: 2
                      }
                    },
                    JsonFormat: {
                      values: {
                        JSON_FORMAT_UNKNOWN: 0,
                        ALLOW: 1,
                        LEGACY_BEST_EFFORT: 2
                      }
                    },
                    EnforceNamingStyle: {
                      values: {
                        ENFORCE_NAMING_STYLE_UNKNOWN: 0,
                        STYLE2024: 1,
                        STYLE_LEGACY: 2
                      }
                    },
                    VisibilityFeature: {
                      fields: {},
                      reserved: [
                        [
                          1,
                          536870911
                        ]
                      ],
                      nested: {
                        DefaultSymbolVisibility: {
                          values: {
                            DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 0,
                            EXPORT_ALL: 1,
                            EXPORT_TOP_LEVEL: 2,
                            LOCAL_ALL: 3,
                            STRICT: 4
                          }
                        }
                      }
                    }
                  }
                },
                FeatureSetDefaults: {
                  edition: "proto2",
                  fields: {
                    defaults: {
                      rule: "repeated",
                      type: "FeatureSetEditionDefault",
                      id: 1
                    },
                    minimumEdition: {
                      type: "Edition",
                      id: 4
                    },
                    maximumEdition: {
                      type: "Edition",
                      id: 5
                    }
                  },
                  nested: {
                    FeatureSetEditionDefault: {
                      fields: {
                        edition: {
                          type: "Edition",
                          id: 3
                        },
                        overridableFeatures: {
                          type: "FeatureSet",
                          id: 4
                        },
                        fixedFeatures: {
                          type: "FeatureSet",
                          id: 5
                        }
                      },
                      reserved: [
                        [
                          1,
                          1
                        ],
                        [
                          2,
                          2
                        ],
                        "features"
                      ]
                    }
                  }
                },
                SourceCodeInfo: {
                  edition: "proto2",
                  fields: {
                    location: {
                      rule: "repeated",
                      type: "Location",
                      id: 1
                    }
                  },
                  extensions: [
                    [
                      536e6,
                      536e6
                    ]
                  ],
                  nested: {
                    Location: {
                      fields: {
                        path: {
                          rule: "repeated",
                          type: "int32",
                          id: 1,
                          options: {
                            packed: true
                          }
                        },
                        span: {
                          rule: "repeated",
                          type: "int32",
                          id: 2,
                          options: {
                            packed: true
                          }
                        },
                        leadingComments: {
                          type: "string",
                          id: 3
                        },
                        trailingComments: {
                          type: "string",
                          id: 4
                        },
                        leadingDetachedComments: {
                          rule: "repeated",
                          type: "string",
                          id: 6
                        }
                      }
                    }
                  }
                },
                GeneratedCodeInfo: {
                  edition: "proto2",
                  fields: {
                    annotation: {
                      rule: "repeated",
                      type: "Annotation",
                      id: 1
                    }
                  },
                  nested: {
                    Annotation: {
                      fields: {
                        path: {
                          rule: "repeated",
                          type: "int32",
                          id: 1,
                          options: {
                            packed: true
                          }
                        },
                        sourceFile: {
                          type: "string",
                          id: 2
                        },
                        begin: {
                          type: "int32",
                          id: 3
                        },
                        end: {
                          type: "int32",
                          id: 4
                        },
                        semantic: {
                          type: "Semantic",
                          id: 5
                        }
                      },
                      nested: {
                        Semantic: {
                          values: {
                            NONE: 0,
                            SET: 1,
                            ALIAS: 2
                          }
                        }
                      }
                    }
                  }
                },
                SymbolVisibility: {
                  edition: "proto2",
                  values: {
                    VISIBILITY_UNSET: 0,
                    VISIBILITY_LOCAL: 1,
                    VISIBILITY_EXPORT: 2
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/protobufjs/ext/descriptor/index.js
var require_descriptor2 = __commonJS({
  "node_modules/protobufjs/ext/descriptor/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var $protobuf = require_protobufjs();
    module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(require_descriptor()).lookup(".google.protobuf");
    var Namespace = $protobuf.Namespace;
    var Root = $protobuf.Root;
    var Enum = $protobuf.Enum;
    var Type = $protobuf.Type;
    var Field = $protobuf.Field;
    var MapField = $protobuf.MapField;
    var OneOf = $protobuf.OneOf;
    var Service = $protobuf.Service;
    var Method = $protobuf.Method;
    var patterns = $protobuf.util.patterns;
    var numberRe = patterns.numberRe;
    var typeRefRe = patterns.typeRefRe;
    Root.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor) {
      if (typeof descriptor.length === "number")
        descriptor = exports.FileDescriptorSet.decode(descriptor);
      var root = new Root();
      if (descriptor.file) {
        var fileDescriptor, filePackage;
        for (var j = 0, i; j < descriptor.file.length; ++j) {
          filePackage = root;
          if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length)
            filePackage = root.define(fileDescriptor["package"]);
          var edition = editionFromDescriptor(fileDescriptor);
          if (fileDescriptor.name && fileDescriptor.name.length)
            root.files.push(filePackage.filename = fileDescriptor.name);
          if (fileDescriptor.messageType)
            for (i = 0; i < fileDescriptor.messageType.length; ++i)
              filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], edition));
          if (fileDescriptor.enumType)
            for (i = 0; i < fileDescriptor.enumType.length; ++i)
              filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition));
          if (fileDescriptor.extension)
            for (i = 0; i < fileDescriptor.extension.length; ++i)
              filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition));
          if (fileDescriptor.service)
            for (i = 0; i < fileDescriptor.service.length; ++i)
              filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition));
          var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions);
          if (opts) {
            var ks = Object.keys(opts);
            for (i = 0; i < ks.length; ++i)
              filePackage.setOption(ks[i], opts[ks[i]]);
          }
        }
      }
      return root.resolveAll();
    }, "fromDescriptor");
    Root.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var set = exports.FileDescriptorSet.create();
      Root_toDescriptorRecursive(this, set.file, edition);
      return set;
    }, "toDescriptor");
    function Root_toDescriptorRecursive(ns, files, edition) {
      var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" });
      editionToDescriptor(edition, file);
      if (!(ns instanceof Root))
        file["package"] = ns.fullName.substring(1);
      for (var i = 0, nested; i < ns.nestedArray.length; ++i)
        if ((nested = ns._nestedArray[i]) instanceof Type)
          file.messageType.push(nested.toDescriptor(edition));
        else if (nested instanceof Enum)
          file.enumType.push(nested.toDescriptor());
        else if (nested instanceof Field)
          file.extension.push(nested.toDescriptor(edition));
        else if (nested instanceof Service)
          file.service.push(nested.toDescriptor());
        else if (nested instanceof /* plain */
        Namespace)
          Root_toDescriptorRecursive(nested, files, edition);
      file.options = toDescriptorOptions(ns.options, exports.FileOptions);
      if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length)
        files.push(file);
    }
    __name(Root_toDescriptorRecursive, "Root_toDescriptorRecursive");
    var unnamedMessageIndex = 0;
    Type.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor, edition, nested, depth) {
      if (depth === void 0)
        depth = 0;
      if (depth > $protobuf.util.nestingLimit)
        throw Error("max depth exceeded");
      if (typeof descriptor.length === "number")
        descriptor = exports.DescriptorProto.decode(descriptor);
      var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)), i;
      if (!nested)
        type._edition = edition;
      if (descriptor.oneofDecl)
        for (i = 0; i < descriptor.oneofDecl.length; ++i)
          type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i]));
      if (descriptor.field)
        for (i = 0; i < descriptor.field.length; ++i) {
          var field = Field.fromDescriptor(descriptor.field[i], edition, true);
          type.add(field);
          if (descriptor.field[i].hasOwnProperty("oneofIndex"))
            type.oneofsArray[descriptor.field[i].oneofIndex].add(field);
        }
      if (descriptor.extension)
        for (i = 0; i < descriptor.extension.length; ++i)
          type.add(Field.fromDescriptor(descriptor.extension[i], edition, true));
      if (descriptor.nestedType)
        for (i = 0; i < descriptor.nestedType.length; ++i) {
          type.add(Type.fromDescriptor(descriptor.nestedType[i], edition, true, depth + 1));
          if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry)
            type.setOption("map_entry", true);
        }
      if (descriptor.enumType)
        for (i = 0; i < descriptor.enumType.length; ++i)
          type.add(Enum.fromDescriptor(descriptor.enumType[i], edition, true));
      if (descriptor.extensionRange && descriptor.extensionRange.length) {
        type.extensions = [];
        for (i = 0; i < descriptor.extensionRange.length; ++i)
          type.extensions.push([descriptor.extensionRange[i].start, descriptor.extensionRange[i].end]);
      }
      if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) {
        type.reserved = [];
        if (descriptor.reservedRange)
          for (i = 0; i < descriptor.reservedRange.length; ++i)
            type.reserved.push([descriptor.reservedRange[i].start, descriptor.reservedRange[i].end]);
        if (descriptor.reservedName)
          for (i = 0; i < descriptor.reservedName.length; ++i)
            type.reserved.push(descriptor.reservedName[i]);
      }
      return type;
    }, "fromDescriptor");
    Type.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var descriptor = exports.DescriptorProto.create({ name: this.name }), i;
      for (i = 0; i < this.fieldsArray.length; ++i) {
        var fieldDescriptor;
        descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition));
        if (this._fieldsArray[i] instanceof MapField) {
          var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), valueTypeName = valueType === /* type */
          11 || valueType === /* enum */
          14 ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type : void 0;
          descriptor.nestedType.push(exports.DescriptorProto.create({
            name: fieldDescriptor.typeName,
            field: [
              exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }),
              // can't reference a type or enum
              exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName })
            ],
            options: exports.MessageOptions.create({ mapEntry: true })
          }));
        }
      }
      for (i = 0; i < this.oneofsArray.length; ++i)
        descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor());
      for (i = 0; i < this.nestedArray.length; ++i) {
        if (this._nestedArray[i] instanceof Field)
          descriptor.field.push(this._nestedArray[i].toDescriptor(edition));
        else if (this._nestedArray[i] instanceof Type)
          descriptor.nestedType.push(this._nestedArray[i].toDescriptor(edition));
        else if (this._nestedArray[i] instanceof Enum)
          descriptor.enumType.push(this._nestedArray[i].toDescriptor());
      }
      if (this.extensions)
        for (i = 0; i < this.extensions.length; ++i)
          descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] }));
      if (this.reserved)
        for (i = 0; i < this.reserved.length; ++i)
          if (typeof this.reserved[i] === "string")
            descriptor.reservedName.push(this.reserved[i]);
          else
            descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] }));
      descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions);
      return descriptor;
    }, "toDescriptor");
    Field.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor, edition, nested) {
      if (typeof descriptor.length === "number")
        descriptor = exports.DescriptorProto.decode(descriptor);
      if (typeof descriptor.number !== "number")
        throw Error("missing field id");
      var typeName = descriptor.typeName, fieldType;
      if (typeName != null && typeName !== "") {
        if (typeof typeName !== "string" || !typeRefRe.test(typeName))
          throw Error("illegal type name: " + typeName);
        fieldType = typeName;
      } else
        fieldType = fromDescriptorType(descriptor.type);
      var fieldRule;
      switch (descriptor.label) {
        // 0 is reserved for errors
        case 1:
          fieldRule = void 0;
          break;
        case 2:
          fieldRule = "required";
          break;
        case 3:
          fieldRule = "repeated";
          break;
        default:
          throw Error("illegal label: " + descriptor.label);
      }
      var extendee = descriptor.extendee;
      if (extendee != null && extendee !== "") {
        if (typeof extendee !== "string" || !typeRefRe.test(extendee))
          throw Error("illegal type name: " + extendee);
      } else
        extendee = void 0;
      var field = new Field(
        descriptor.name.length ? descriptor.name : "field" + descriptor.number,
        descriptor.number,
        fieldType,
        fieldRule,
        extendee
      );
      if (!nested)
        field._edition = edition;
      field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions);
      if (descriptor.proto3_optional)
        field.options.proto3_optional = true;
      if (descriptor.defaultValue && descriptor.defaultValue.length) {
        var defaultValue = descriptor.defaultValue;
        switch (defaultValue) {
          case "true":
          case "TRUE":
            defaultValue = true;
            break;
          case "false":
          case "FALSE":
            defaultValue = false;
            break;
          default:
            var match = numberRe.exec(defaultValue);
            if (match)
              defaultValue = parseInt(defaultValue);
            break;
        }
        field.setOption("default", defaultValue);
      }
      if (packableDescriptorType(descriptor.type)) {
        if (edition === "proto3") {
          if (descriptor.options && !descriptor.options.packed)
            field.setOption("packed", false);
        } else if ((!edition || edition === "proto2") && descriptor.options && descriptor.options.packed)
          field.setOption("packed", true);
      }
      return field;
    }, "fromDescriptor");
    Field.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id });
      if (this.map) {
        descriptor.type = 11;
        descriptor.typeName = $protobuf.util.ucFirst(this.name);
        descriptor.label = 3;
      } else {
        switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) {
          case 10:
          // group
          case 11:
          // type
          case 14:
            descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type;
            break;
        }
        if (this.rule === "repeated") {
          descriptor.label = 3;
        } else if (this.required && edition === "proto2") {
          descriptor.label = 2;
        } else {
          descriptor.label = 1;
        }
      }
      descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend;
      if (this.partOf && this.parent instanceof Type) {
        if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0)
          throw Error("missing oneof");
      }
      if (this.options) {
        descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions);
        if (this.options["default"] != null)
          descriptor.defaultValue = String(this.options["default"]);
        if (this.options.proto3_optional)
          descriptor.proto3_optional = true;
      }
      if (edition === "proto3") {
        if (!this.packed)
          (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false;
      } else if ((!edition || edition === "proto2") && this.packed)
        (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true;
      return descriptor;
    }, "toDescriptor");
    var unnamedEnumIndex = 0;
    Enum.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor, edition, nested) {
      if (typeof descriptor.length === "number")
        descriptor = exports.EnumDescriptorProto.decode(descriptor);
      var values = {};
      if (descriptor.value)
        for (var i = 0; i < descriptor.value.length; ++i) {
          var name = descriptor.value[i].name, value = descriptor.value[i].number || 0;
          values[name && name.length ? name : "NAME" + value] = value;
        }
      var enm = new Enum(
        descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++,
        values,
        fromDescriptorOptions(descriptor.options, exports.EnumOptions)
      );
      if (!nested)
        enm._edition = edition;
      return enm;
    }, "fromDescriptor");
    Enum.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      var values = [];
      for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i)
        values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] }));
      return exports.EnumDescriptorProto.create({
        name: this.name,
        value: values,
        options: toDescriptorOptions(this.options, exports.EnumOptions)
      });
    }, "toDescriptor");
    var unnamedOneofIndex = 0;
    OneOf.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor) {
      if (typeof descriptor.length === "number")
        descriptor = exports.OneofDescriptorProto.decode(descriptor);
      return new OneOf(
        // unnamedOneOfIndex is global, not per type, because we have no ref to a type here
        descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++
        // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option
      );
    }, "fromDescriptor");
    OneOf.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      return exports.OneofDescriptorProto.create({
        name: this.name
        // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option
      });
    }, "toDescriptor");
    var unnamedServiceIndex = 0;
    Service.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor, edition, nested) {
      if (typeof descriptor.length === "number")
        descriptor = exports.ServiceDescriptorProto.decode(descriptor);
      var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions));
      if (!nested)
        service._edition = edition;
      if (descriptor.method)
        for (var i = 0; i < descriptor.method.length; ++i)
          service.add(Method.fromDescriptor(descriptor.method[i]));
      return service;
    }, "fromDescriptor");
    Service.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      var methods = [];
      for (var i = 0; i < this.methodsArray.length; ++i)
        methods.push(this._methodsArray[i].toDescriptor());
      return exports.ServiceDescriptorProto.create({
        name: this.name,
        method: methods,
        options: toDescriptorOptions(this.options, exports.ServiceOptions)
      });
    }, "toDescriptor");
    var unnamedMethodIndex = 0;
    Method.fromDescriptor = /* @__PURE__ */ __name(function fromDescriptor(descriptor) {
      if (typeof descriptor.length === "number")
        descriptor = exports.MethodDescriptorProto.decode(descriptor);
      var inputType = descriptor.inputType, outputType = descriptor.outputType;
      if (inputType != null && inputType !== "") {
        if (typeof inputType !== "string" || !typeRefRe.test(inputType))
          throw Error("illegal type name: " + inputType);
      }
      if (outputType != null && outputType !== "") {
        if (typeof outputType !== "string" || !typeRefRe.test(outputType))
          throw Error("illegal type name: " + outputType);
      }
      return new Method(
        // unnamedMethodIndex is global, not per service, because we have no ref to a service here
        descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++,
        "rpc",
        inputType,
        outputType,
        Boolean(descriptor.clientStreaming),
        Boolean(descriptor.serverStreaming),
        fromDescriptorOptions(descriptor.options, exports.MethodOptions)
      );
    }, "fromDescriptor");
    Method.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      return exports.MethodDescriptorProto.create({
        name: this.name,
        inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType,
        outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType,
        clientStreaming: this.requestStream,
        serverStreaming: this.responseStream,
        options: toDescriptorOptions(this.options, exports.MethodOptions)
      });
    }, "toDescriptor");
    function fromDescriptorType(type) {
      switch (type) {
        // 0 is reserved for errors
        case 1:
          return "double";
        case 2:
          return "float";
        case 3:
          return "int64";
        case 4:
          return "uint64";
        case 5:
          return "int32";
        case 6:
          return "fixed64";
        case 7:
          return "fixed32";
        case 8:
          return "bool";
        case 9:
          return "string";
        case 12:
          return "bytes";
        case 13:
          return "uint32";
        case 15:
          return "sfixed32";
        case 16:
          return "sfixed64";
        case 17:
          return "sint32";
        case 18:
          return "sint64";
      }
      throw Error("illegal type: " + type);
    }
    __name(fromDescriptorType, "fromDescriptorType");
    function packableDescriptorType(type) {
      switch (type) {
        case 1:
        // double
        case 2:
        // float
        case 3:
        // int64
        case 4:
        // uint64
        case 5:
        // int32
        case 6:
        // fixed64
        case 7:
        // fixed32
        case 8:
        // bool
        case 13:
        // uint32
        case 14:
        // enum (!)
        case 15:
        // sfixed32
        case 16:
        // sfixed64
        case 17:
        // sint32
        case 18:
          return true;
      }
      return false;
    }
    __name(packableDescriptorType, "packableDescriptorType");
    function toDescriptorType(type, resolvedType, delimited) {
      switch (type) {
        // 0 is reserved for errors
        case "double":
          return 1;
        case "float":
          return 2;
        case "int64":
          return 3;
        case "uint64":
          return 4;
        case "int32":
          return 5;
        case "fixed64":
          return 6;
        case "fixed32":
          return 7;
        case "bool":
          return 8;
        case "string":
          return 9;
        case "bytes":
          return 12;
        case "uint32":
          return 13;
        case "sfixed32":
          return 15;
        case "sfixed64":
          return 16;
        case "sint32":
          return 17;
        case "sint64":
          return 18;
      }
      if (resolvedType instanceof Enum)
        return 14;
      if (resolvedType instanceof Type)
        return delimited ? 10 : 11;
      throw Error("illegal type: " + type);
    }
    __name(toDescriptorType, "toDescriptorType");
    function fromDescriptorOptionsRecursive(obj, type) {
      var val = {};
      for (var i = 0, field, key; i < type.fieldsArray.length; ++i) {
        if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") continue;
        if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
        var newKey = underScore(key);
        if (field.resolvedType instanceof Type) {
          val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType);
        } else if (field.resolvedType instanceof Enum) {
          val[newKey] = field.resolvedType.valuesById[obj[key]];
        } else {
          val[newKey] = obj[key];
        }
      }
      return val;
    }
    __name(fromDescriptorOptionsRecursive, "fromDescriptorOptionsRecursive");
    function fromDescriptorOptions(options, type) {
      if (!options)
        return void 0;
      return fromDescriptorOptionsRecursive(type.toObject(options), type);
    }
    __name(fromDescriptorOptions, "fromDescriptorOptions");
    function toDescriptorOptionsRecursive(obj, type) {
      var val = {};
      var keys = Object.keys(obj);
      for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var newKey = $protobuf.util.camelCase(key);
        if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue;
        var field = type.fields[newKey];
        if (field.resolvedType instanceof Type) {
          val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType);
        } else {
          val[newKey] = obj[key];
        }
        if (field.repeated && !Array.isArray(val[newKey])) {
          val[newKey] = [val[newKey]];
        }
      }
      return val;
    }
    __name(toDescriptorOptionsRecursive, "toDescriptorOptionsRecursive");
    function toDescriptorOptions(options, type) {
      if (!options)
        return void 0;
      return type.fromObject(toDescriptorOptionsRecursive(options, type));
    }
    __name(toDescriptorOptions, "toDescriptorOptions");
    function shortname(from, to) {
      var fromPath = from.fullName.split("."), toPath = to.fullName.split("."), i = 0, j = 0, k = toPath.length - 1;
      if (!(from instanceof Root) && to instanceof Namespace)
        while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) {
          var other = to.lookup(fromPath[i++], true);
          if (other !== null && other !== to)
            break;
          ++j;
        }
      else
        for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j) ;
      return toPath.slice(j).join(".");
    }
    __name(shortname, "shortname");
    function underScore(str) {
      return str.substring(0, 1) + str.substring(1).replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) {
        return "_" + $1.toLowerCase();
      });
    }
    __name(underScore, "underScore");
    function editionFromDescriptor(fileDescriptor) {
      if (fileDescriptor.syntax === "editions") {
        switch (fileDescriptor.edition) {
          case exports.Edition.EDITION_2023:
            return "2023";
          default:
            throw new Error("Unsupported edition " + fileDescriptor.edition);
        }
      }
      if (fileDescriptor.syntax === "proto3") {
        return "proto3";
      }
      return "proto2";
    }
    __name(editionFromDescriptor, "editionFromDescriptor");
    function editionToDescriptor(edition, fileDescriptor) {
      if (!edition) return;
      if (edition === "proto2" || edition === "proto3") {
        fileDescriptor.syntax = edition;
      } else {
        fileDescriptor.syntax = "editions";
        switch (edition) {
          case "2023":
            fileDescriptor.edition = exports.Edition.EDITION_2023;
            break;
          default:
            throw new Error("Unsupported edition " + edition);
        }
      }
    }
    __name(editionToDescriptor, "editionToDescriptor");
  }
});

// node_modules/protobufjs/google/protobuf/api.json
var require_api = __commonJS({
  "node_modules/protobufjs/google/protobuf/api.json"(exports, module) {
    module.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              nested: {
                Api: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    methods: {
                      rule: "repeated",
                      type: "Method",
                      id: 2
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 3
                    },
                    version: {
                      type: "string",
                      id: 4
                    },
                    sourceContext: {
                      type: "SourceContext",
                      id: 5
                    },
                    mixins: {
                      rule: "repeated",
                      type: "Mixin",
                      id: 6
                    },
                    syntax: {
                      type: "Syntax",
                      id: 7
                    }
                  }
                },
                Method: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    requestTypeUrl: {
                      type: "string",
                      id: 2
                    },
                    requestStreaming: {
                      type: "bool",
                      id: 3
                    },
                    responseTypeUrl: {
                      type: "string",
                      id: 4
                    },
                    responseStreaming: {
                      type: "bool",
                      id: 5
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 6
                    },
                    syntax: {
                      type: "Syntax",
                      id: 7
                    }
                  }
                },
                Mixin: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    root: {
                      type: "string",
                      id: 2
                    }
                  }
                },
                SourceContext: {
                  fields: {
                    fileName: {
                      type: "string",
                      id: 1
                    }
                  }
                },
                Option: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      type: "Any",
                      id: 2
                    }
                  }
                },
                Syntax: {
                  values: {
                    SYNTAX_PROTO2: 0,
                    SYNTAX_PROTO3: 1
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/protobufjs/google/protobuf/source_context.json
var require_source_context = __commonJS({
  "node_modules/protobufjs/google/protobuf/source_context.json"(exports, module) {
    module.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              nested: {
                SourceContext: {
                  fields: {
                    fileName: {
                      type: "string",
                      id: 1
                    }
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/protobufjs/google/protobuf/type.json
var require_type2 = __commonJS({
  "node_modules/protobufjs/google/protobuf/type.json"(exports, module) {
    module.exports = {
      nested: {
        google: {
          nested: {
            protobuf: {
              nested: {
                Type: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    fields: {
                      rule: "repeated",
                      type: "Field",
                      id: 2
                    },
                    oneofs: {
                      rule: "repeated",
                      type: "string",
                      id: 3
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 4
                    },
                    sourceContext: {
                      type: "SourceContext",
                      id: 5
                    },
                    syntax: {
                      type: "Syntax",
                      id: 6
                    }
                  }
                },
                Field: {
                  fields: {
                    kind: {
                      type: "Kind",
                      id: 1
                    },
                    cardinality: {
                      type: "Cardinality",
                      id: 2
                    },
                    number: {
                      type: "int32",
                      id: 3
                    },
                    name: {
                      type: "string",
                      id: 4
                    },
                    typeUrl: {
                      type: "string",
                      id: 6
                    },
                    oneofIndex: {
                      type: "int32",
                      id: 7
                    },
                    packed: {
                      type: "bool",
                      id: 8
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 9
                    },
                    jsonName: {
                      type: "string",
                      id: 10
                    },
                    defaultValue: {
                      type: "string",
                      id: 11
                    }
                  },
                  nested: {
                    Kind: {
                      values: {
                        TYPE_UNKNOWN: 0,
                        TYPE_DOUBLE: 1,
                        TYPE_FLOAT: 2,
                        TYPE_INT64: 3,
                        TYPE_UINT64: 4,
                        TYPE_INT32: 5,
                        TYPE_FIXED64: 6,
                        TYPE_FIXED32: 7,
                        TYPE_BOOL: 8,
                        TYPE_STRING: 9,
                        TYPE_GROUP: 10,
                        TYPE_MESSAGE: 11,
                        TYPE_BYTES: 12,
                        TYPE_UINT32: 13,
                        TYPE_ENUM: 14,
                        TYPE_SFIXED32: 15,
                        TYPE_SFIXED64: 16,
                        TYPE_SINT32: 17,
                        TYPE_SINT64: 18
                      }
                    },
                    Cardinality: {
                      values: {
                        CARDINALITY_UNKNOWN: 0,
                        CARDINALITY_OPTIONAL: 1,
                        CARDINALITY_REQUIRED: 2,
                        CARDINALITY_REPEATED: 3
                      }
                    }
                  }
                },
                Enum: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    enumvalue: {
                      rule: "repeated",
                      type: "EnumValue",
                      id: 2
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 3
                    },
                    sourceContext: {
                      type: "SourceContext",
                      id: 4
                    },
                    syntax: {
                      type: "Syntax",
                      id: 5
                    }
                  }
                },
                EnumValue: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    number: {
                      type: "int32",
                      id: 2
                    },
                    options: {
                      rule: "repeated",
                      type: "Option",
                      id: 3
                    }
                  }
                },
                Option: {
                  fields: {
                    name: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      type: "Any",
                      id: 2
                    }
                  }
                },
                Syntax: {
                  values: {
                    SYNTAX_PROTO2: 0,
                    SYNTAX_PROTO3: 1
                  }
                },
                Any: {
                  fields: {
                    type_url: {
                      type: "string",
                      id: 1
                    },
                    value: {
                      type: "bytes",
                      id: 2
                    }
                  }
                },
                SourceContext: {
                  fields: {
                    fileName: {
                      type: "string",
                      id: 1
                    }
                  }
                }
              }
            }
          }
        }
      }
    };
  }
});

// node_modules/@grpc/proto-loader/build/src/util.js
var require_util2 = __commonJS({
  "node_modules/@grpc/proto-loader/build/src/util.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0;
    var fs9 = __require("fs");
    var path11 = __require("path");
    var Protobuf = require_protobufjs();
    function addIncludePathResolver(root, includePaths) {
      const originalResolvePath = root.resolvePath;
      root.resolvePath = (origin, target) => {
        if (path11.isAbsolute(target)) {
          return target;
        }
        for (const directory of includePaths) {
          const fullPath = path11.join(directory, target);
          try {
            fs9.accessSync(fullPath, fs9.constants.R_OK);
            return fullPath;
          } catch (err) {
            continue;
          }
        }
        process.emitWarning(`${target} not found in any of the include paths ${includePaths}`);
        return originalResolvePath(origin, target);
      };
    }
    __name(addIncludePathResolver, "addIncludePathResolver");
    async function loadProtosWithOptions(filename, options) {
      const root = new Protobuf.Root();
      options = options || {};
      if (!!options.includeDirs) {
        if (!Array.isArray(options.includeDirs)) {
          return Promise.reject(new Error("The includeDirs option must be an array"));
        }
        addIncludePathResolver(root, options.includeDirs);
      }
      const loadedRoot = await root.load(filename, options);
      loadedRoot.resolveAll();
      return loadedRoot;
    }
    __name(loadProtosWithOptions, "loadProtosWithOptions");
    exports.loadProtosWithOptions = loadProtosWithOptions;
    function loadProtosWithOptionsSync(filename, options) {
      const root = new Protobuf.Root();
      options = options || {};
      if (!!options.includeDirs) {
        if (!Array.isArray(options.includeDirs)) {
          throw new Error("The includeDirs option must be an array");
        }
        addIncludePathResolver(root, options.includeDirs);
      }
      const loadedRoot = root.loadSync(filename, options);
      loadedRoot.resolveAll();
      return loadedRoot;
    }
    __name(loadProtosWithOptionsSync, "loadProtosWithOptionsSync");
    exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync;
    function addCommonProtos() {
      const apiDescriptor = require_api();
      const descriptorDescriptor = require_descriptor();
      const sourceContextDescriptor = require_source_context();
      const typeDescriptor = require_type2();
      Protobuf.common("api", apiDescriptor.nested.google.nested.protobuf.nested);
      Protobuf.common("descriptor", descriptorDescriptor.nested.google.nested.protobuf.nested);
      Protobuf.common("source_context", sourceContextDescriptor.nested.google.nested.protobuf.nested);
      Protobuf.common("type", typeDescriptor.nested.google.nested.protobuf.nested);
    }
    __name(addCommonProtos, "addCommonProtos");
    exports.addCommonProtos = addCommonProtos;
  }
});

// node_modules/@grpc/proto-loader/build/src/index.js
var require_src5 = __commonJS({
  "node_modules/@grpc/proto-loader/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = void 0;
    var camelCase = require_lodash();
    var Protobuf = require_protobufjs();
    var descriptor = require_descriptor2();
    var util_1 = require_util2();
    var Long = require_umd();
    exports.Long = Long;
    function isAnyExtension(obj) {
      return "@type" in obj && typeof obj["@type"] === "string";
    }
    __name(isAnyExtension, "isAnyExtension");
    exports.isAnyExtension = isAnyExtension;
    var IdempotencyLevel;
    (function(IdempotencyLevel2) {
      IdempotencyLevel2["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN";
      IdempotencyLevel2["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS";
      IdempotencyLevel2["IDEMPOTENT"] = "IDEMPOTENT";
    })(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {}));
    var descriptorOptions = {
      longs: String,
      enums: String,
      bytes: String,
      defaults: true,
      oneofs: true,
      json: true
    };
    function joinName(baseName, name) {
      if (baseName === "") {
        return name;
      } else {
        return baseName + "." + name;
      }
    }
    __name(joinName, "joinName");
    function isHandledReflectionObject(obj) {
      return obj instanceof Protobuf.Service || obj instanceof Protobuf.Type || obj instanceof Protobuf.Enum;
    }
    __name(isHandledReflectionObject, "isHandledReflectionObject");
    function isNamespaceBase(obj) {
      return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root;
    }
    __name(isNamespaceBase, "isNamespaceBase");
    function getAllHandledReflectionObjects(obj, parentName) {
      const objName = joinName(parentName, obj.name);
      if (isHandledReflectionObject(obj)) {
        return [[objName, obj]];
      } else {
        if (isNamespaceBase(obj) && typeof obj.nested !== "undefined") {
          return Object.keys(obj.nested).map((name) => {
            return getAllHandledReflectionObjects(obj.nested[name], objName);
          }).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
        }
      }
      return [];
    }
    __name(getAllHandledReflectionObjects, "getAllHandledReflectionObjects");
    function createDeserializer(cls, options) {
      return /* @__PURE__ */ __name(function deserialize(argBuf) {
        return cls.toObject(cls.decode(argBuf), options);
      }, "deserialize");
    }
    __name(createDeserializer, "createDeserializer");
    function createSerializer(cls) {
      return /* @__PURE__ */ __name(function serialize(arg) {
        if (Array.isArray(arg)) {
          throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`);
        }
        const message = cls.fromObject(arg);
        return cls.encode(message).finish();
      }, "serialize");
    }
    __name(createSerializer, "createSerializer");
    function mapMethodOptions(options) {
      return (options || []).reduce((obj, item) => {
        for (const [key, value] of Object.entries(item)) {
          switch (key) {
            case "uninterpreted_option":
              obj.uninterpreted_option.push(item.uninterpreted_option);
              break;
            default:
              obj[key] = value;
          }
        }
        return obj;
      }, {
        deprecated: false,
        idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN,
        uninterpreted_option: []
      });
    }
    __name(mapMethodOptions, "mapMethodOptions");
    function createMethodDefinition(method, serviceName, options, fileDescriptors) {
      const requestType = method.resolvedRequestType;
      const responseType = method.resolvedResponseType;
      return {
        path: "/" + serviceName + "/" + method.name,
        requestStream: !!method.requestStream,
        responseStream: !!method.responseStream,
        requestSerialize: createSerializer(requestType),
        requestDeserialize: createDeserializer(requestType, options),
        responseSerialize: createSerializer(responseType),
        responseDeserialize: createDeserializer(responseType, options),
        // TODO(murgatroid99): Find a better way to handle this
        originalName: camelCase(method.name),
        requestType: createMessageDefinition(requestType, options, fileDescriptors),
        responseType: createMessageDefinition(responseType, options, fileDescriptors),
        options: mapMethodOptions(method.parsedOptions)
      };
    }
    __name(createMethodDefinition, "createMethodDefinition");
    function createServiceDefinition(service, name, options, fileDescriptors) {
      const def = {};
      for (const method of service.methodsArray) {
        def[method.name] = createMethodDefinition(method, name, options, fileDescriptors);
      }
      return def;
    }
    __name(createServiceDefinition, "createServiceDefinition");
    function createMessageDefinition(message, options, fileDescriptors) {
      const messageDescriptor = message.toDescriptor("proto3");
      return {
        format: "Protocol Buffer 3 DescriptorProto",
        type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions),
        fileDescriptorProtos: fileDescriptors,
        serialize: createSerializer(message),
        deserialize: createDeserializer(message, options)
      };
    }
    __name(createMessageDefinition, "createMessageDefinition");
    function createEnumDefinition(enumType, fileDescriptors) {
      const enumDescriptor = enumType.toDescriptor("proto3");
      return {
        format: "Protocol Buffer 3 EnumDescriptorProto",
        type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions),
        fileDescriptorProtos: fileDescriptors
      };
    }
    __name(createEnumDefinition, "createEnumDefinition");
    function createDefinition(obj, name, options, fileDescriptors) {
      if (obj instanceof Protobuf.Service) {
        return createServiceDefinition(obj, name, options, fileDescriptors);
      } else if (obj instanceof Protobuf.Type) {
        return createMessageDefinition(obj, options, fileDescriptors);
      } else if (obj instanceof Protobuf.Enum) {
        return createEnumDefinition(obj, fileDescriptors);
      } else {
        throw new Error("Type mismatch in reflection object handling");
      }
    }
    __name(createDefinition, "createDefinition");
    function createPackageDefinition(root, options) {
      const def = {};
      root.resolveAll();
      const descriptorList = root.toDescriptor("proto3").file;
      const bufferList = descriptorList.map((value) => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish()));
      for (const [name, obj] of getAllHandledReflectionObjects(root, "")) {
        def[name] = createDefinition(obj, name, options, bufferList);
      }
      return def;
    }
    __name(createPackageDefinition, "createPackageDefinition");
    function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) {
      options = options || {};
      const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet);
      root.resolveAll();
      return createPackageDefinition(root, options);
    }
    __name(createPackageDefinitionFromDescriptorSet, "createPackageDefinitionFromDescriptorSet");
    function load(filename, options) {
      return (0, util_1.loadProtosWithOptions)(filename, options).then((loadedRoot) => {
        return createPackageDefinition(loadedRoot, options);
      });
    }
    __name(load, "load");
    exports.load = load;
    function loadSync(filename, options) {
      const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options);
      return createPackageDefinition(loadedRoot, options);
    }
    __name(loadSync, "loadSync");
    exports.loadSync = loadSync;
    function fromJSON(json, options) {
      options = options || {};
      const loadedRoot = Protobuf.Root.fromJSON(json);
      loadedRoot.resolveAll();
      return createPackageDefinition(loadedRoot, options);
    }
    __name(fromJSON, "fromJSON");
    exports.fromJSON = fromJSON;
    function loadFileDescriptorSetFromBuffer(descriptorSet, options) {
      const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet);
      return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options);
    }
    __name(loadFileDescriptorSetFromBuffer, "loadFileDescriptorSetFromBuffer");
    exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer;
    function loadFileDescriptorSetFromObject(descriptorSet, options) {
      const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet);
      return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options);
    }
    __name(loadFileDescriptorSetFromObject, "loadFileDescriptorSetFromObject");
    exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject;
    (0, util_1.addCommonProtos)();
  }
});

// node_modules/@grpc/grpc-js/build/src/channelz.js
var require_channelz = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channelz.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.registerChannelzSocket = exports.registerChannelzServer = exports.registerChannelzSubchannel = exports.registerChannelzChannel = exports.ChannelzCallTrackerStub = exports.ChannelzCallTracker = exports.ChannelzChildrenTrackerStub = exports.ChannelzChildrenTracker = exports.ChannelzTrace = exports.ChannelzTraceStub = void 0;
    exports.unregisterChannelzRef = unregisterChannelzRef;
    exports.getChannelzHandlers = getChannelzHandlers;
    exports.getChannelzServiceDefinition = getChannelzServiceDefinition;
    exports.setup = setup;
    var net_1 = __require("net");
    var ordered_map_1 = require_cjs();
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants2();
    var subchannel_address_1 = require_subchannel_address();
    var admin_1 = require_admin();
    var make_client_1 = require_make_client();
    function channelRefToMessage(ref) {
      return {
        channel_id: ref.id,
        name: ref.name
      };
    }
    __name(channelRefToMessage, "channelRefToMessage");
    function subchannelRefToMessage(ref) {
      return {
        subchannel_id: ref.id,
        name: ref.name
      };
    }
    __name(subchannelRefToMessage, "subchannelRefToMessage");
    function serverRefToMessage(ref) {
      return {
        server_id: ref.id
      };
    }
    __name(serverRefToMessage, "serverRefToMessage");
    function socketRefToMessage(ref) {
      return {
        socket_id: ref.id,
        name: ref.name
      };
    }
    __name(socketRefToMessage, "socketRefToMessage");
    var TARGET_RETAINED_TRACES = 32;
    var DEFAULT_MAX_RESULTS = 100;
    var ChannelzTraceStub = class {
      static {
        __name(this, "ChannelzTraceStub");
      }
      constructor() {
        this.events = [];
        this.creationTimestamp = /* @__PURE__ */ new Date();
        this.eventsLogged = 0;
      }
      addTrace() {
      }
      getTraceMessage() {
        return {
          creation_timestamp: dateToProtoTimestamp(this.creationTimestamp),
          num_events_logged: this.eventsLogged,
          events: []
        };
      }
    };
    exports.ChannelzTraceStub = ChannelzTraceStub;
    var ChannelzTrace = class {
      static {
        __name(this, "ChannelzTrace");
      }
      constructor() {
        this.events = [];
        this.eventsLogged = 0;
        this.creationTimestamp = /* @__PURE__ */ new Date();
      }
      addTrace(severity, description, child) {
        const timestamp = /* @__PURE__ */ new Date();
        this.events.push({
          description,
          severity,
          timestamp,
          childChannel: (child === null || child === void 0 ? void 0 : child.kind) === "channel" ? child : void 0,
          childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === "subchannel" ? child : void 0
        });
        if (this.events.length >= TARGET_RETAINED_TRACES * 2) {
          this.events = this.events.slice(TARGET_RETAINED_TRACES);
        }
        this.eventsLogged += 1;
      }
      getTraceMessage() {
        return {
          creation_timestamp: dateToProtoTimestamp(this.creationTimestamp),
          num_events_logged: this.eventsLogged,
          events: this.events.map((event) => {
            return {
              description: event.description,
              severity: event.severity,
              timestamp: dateToProtoTimestamp(event.timestamp),
              channel_ref: event.childChannel ? channelRefToMessage(event.childChannel) : null,
              subchannel_ref: event.childSubchannel ? subchannelRefToMessage(event.childSubchannel) : null
            };
          })
        };
      }
    };
    exports.ChannelzTrace = ChannelzTrace;
    var ChannelzChildrenTracker = class {
      static {
        __name(this, "ChannelzChildrenTracker");
      }
      constructor() {
        this.channelChildren = new ordered_map_1.OrderedMap();
        this.subchannelChildren = new ordered_map_1.OrderedMap();
        this.socketChildren = new ordered_map_1.OrderedMap();
        this.trackerMap = {
          [
            "channel"
            /* EntityTypes.channel */
          ]: this.channelChildren,
          [
            "subchannel"
            /* EntityTypes.subchannel */
          ]: this.subchannelChildren,
          [
            "socket"
            /* EntityTypes.socket */
          ]: this.socketChildren
        };
      }
      refChild(child) {
        const tracker = this.trackerMap[child.kind];
        const trackedChild = tracker.find(child.id);
        if (trackedChild.equals(tracker.end())) {
          tracker.setElement(child.id, {
            ref: child,
            count: 1
          }, trackedChild);
        } else {
          trackedChild.pointer[1].count += 1;
        }
      }
      unrefChild(child) {
        const tracker = this.trackerMap[child.kind];
        const trackedChild = tracker.getElementByKey(child.id);
        if (trackedChild !== void 0) {
          trackedChild.count -= 1;
          if (trackedChild.count === 0) {
            tracker.eraseElementByKey(child.id);
          }
        }
      }
      getChildLists() {
        return {
          channels: this.channelChildren,
          subchannels: this.subchannelChildren,
          sockets: this.socketChildren
        };
      }
    };
    exports.ChannelzChildrenTracker = ChannelzChildrenTracker;
    var ChannelzChildrenTrackerStub = class extends ChannelzChildrenTracker {
      static {
        __name(this, "ChannelzChildrenTrackerStub");
      }
      refChild() {
      }
      unrefChild() {
      }
    };
    exports.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub;
    var ChannelzCallTracker = class {
      static {
        __name(this, "ChannelzCallTracker");
      }
      constructor() {
        this.callsStarted = 0;
        this.callsSucceeded = 0;
        this.callsFailed = 0;
        this.lastCallStartedTimestamp = null;
      }
      addCallStarted() {
        this.callsStarted += 1;
        this.lastCallStartedTimestamp = /* @__PURE__ */ new Date();
      }
      addCallSucceeded() {
        this.callsSucceeded += 1;
      }
      addCallFailed() {
        this.callsFailed += 1;
      }
    };
    exports.ChannelzCallTracker = ChannelzCallTracker;
    var ChannelzCallTrackerStub = class extends ChannelzCallTracker {
      static {
        __name(this, "ChannelzCallTrackerStub");
      }
      addCallStarted() {
      }
      addCallSucceeded() {
      }
      addCallFailed() {
      }
    };
    exports.ChannelzCallTrackerStub = ChannelzCallTrackerStub;
    var entityMaps = {
      [
        "channel"
        /* EntityTypes.channel */
      ]: new ordered_map_1.OrderedMap(),
      [
        "subchannel"
        /* EntityTypes.subchannel */
      ]: new ordered_map_1.OrderedMap(),
      [
        "server"
        /* EntityTypes.server */
      ]: new ordered_map_1.OrderedMap(),
      [
        "socket"
        /* EntityTypes.socket */
      ]: new ordered_map_1.OrderedMap()
    };
    var generateRegisterFn = /* @__PURE__ */ __name((kind) => {
      let nextId = 1;
      function getNextId() {
        return nextId++;
      }
      __name(getNextId, "getNextId");
      const entityMap = entityMaps[kind];
      return (name, getInfo, channelzEnabled) => {
        const id = getNextId();
        const ref = { id, name, kind };
        if (channelzEnabled) {
          entityMap.setElement(id, { ref, getInfo });
        }
        return ref;
      };
    }, "generateRegisterFn");
    exports.registerChannelzChannel = generateRegisterFn(
      "channel"
      /* EntityTypes.channel */
    );
    exports.registerChannelzSubchannel = generateRegisterFn(
      "subchannel"
      /* EntityTypes.subchannel */
    );
    exports.registerChannelzServer = generateRegisterFn(
      "server"
      /* EntityTypes.server */
    );
    exports.registerChannelzSocket = generateRegisterFn(
      "socket"
      /* EntityTypes.socket */
    );
    function unregisterChannelzRef(ref) {
      entityMaps[ref.kind].eraseElementByKey(ref.id);
    }
    __name(unregisterChannelzRef, "unregisterChannelzRef");
    function parseIPv6Section(addressSection) {
      const numberValue = Number.parseInt(addressSection, 16);
      return [numberValue / 256 | 0, numberValue % 256];
    }
    __name(parseIPv6Section, "parseIPv6Section");
    function parseIPv6Chunk(addressChunk) {
      if (addressChunk === "") {
        return [];
      }
      const bytePairs = addressChunk.split(":").map((section) => parseIPv6Section(section));
      const result = [];
      return result.concat(...bytePairs);
    }
    __name(parseIPv6Chunk, "parseIPv6Chunk");
    function isIPv6MappedIPv4(ipAddress) {
      return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith("::ffff:") && (0, net_1.isIPv4)(ipAddress.substring(7));
    }
    __name(isIPv6MappedIPv4, "isIPv6MappedIPv4");
    function ipv4AddressStringToBuffer(ipAddress) {
      return Buffer.from(Uint8Array.from(ipAddress.split(".").map((segment) => Number.parseInt(segment))));
    }
    __name(ipv4AddressStringToBuffer, "ipv4AddressStringToBuffer");
    function ipAddressStringToBuffer(ipAddress) {
      if ((0, net_1.isIPv4)(ipAddress)) {
        return ipv4AddressStringToBuffer(ipAddress);
      } else if (isIPv6MappedIPv4(ipAddress)) {
        return ipv4AddressStringToBuffer(ipAddress.substring(7));
      } else if ((0, net_1.isIPv6)(ipAddress)) {
        let leftSection;
        let rightSection;
        const doubleColonIndex = ipAddress.indexOf("::");
        if (doubleColonIndex === -1) {
          leftSection = ipAddress;
          rightSection = "";
        } else {
          leftSection = ipAddress.substring(0, doubleColonIndex);
          rightSection = ipAddress.substring(doubleColonIndex + 2);
        }
        const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection));
        const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection));
        const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0);
        return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]);
      } else {
        return null;
      }
    }
    __name(ipAddressStringToBuffer, "ipAddressStringToBuffer");
    function connectivityStateToMessage(state) {
      switch (state) {
        case connectivity_state_1.ConnectivityState.CONNECTING:
          return {
            state: "CONNECTING"
          };
        case connectivity_state_1.ConnectivityState.IDLE:
          return {
            state: "IDLE"
          };
        case connectivity_state_1.ConnectivityState.READY:
          return {
            state: "READY"
          };
        case connectivity_state_1.ConnectivityState.SHUTDOWN:
          return {
            state: "SHUTDOWN"
          };
        case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE:
          return {
            state: "TRANSIENT_FAILURE"
          };
        default:
          return {
            state: "UNKNOWN"
          };
      }
    }
    __name(connectivityStateToMessage, "connectivityStateToMessage");
    function dateToProtoTimestamp(date) {
      if (!date) {
        return null;
      }
      const millisSinceEpoch = date.getTime();
      return {
        seconds: millisSinceEpoch / 1e3 | 0,
        nanos: millisSinceEpoch % 1e3 * 1e6
      };
    }
    __name(dateToProtoTimestamp, "dateToProtoTimestamp");
    function getChannelMessage(channelEntry) {
      const resolvedInfo = channelEntry.getInfo();
      const channelRef = [];
      const subchannelRef = [];
      resolvedInfo.children.channels.forEach((el) => {
        channelRef.push(channelRefToMessage(el[1].ref));
      });
      resolvedInfo.children.subchannels.forEach((el) => {
        subchannelRef.push(subchannelRefToMessage(el[1].ref));
      });
      return {
        ref: channelRefToMessage(channelEntry.ref),
        data: {
          target: resolvedInfo.target,
          state: connectivityStateToMessage(resolvedInfo.state),
          calls_started: resolvedInfo.callTracker.callsStarted,
          calls_succeeded: resolvedInfo.callTracker.callsSucceeded,
          calls_failed: resolvedInfo.callTracker.callsFailed,
          last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp),
          trace: resolvedInfo.trace.getTraceMessage()
        },
        channel_ref: channelRef,
        subchannel_ref: subchannelRef
      };
    }
    __name(getChannelMessage, "getChannelMessage");
    function GetChannel(call, callback) {
      const channelId = parseInt(call.request.channel_id, 10);
      const channelEntry = entityMaps[
        "channel"
        /* EntityTypes.channel */
      ].getElementByKey(channelId);
      if (channelEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No channel data found for id " + channelId
        });
        return;
      }
      callback(null, { channel: getChannelMessage(channelEntry) });
    }
    __name(GetChannel, "GetChannel");
    function GetTopChannels(call, callback) {
      const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS;
      const resultList = [];
      const startId = parseInt(call.request.start_channel_id, 10);
      const channelEntries = entityMaps[
        "channel"
        /* EntityTypes.channel */
      ];
      let i;
      for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) {
        resultList.push(getChannelMessage(i.pointer[1]));
      }
      callback(null, {
        channel: resultList,
        end: i.equals(channelEntries.end())
      });
    }
    __name(GetTopChannels, "GetTopChannels");
    function getServerMessage(serverEntry) {
      const resolvedInfo = serverEntry.getInfo();
      const listenSocket = [];
      resolvedInfo.listenerChildren.sockets.forEach((el) => {
        listenSocket.push(socketRefToMessage(el[1].ref));
      });
      return {
        ref: serverRefToMessage(serverEntry.ref),
        data: {
          calls_started: resolvedInfo.callTracker.callsStarted,
          calls_succeeded: resolvedInfo.callTracker.callsSucceeded,
          calls_failed: resolvedInfo.callTracker.callsFailed,
          last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp),
          trace: resolvedInfo.trace.getTraceMessage()
        },
        listen_socket: listenSocket
      };
    }
    __name(getServerMessage, "getServerMessage");
    function GetServer(call, callback) {
      const serverId = parseInt(call.request.server_id, 10);
      const serverEntries = entityMaps[
        "server"
        /* EntityTypes.server */
      ];
      const serverEntry = serverEntries.getElementByKey(serverId);
      if (serverEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No server data found for id " + serverId
        });
        return;
      }
      callback(null, { server: getServerMessage(serverEntry) });
    }
    __name(GetServer, "GetServer");
    function GetServers(call, callback) {
      const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS;
      const startId = parseInt(call.request.start_server_id, 10);
      const serverEntries = entityMaps[
        "server"
        /* EntityTypes.server */
      ];
      const resultList = [];
      let i;
      for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) {
        resultList.push(getServerMessage(i.pointer[1]));
      }
      callback(null, {
        server: resultList,
        end: i.equals(serverEntries.end())
      });
    }
    __name(GetServers, "GetServers");
    function GetSubchannel(call, callback) {
      const subchannelId = parseInt(call.request.subchannel_id, 10);
      const subchannelEntry = entityMaps[
        "subchannel"
        /* EntityTypes.subchannel */
      ].getElementByKey(subchannelId);
      if (subchannelEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No subchannel data found for id " + subchannelId
        });
        return;
      }
      const resolvedInfo = subchannelEntry.getInfo();
      const listenSocket = [];
      resolvedInfo.children.sockets.forEach((el) => {
        listenSocket.push(socketRefToMessage(el[1].ref));
      });
      const subchannelMessage = {
        ref: subchannelRefToMessage(subchannelEntry.ref),
        data: {
          target: resolvedInfo.target,
          state: connectivityStateToMessage(resolvedInfo.state),
          calls_started: resolvedInfo.callTracker.callsStarted,
          calls_succeeded: resolvedInfo.callTracker.callsSucceeded,
          calls_failed: resolvedInfo.callTracker.callsFailed,
          last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp),
          trace: resolvedInfo.trace.getTraceMessage()
        },
        socket_ref: listenSocket
      };
      callback(null, { subchannel: subchannelMessage });
    }
    __name(GetSubchannel, "GetSubchannel");
    function subchannelAddressToAddressMessage(subchannelAddress) {
      var _a;
      if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) {
        return {
          address: "tcpip_address",
          tcpip_address: {
            ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : void 0,
            port: subchannelAddress.port
          }
        };
      } else {
        return {
          address: "uds_address",
          uds_address: {
            filename: subchannelAddress.path
          }
        };
      }
    }
    __name(subchannelAddressToAddressMessage, "subchannelAddressToAddressMessage");
    function GetSocket(call, callback) {
      var _a, _b, _c, _d, _e;
      const socketId = parseInt(call.request.socket_id, 10);
      const socketEntry = entityMaps[
        "socket"
        /* EntityTypes.socket */
      ].getElementByKey(socketId);
      if (socketEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No socket data found for id " + socketId
        });
        return;
      }
      const resolvedInfo = socketEntry.getInfo();
      const securityMessage = resolvedInfo.security ? {
        model: "tls",
        tls: {
          cipher_suite: resolvedInfo.security.cipherSuiteStandardName ? "standard_name" : "other_name",
          standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : void 0,
          other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : void 0,
          local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : void 0,
          remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : void 0
        }
      } : null;
      const socketMessage = {
        ref: socketRefToMessage(socketEntry.ref),
        local: resolvedInfo.localAddress ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) : null,
        remote: resolvedInfo.remoteAddress ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) : null,
        remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : void 0,
        security: securityMessage,
        data: {
          keep_alives_sent: resolvedInfo.keepAlivesSent,
          streams_started: resolvedInfo.streamsStarted,
          streams_succeeded: resolvedInfo.streamsSucceeded,
          streams_failed: resolvedInfo.streamsFailed,
          last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp),
          last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp),
          messages_received: resolvedInfo.messagesReceived,
          messages_sent: resolvedInfo.messagesSent,
          last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp),
          last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp),
          local_flow_control_window: resolvedInfo.localFlowControlWindow ? { value: resolvedInfo.localFlowControlWindow } : null,
          remote_flow_control_window: resolvedInfo.remoteFlowControlWindow ? { value: resolvedInfo.remoteFlowControlWindow } : null
        }
      };
      callback(null, { socket: socketMessage });
    }
    __name(GetSocket, "GetSocket");
    function GetServerSockets(call, callback) {
      const serverId = parseInt(call.request.server_id, 10);
      const serverEntry = entityMaps[
        "server"
        /* EntityTypes.server */
      ].getElementByKey(serverId);
      if (serverEntry === void 0) {
        callback({
          code: constants_1.Status.NOT_FOUND,
          details: "No server data found for id " + serverId
        });
        return;
      }
      const startId = parseInt(call.request.start_socket_id, 10);
      const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS;
      const resolvedInfo = serverEntry.getInfo();
      const allSockets = resolvedInfo.sessionChildren.sockets;
      const resultList = [];
      let i;
      for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) {
        resultList.push(socketRefToMessage(i.pointer[1].ref));
      }
      callback(null, {
        socket_ref: resultList,
        end: i.equals(allSockets.end())
      });
    }
    __name(GetServerSockets, "GetServerSockets");
    function getChannelzHandlers() {
      return {
        GetChannel,
        GetTopChannels,
        GetServer,
        GetServers,
        GetSubchannel,
        GetSocket,
        GetServerSockets
      };
    }
    __name(getChannelzHandlers, "getChannelzHandlers");
    var loadedChannelzDefinition = null;
    function getChannelzServiceDefinition() {
      if (loadedChannelzDefinition) {
        return loadedChannelzDefinition;
      }
      const loaderLoadSync = require_src5().loadSync;
      const loadedProto = loaderLoadSync("channelz.proto", {
        keepCase: true,
        longs: String,
        enums: String,
        defaults: true,
        oneofs: true,
        includeDirs: [`${__qwen_dirname}/../../proto`]
      });
      const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto);
      loadedChannelzDefinition = channelzGrpcObject.grpc.channelz.v1.Channelz.service;
      return loadedChannelzDefinition;
    }
    __name(getChannelzServiceDefinition, "getChannelzServiceDefinition");
    function setup() {
      (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/call-number.js
var require_call_number = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/call-number.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getNextCallNumber = getNextCallNumber;
    var nextCallNumber = 0;
    function getNextCallNumber() {
      return nextCallNumber++;
    }
    __name(getNextCallNumber, "getNextCallNumber");
  }
});

// node_modules/@grpc/grpc-js/build/src/compression-algorithms.js
var require_compression_algorithms = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/compression-algorithms.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompressionAlgorithms = void 0;
    var CompressionAlgorithms;
    (function(CompressionAlgorithms2) {
      CompressionAlgorithms2[CompressionAlgorithms2["identity"] = 0] = "identity";
      CompressionAlgorithms2[CompressionAlgorithms2["deflate"] = 1] = "deflate";
      CompressionAlgorithms2[CompressionAlgorithms2["gzip"] = 2] = "gzip";
    })(CompressionAlgorithms || (exports.CompressionAlgorithms = CompressionAlgorithms = {}));
  }
});

// node_modules/@grpc/grpc-js/build/src/filter.js
var require_filter = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/filter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseFilter = void 0;
    var BaseFilter = class {
      static {
        __name(this, "BaseFilter");
      }
      async sendMetadata(metadata) {
        return metadata;
      }
      receiveMetadata(metadata) {
        return metadata;
      }
      async sendMessage(message) {
        return message;
      }
      async receiveMessage(message) {
        return message;
      }
      receiveTrailers(status) {
        return status;
      }
    };
    exports.BaseFilter = BaseFilter;
  }
});

// node_modules/@grpc/grpc-js/build/src/compression-filter.js
var require_compression_filter = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/compression-filter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompressionFilterFactory = exports.CompressionFilter = void 0;
    var zlib2 = __require("zlib");
    var compression_algorithms_1 = require_compression_algorithms();
    var constants_1 = require_constants2();
    var filter_1 = require_filter();
    var logging = require_logging();
    var isCompressionAlgorithmKey = /* @__PURE__ */ __name((key) => {
      return typeof key === "number" && typeof compression_algorithms_1.CompressionAlgorithms[key] === "string";
    }, "isCompressionAlgorithmKey");
    var CompressionHandler = class {
      static {
        __name(this, "CompressionHandler");
      }
      /**
       * @param message Raw uncompressed message bytes
       * @param compress Indicates whether the message should be compressed
       * @return Framed message, compressed if applicable
       */
      async writeMessage(message, compress) {
        let messageBuffer = message;
        if (compress) {
          messageBuffer = await this.compressMessage(messageBuffer);
        }
        const output = Buffer.allocUnsafe(messageBuffer.length + 5);
        output.writeUInt8(compress ? 1 : 0, 0);
        output.writeUInt32BE(messageBuffer.length, 1);
        messageBuffer.copy(output, 5);
        return output;
      }
      /**
       * @param data Framed message, possibly compressed
       * @return Uncompressed message
       */
      async readMessage(data) {
        const compressed = data.readUInt8(0) === 1;
        let messageBuffer = data.slice(5);
        if (compressed) {
          messageBuffer = await this.decompressMessage(messageBuffer);
        }
        return messageBuffer;
      }
    };
    var IdentityHandler = class extends CompressionHandler {
      static {
        __name(this, "IdentityHandler");
      }
      async compressMessage(message) {
        return message;
      }
      async writeMessage(message, compress) {
        const output = Buffer.allocUnsafe(message.length + 5);
        output.writeUInt8(0, 0);
        output.writeUInt32BE(message.length, 1);
        message.copy(output, 5);
        return output;
      }
      decompressMessage(message) {
        return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity'));
      }
    };
    var DeflateHandler = class extends CompressionHandler {
      static {
        __name(this, "DeflateHandler");
      }
      constructor(maxRecvMessageLength) {
        super();
        this.maxRecvMessageLength = maxRecvMessageLength;
      }
      compressMessage(message) {
        return new Promise((resolve2, reject) => {
          zlib2.deflate(message, (err, output) => {
            if (err) {
              reject(err);
            } else {
              resolve2(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve2, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib2.createInflate();
          decompresser.on("error", (error) => {
            reject({
              code: constants_1.Status.INTERNAL,
              details: "Failed to decompress deflate-encoded message"
            });
          });
          decompresser.on("data", (chunk) => {
            messageParts.push(chunk);
            totalLength += chunk.byteLength;
            if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) {
              decompresser.destroy();
              reject({
                code: constants_1.Status.RESOURCE_EXHAUSTED,
                details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`
              });
            }
          });
          decompresser.on("end", () => {
            resolve2(Buffer.concat(messageParts));
          });
          decompresser.write(message);
          decompresser.end();
        });
      }
    };
    var GzipHandler = class extends CompressionHandler {
      static {
        __name(this, "GzipHandler");
      }
      constructor(maxRecvMessageLength) {
        super();
        this.maxRecvMessageLength = maxRecvMessageLength;
      }
      compressMessage(message) {
        return new Promise((resolve2, reject) => {
          zlib2.gzip(message, (err, output) => {
            if (err) {
              reject(err);
            } else {
              resolve2(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve2, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib2.createGunzip();
          decompresser.on("error", (error) => {
            reject({
              code: constants_1.Status.INTERNAL,
              details: "Failed to decompress gzip-encoded message"
            });
          });
          decompresser.on("data", (chunk) => {
            messageParts.push(chunk);
            totalLength += chunk.byteLength;
            if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) {
              decompresser.destroy();
              reject({
                code: constants_1.Status.RESOURCE_EXHAUSTED,
                details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`
              });
            }
          });
          decompresser.on("end", () => {
            resolve2(Buffer.concat(messageParts));
          });
          decompresser.write(message);
          decompresser.end();
        });
      }
    };
    var UnknownHandler = class extends CompressionHandler {
      static {
        __name(this, "UnknownHandler");
      }
      constructor(compressionName) {
        super();
        this.compressionName = compressionName;
      }
      compressMessage(message) {
        return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`));
      }
      decompressMessage(message) {
        return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`));
      }
    };
    function getCompressionHandler(compressionName, maxReceiveMessageSize) {
      switch (compressionName) {
        case "identity":
          return new IdentityHandler();
        case "deflate":
          return new DeflateHandler(maxReceiveMessageSize);
        case "gzip":
          return new GzipHandler(maxReceiveMessageSize);
        default:
          return new UnknownHandler(compressionName);
      }
    }
    __name(getCompressionHandler, "getCompressionHandler");
    var CompressionFilter = class extends filter_1.BaseFilter {
      static {
        __name(this, "CompressionFilter");
      }
      constructor(channelOptions, sharedFilterConfig) {
        var _a, _b, _c;
        super();
        this.sharedFilterConfig = sharedFilterConfig;
        this.sendCompression = new IdentityHandler();
        this.receiveCompression = new IdentityHandler();
        this.currentCompressionAlgorithm = "identity";
        const compressionAlgorithmKey = channelOptions["grpc.default_compression_algorithm"];
        this.maxReceiveMessageLength = (_a = channelOptions["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.maxSendMessageLength = (_b = channelOptions["grpc.max_send_message_length"]) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH;
        if (compressionAlgorithmKey !== void 0) {
          if (isCompressionAlgorithmKey(compressionAlgorithmKey)) {
            const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey];
            const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === void 0 ? void 0 : _c.split(",");
            if (!serverSupportedEncodings || serverSupportedEncodings.includes(clientSelectedEncoding)) {
              this.currentCompressionAlgorithm = clientSelectedEncoding;
              this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1);
            }
          } else {
            logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`);
          }
        }
      }
      async sendMetadata(metadata) {
        const headers = await metadata;
        headers.set("grpc-accept-encoding", "identity,deflate,gzip");
        headers.set("accept-encoding", "identity");
        if (this.currentCompressionAlgorithm === "identity") {
          headers.remove("grpc-encoding");
        } else {
          headers.set("grpc-encoding", this.currentCompressionAlgorithm);
        }
        return headers;
      }
      receiveMetadata(metadata) {
        const receiveEncoding = metadata.get("grpc-encoding");
        if (receiveEncoding.length > 0) {
          const encoding = receiveEncoding[0];
          if (typeof encoding === "string") {
            this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength);
          }
        }
        metadata.remove("grpc-encoding");
        const serverSupportedEncodingsHeader = metadata.get("grpc-accept-encoding")[0];
        if (serverSupportedEncodingsHeader) {
          this.sharedFilterConfig.serverSupportedEncodingHeader = serverSupportedEncodingsHeader;
          const serverSupportedEncodings = serverSupportedEncodingsHeader.split(",");
          if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) {
            this.sendCompression = new IdentityHandler();
            this.currentCompressionAlgorithm = "identity";
          }
        }
        metadata.remove("grpc-accept-encoding");
        return metadata;
      }
      async sendMessage(message) {
        var _a;
        const resolvedMessage = await message;
        if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) {
          throw {
            code: constants_1.Status.RESOURCE_EXHAUSTED,
            details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}`
          };
        }
        let compress;
        if (this.sendCompression instanceof IdentityHandler) {
          compress = false;
        } else {
          compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2) === 0;
        }
        return {
          message: await this.sendCompression.writeMessage(resolvedMessage.message, compress),
          flags: resolvedMessage.flags
        };
      }
      async receiveMessage(message) {
        return this.receiveCompression.readMessage(await message);
      }
    };
    exports.CompressionFilter = CompressionFilter;
    var CompressionFilterFactory = class {
      static {
        __name(this, "CompressionFilterFactory");
      }
      constructor(channel, options) {
        this.options = options;
        this.sharedFilterConfig = {};
      }
      createFilter() {
        return new CompressionFilter(this.options, this.sharedFilterConfig);
      }
    };
    exports.CompressionFilterFactory = CompressionFilterFactory;
  }
});

// node_modules/@grpc/grpc-js/build/src/control-plane-status.js
var require_control_plane_status = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/control-plane-status.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode;
    var constants_1 = require_constants2();
    var INAPPROPRIATE_CONTROL_PLANE_CODES = [
      constants_1.Status.OK,
      constants_1.Status.INVALID_ARGUMENT,
      constants_1.Status.NOT_FOUND,
      constants_1.Status.ALREADY_EXISTS,
      constants_1.Status.FAILED_PRECONDITION,
      constants_1.Status.ABORTED,
      constants_1.Status.OUT_OF_RANGE,
      constants_1.Status.DATA_LOSS
    ];
    function restrictControlPlaneStatusCode(code, details) {
      if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) {
        return {
          code: constants_1.Status.INTERNAL,
          details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}`
        };
      } else {
        return { code, details };
      }
    }
    __name(restrictControlPlaneStatusCode, "restrictControlPlaneStatusCode");
  }
});

// node_modules/@grpc/grpc-js/build/src/deadline.js
var require_deadline = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/deadline.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.minDeadline = minDeadline;
    exports.getDeadlineTimeoutString = getDeadlineTimeoutString;
    exports.getRelativeTimeout = getRelativeTimeout;
    exports.deadlineToString = deadlineToString;
    exports.formatDateDifference = formatDateDifference;
    function minDeadline(...deadlineList) {
      let minValue = Infinity;
      for (const deadline of deadlineList) {
        const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline;
        if (deadlineMsecs < minValue) {
          minValue = deadlineMsecs;
        }
      }
      return minValue;
    }
    __name(minDeadline, "minDeadline");
    var units = [
      ["m", 1],
      ["S", 1e3],
      ["M", 60 * 1e3],
      ["H", 60 * 60 * 1e3]
    ];
    function getDeadlineTimeoutString(deadline) {
      const now = (/* @__PURE__ */ new Date()).getTime();
      if (deadline instanceof Date) {
        deadline = deadline.getTime();
      }
      const timeoutMs = Math.max(deadline - now, 0);
      for (const [unit, factor] of units) {
        const amount = timeoutMs / factor;
        if (amount < 1e8) {
          return String(Math.ceil(amount)) + unit;
        }
      }
      throw new Error("Deadline is too far in the future");
    }
    __name(getDeadlineTimeoutString, "getDeadlineTimeoutString");
    var MAX_TIMEOUT_TIME = 2147483647;
    function getRelativeTimeout(deadline) {
      const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline;
      const now = (/* @__PURE__ */ new Date()).getTime();
      const timeout = deadlineMs - now;
      if (timeout < 0) {
        return 0;
      } else if (timeout > MAX_TIMEOUT_TIME) {
        return Infinity;
      } else {
        return timeout;
      }
    }
    __name(getRelativeTimeout, "getRelativeTimeout");
    function deadlineToString(deadline) {
      if (deadline instanceof Date) {
        return deadline.toISOString();
      } else {
        const dateDeadline = new Date(deadline);
        if (Number.isNaN(dateDeadline.getTime())) {
          return "" + deadline;
        } else {
          return dateDeadline.toISOString();
        }
      }
    }
    __name(deadlineToString, "deadlineToString");
    function formatDateDifference(startDate, endDate) {
      return ((endDate.getTime() - startDate.getTime()) / 1e3).toFixed(3) + "s";
    }
    __name(formatDateDifference, "formatDateDifference");
  }
});

// node_modules/@grpc/grpc-js/build/src/filter-stack.js
var require_filter_stack = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/filter-stack.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilterStackFactory = exports.FilterStack = void 0;
    var FilterStack = class {
      static {
        __name(this, "FilterStack");
      }
      constructor(filters) {
        this.filters = filters;
      }
      sendMetadata(metadata) {
        let result = metadata;
        for (let i = 0; i < this.filters.length; i++) {
          result = this.filters[i].sendMetadata(result);
        }
        return result;
      }
      receiveMetadata(metadata) {
        let result = metadata;
        for (let i = this.filters.length - 1; i >= 0; i--) {
          result = this.filters[i].receiveMetadata(result);
        }
        return result;
      }
      sendMessage(message) {
        let result = message;
        for (let i = 0; i < this.filters.length; i++) {
          result = this.filters[i].sendMessage(result);
        }
        return result;
      }
      receiveMessage(message) {
        let result = message;
        for (let i = this.filters.length - 1; i >= 0; i--) {
          result = this.filters[i].receiveMessage(result);
        }
        return result;
      }
      receiveTrailers(status) {
        let result = status;
        for (let i = this.filters.length - 1; i >= 0; i--) {
          result = this.filters[i].receiveTrailers(result);
        }
        return result;
      }
      push(filters) {
        this.filters.unshift(...filters);
      }
      getFilters() {
        return this.filters;
      }
    };
    exports.FilterStack = FilterStack;
    var FilterStackFactory = class _FilterStackFactory {
      static {
        __name(this, "FilterStackFactory");
      }
      constructor(factories) {
        this.factories = factories;
      }
      push(filterFactories) {
        this.factories.unshift(...filterFactories);
      }
      clone() {
        return new _FilterStackFactory([...this.factories]);
      }
      createFilter() {
        return new FilterStack(this.factories.map((factory) => factory.createFilter()));
      }
    };
    exports.FilterStackFactory = FilterStackFactory;
  }
});

// node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js
var require_single_subchannel_channel = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SingleSubchannelChannel = void 0;
    var call_number_1 = require_call_number();
    var channelz_1 = require_channelz();
    var compression_filter_1 = require_compression_filter();
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants2();
    var control_plane_status_1 = require_control_plane_status();
    var deadline_1 = require_deadline();
    var filter_stack_1 = require_filter_stack();
    var metadata_1 = require_metadata();
    var resolver_1 = require_resolver();
    var uri_parser_1 = require_uri_parser();
    var SubchannelCallWrapper = class {
      static {
        __name(this, "SubchannelCallWrapper");
      }
      constructor(subchannel, method, filterStackFactory, options, callNumber) {
        var _a, _b;
        this.subchannel = subchannel;
        this.method = method;
        this.options = options;
        this.callNumber = callNumber;
        this.childCall = null;
        this.pendingMessage = null;
        this.readPending = false;
        this.halfClosePending = false;
        this.pendingStatus = null;
        this.readFilterPending = false;
        this.writeFilterPending = false;
        const splitPath = this.method.split("/");
        let serviceName = "";
        if (splitPath.length >= 2) {
          serviceName = splitPath[1];
        }
        const hostname2 = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost";
        this.serviceUrl = `https://${hostname2}/${serviceName}`;
        const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline);
        if (timeout !== Infinity) {
          if (timeout <= 0) {
            this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded");
          } else {
            setTimeout(() => {
              this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded");
            }, timeout);
          }
        }
        this.filterStack = filterStackFactory.createFilter();
      }
      cancelWithStatus(status, details) {
        if (this.childCall) {
          this.childCall.cancelWithStatus(status, details);
        } else {
          this.pendingStatus = {
            code: status,
            details,
            metadata: new metadata_1.Metadata()
          };
        }
      }
      getPeer() {
        var _a, _b;
        return (_b = (_a = this.childCall) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.subchannel.getAddress();
      }
      async start(metadata, listener) {
        if (this.pendingStatus) {
          listener.onReceiveStatus(this.pendingStatus);
          return;
        }
        if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) {
          listener.onReceiveStatus({
            code: constants_1.Status.UNAVAILABLE,
            details: "Subchannel not ready",
            metadata: new metadata_1.Metadata()
          });
          return;
        }
        const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata));
        let credsMetadata;
        try {
          credsMetadata = await this.subchannel.getCallCredentials().generateMetadata({ method_name: this.method, service_url: this.serviceUrl });
        } catch (e) {
          const error = e;
          const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === "number" ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`);
          listener.onReceiveStatus({
            code,
            details,
            metadata: new metadata_1.Metadata()
          });
          return;
        }
        credsMetadata.merge(filteredMetadata);
        const childListener = {
          onReceiveMetadata: /* @__PURE__ */ __name(async (metadata2) => {
            listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata2));
          }, "onReceiveMetadata"),
          onReceiveMessage: /* @__PURE__ */ __name(async (message) => {
            this.readFilterPending = true;
            const filteredMessage = await this.filterStack.receiveMessage(message);
            this.readFilterPending = false;
            listener.onReceiveMessage(filteredMessage);
            if (this.pendingStatus) {
              listener.onReceiveStatus(this.pendingStatus);
            }
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name(async (status) => {
            const filteredStatus = await this.filterStack.receiveTrailers(status);
            if (this.readFilterPending) {
              this.pendingStatus = filteredStatus;
            } else {
              listener.onReceiveStatus(filteredStatus);
            }
          }, "onReceiveStatus")
        };
        this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener);
        if (this.readPending) {
          this.childCall.startRead();
        }
        if (this.pendingMessage) {
          this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message);
        }
        if (this.halfClosePending && !this.writeFilterPending) {
          this.childCall.halfClose();
        }
      }
      async sendMessageWithContext(context2, message) {
        this.writeFilterPending = true;
        const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message, flags: context2.flags }));
        this.writeFilterPending = false;
        if (this.childCall) {
          this.childCall.sendMessageWithContext(context2, filteredMessage.message);
          if (this.halfClosePending) {
            this.childCall.halfClose();
          }
        } else {
          this.pendingMessage = { context: context2, message: filteredMessage.message };
        }
      }
      startRead() {
        if (this.childCall) {
          this.childCall.startRead();
        } else {
          this.readPending = true;
        }
      }
      halfClose() {
        if (this.childCall && !this.writeFilterPending) {
          this.childCall.halfClose();
        } else {
          this.halfClosePending = true;
        }
      }
      getCallNumber() {
        return this.callNumber;
      }
      setCredentials(credentials) {
        throw new Error("Method not implemented.");
      }
      getAuthContext() {
        if (this.childCall) {
          return this.childCall.getAuthContext();
        } else {
          return null;
        }
      }
    };
    var SingleSubchannelChannel = class {
      static {
        __name(this, "SingleSubchannelChannel");
      }
      constructor(subchannel, target, options) {
        this.subchannel = subchannel;
        this.target = target;
        this.channelzEnabled = false;
        this.channelzTrace = new channelz_1.ChannelzTrace();
        this.callTracker = new channelz_1.ChannelzCallTracker();
        this.childrenTracker = new channelz_1.ChannelzChildrenTracker();
        this.channelzEnabled = options["grpc.enable_channelz"] !== 0;
        this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({
          target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`,
          state: this.subchannel.getConnectivityState(),
          trace: this.channelzTrace,
          callTracker: this.callTracker,
          children: this.childrenTracker.getChildLists()
        }), this.channelzEnabled);
        if (this.channelzEnabled) {
          this.childrenTracker.refChild(subchannel.getChannelzRef());
        }
        this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]);
      }
      close() {
        if (this.channelzEnabled) {
          this.childrenTracker.unrefChild(this.subchannel.getChannelzRef());
        }
        (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
      }
      getTarget() {
        return (0, uri_parser_1.uriToString)(this.target);
      }
      getConnectivityState(tryToConnect) {
        throw new Error("Method not implemented.");
      }
      watchConnectivityState(currentState, deadline, callback) {
        throw new Error("Method not implemented.");
      }
      getChannelzRef() {
        return this.channelzRef;
      }
      createCall(method, deadline) {
        const callOptions = {
          deadline,
          host: (0, resolver_1.getDefaultAuthority)(this.target),
          flags: constants_1.Propagate.DEFAULTS,
          parentCall: null
        };
        return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)());
      }
    };
    exports.SingleSubchannelChannel = SingleSubchannelChannel;
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel.js
var require_subchannel = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Subchannel = void 0;
    var connectivity_state_1 = require_connectivity_state();
    var backoff_timeout_1 = require_backoff_timeout();
    var logging = require_logging();
    var constants_1 = require_constants2();
    var uri_parser_1 = require_uri_parser();
    var subchannel_address_1 = require_subchannel_address();
    var channelz_1 = require_channelz();
    var single_subchannel_channel_1 = require_single_subchannel_channel();
    var TRACER_NAME = "subchannel";
    var KEEPALIVE_MAX_TIME_MS = ~(1 << 31);
    var Subchannel = class {
      static {
        __name(this, "Subchannel");
      }
      /**
       * A class representing a connection to a single backend.
       * @param channelTarget The target string for the channel as a whole
       * @param subchannelAddress The address for the backend that this subchannel
       *     will connect to
       * @param options The channel options, plus any specific subchannel options
       *     for this subchannel
       * @param credentials The channel credentials used to establish this
       *     connection
       */
      constructor(channelTarget, subchannelAddress, options, credentials, connector) {
        var _a;
        this.channelTarget = channelTarget;
        this.subchannelAddress = subchannelAddress;
        this.options = options;
        this.connector = connector;
        this.connectivityState = connectivity_state_1.ConnectivityState.IDLE;
        this.transport = null;
        this.continueConnecting = false;
        this.stateListeners = /* @__PURE__ */ new Set();
        this.refcount = 0;
        this.channelzEnabled = true;
        this.dataProducers = /* @__PURE__ */ new Map();
        this.subchannelChannel = null;
        const backoffOptions = {
          initialDelay: options["grpc.initial_reconnect_backoff_ms"],
          maxDelay: options["grpc.max_reconnect_backoff_ms"]
        };
        this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {
          this.handleBackoffTimer();
        }, backoffOptions);
        this.backoffTimeout.unref();
        this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress);
        this.keepaliveTime = (_a = options["grpc.keepalive_time_ms"]) !== null && _a !== void 0 ? _a : -1;
        if (options["grpc.enable_channelz"] === 0) {
          this.channelzEnabled = false;
          this.channelzTrace = new channelz_1.ChannelzTraceStub();
          this.callTracker = new channelz_1.ChannelzCallTrackerStub();
          this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub();
          this.streamTracker = new channelz_1.ChannelzCallTrackerStub();
        } else {
          this.channelzTrace = new channelz_1.ChannelzTrace();
          this.callTracker = new channelz_1.ChannelzCallTracker();
          this.childrenTracker = new channelz_1.ChannelzChildrenTracker();
          this.streamTracker = new channelz_1.ChannelzCallTracker();
        }
        this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled);
        this.channelzTrace.addTrace("CT_INFO", "Subchannel created");
        this.trace("Subchannel constructed with options " + JSON.stringify(options, void 0, 2));
        this.secureConnector = credentials._createSecureConnector(channelTarget, options);
      }
      getChannelzInfo() {
        return {
          state: this.connectivityState,
          trace: this.channelzTrace,
          callTracker: this.callTracker,
          children: this.childrenTracker.getChildLists(),
          target: this.subchannelAddressString
        };
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      refTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      handleBackoffTimer() {
        if (this.continueConnecting) {
          this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING);
        } else {
          this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE);
        }
      }
      /**
       * Start a backoff timer with the current nextBackoff timeout
       */
      startBackoff() {
        this.backoffTimeout.runOnce();
      }
      stopBackoff() {
        this.backoffTimeout.stop();
        this.backoffTimeout.reset();
      }
      startConnectingInternal() {
        let options = this.options;
        if (options["grpc.keepalive_time_ms"]) {
          const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS);
          options = Object.assign(Object.assign({}, options), { "grpc.keepalive_time_ms": adjustedKeepaliveTime });
        }
        this.connector.connect(this.subchannelAddress, this.secureConnector, options).then((transport) => {
          if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) {
            this.transport = transport;
            if (this.channelzEnabled) {
              this.childrenTracker.refChild(transport.getChannelzRef());
            }
            transport.addDisconnectListener((tooManyPings) => {
              this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE);
              if (tooManyPings && this.keepaliveTime > 0) {
                this.keepaliveTime *= 2;
                logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`);
              }
            });
          } else {
            transport.shutdown();
          }
        }, (error) => {
          this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`);
        });
      }
      /**
       * Initiate a state transition from any element of oldStates to the new
       * state. If the current connectivityState is not in oldStates, do nothing.
       * @param oldStates The set of states to transition from
       * @param newState The state to transition to
       * @returns True if the state changed, false otherwise
       */
      transitionToState(oldStates, newState, errorMessage2) {
        var _a, _b;
        if (oldStates.indexOf(this.connectivityState) === -1) {
          return false;
        }
        if (errorMessage2) {
          this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage2 + '"');
        } else {
          this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        }
        if (this.channelzEnabled) {
          this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]);
        }
        const previousState = this.connectivityState;
        this.connectivityState = newState;
        switch (newState) {
          case connectivity_state_1.ConnectivityState.READY:
            this.stopBackoff();
            break;
          case connectivity_state_1.ConnectivityState.CONNECTING:
            this.startBackoff();
            this.startConnectingInternal();
            this.continueConnecting = false;
            break;
          case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE:
            if (this.channelzEnabled && this.transport) {
              this.childrenTracker.unrefChild(this.transport.getChannelzRef());
            }
            (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown();
            this.transport = null;
            if (!this.backoffTimeout.isRunning()) {
              process.nextTick(() => {
                this.handleBackoffTimer();
              });
            }
            break;
          case connectivity_state_1.ConnectivityState.IDLE:
            if (this.channelzEnabled && this.transport) {
              this.childrenTracker.unrefChild(this.transport.getChannelzRef());
            }
            (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown();
            this.transport = null;
            break;
          default:
            throw new Error(`Invalid state: unknown ConnectivityState ${newState}`);
        }
        for (const listener of this.stateListeners) {
          listener(this, previousState, newState, this.keepaliveTime, errorMessage2);
        }
        return true;
      }
      ref() {
        this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1));
        this.refcount += 1;
      }
      unref() {
        this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1));
        this.refcount -= 1;
        if (this.refcount === 0) {
          this.channelzTrace.addTrace("CT_INFO", "Shutting down");
          (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
          this.secureConnector.destroy();
          process.nextTick(() => {
            this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE);
          });
        }
      }
      unrefIfOneRef() {
        if (this.refcount === 1) {
          this.unref();
          return true;
        }
        return false;
      }
      createCall(metadata, host, method, listener) {
        if (!this.transport) {
          throw new Error("Cannot create call, subchannel not READY");
        }
        let statsTracker;
        if (this.channelzEnabled) {
          this.callTracker.addCallStarted();
          this.streamTracker.addCallStarted();
          statsTracker = {
            onCallEnd: /* @__PURE__ */ __name((status) => {
              if (status.code === constants_1.Status.OK) {
                this.callTracker.addCallSucceeded();
              } else {
                this.callTracker.addCallFailed();
              }
            }, "onCallEnd")
          };
        } else {
          statsTracker = {};
        }
        return this.transport.createCall(metadata, host, method, listener, statsTracker);
      }
      /**
       * If the subchannel is currently IDLE, start connecting and switch to the
       * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE,
       * the next time it would transition to IDLE, start connecting again instead.
       * Otherwise, do nothing.
       */
      startConnecting() {
        process.nextTick(() => {
          if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) {
            if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
              this.continueConnecting = true;
            }
          }
        });
      }
      /**
       * Get the subchannel's current connectivity state.
       */
      getConnectivityState() {
        return this.connectivityState;
      }
      /**
       * Add a listener function to be called whenever the subchannel's
       * connectivity state changes.
       * @param listener
       */
      addConnectivityStateListener(listener) {
        this.stateListeners.add(listener);
      }
      /**
       * Remove a listener previously added with `addConnectivityStateListener`
       * @param listener A reference to a function previously passed to
       *     `addConnectivityStateListener`
       */
      removeConnectivityStateListener(listener) {
        this.stateListeners.delete(listener);
      }
      /**
       * Reset the backoff timeout, and immediately start connecting if in backoff.
       */
      resetBackoff() {
        process.nextTick(() => {
          this.backoffTimeout.reset();
          this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING);
        });
      }
      getAddress() {
        return this.subchannelAddressString;
      }
      getChannelzRef() {
        return this.channelzRef;
      }
      isHealthy() {
        return true;
      }
      addHealthStateWatcher(listener) {
      }
      removeHealthStateWatcher(listener) {
      }
      getRealSubchannel() {
        return this;
      }
      realSubchannelEquals(other) {
        return other.getRealSubchannel() === this;
      }
      throttleKeepalive(newKeepaliveTime) {
        if (newKeepaliveTime > this.keepaliveTime) {
          this.keepaliveTime = newKeepaliveTime;
        }
      }
      getCallCredentials() {
        return this.secureConnector.getCallCredentials();
      }
      getChannel() {
        if (!this.subchannelChannel) {
          this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options);
        }
        return this.subchannelChannel;
      }
      addDataWatcher(dataWatcher) {
        throw new Error("Not implemented");
      }
      getOrCreateDataProducer(name, createDataProducer) {
        const existingProducer = this.dataProducers.get(name);
        if (existingProducer) {
          return existingProducer;
        }
        const newProducer = createDataProducer(this);
        this.dataProducers.set(name, newProducer);
        return newProducer;
      }
      removeDataProducer(name) {
        this.dataProducers.delete(name);
      }
    };
    exports.Subchannel = Subchannel;
  }
});

// node_modules/@grpc/grpc-js/build/src/environment.js
var require_environment2 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/environment.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var _a;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0;
    exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : "false") === "true";
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver-dns.js
var require_resolver_dns = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver-dns.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DEFAULT_PORT = void 0;
    exports.setup = setup;
    var resolver_1 = require_resolver();
    var dns_1 = __require("dns");
    var service_config_1 = require_service_config();
    var constants_1 = require_constants2();
    var call_interface_1 = require_call_interface();
    var metadata_1 = require_metadata();
    var logging = require_logging();
    var constants_2 = require_constants2();
    var uri_parser_1 = require_uri_parser();
    var net_1 = __require("net");
    var backoff_timeout_1 = require_backoff_timeout();
    var environment_1 = require_environment2();
    var TRACER_NAME = "dns_resolver";
    function trace2(text) {
      logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    exports.DEFAULT_PORT = 443;
    var DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 3e4;
    var DnsResolver = class {
      static {
        __name(this, "DnsResolver");
      }
      constructor(target, listener, channelOptions) {
        var _a, _b, _c;
        this.target = target;
        this.listener = listener;
        this.pendingLookupPromise = null;
        this.pendingTxtPromise = null;
        this.latestLookupResult = null;
        this.latestServiceConfigResult = null;
        this.continueResolving = false;
        this.isNextResolutionTimerRunning = false;
        this.isServiceConfigEnabled = true;
        this.returnedIpResult = false;
        this.alternativeResolver = new dns_1.promises.Resolver();
        trace2("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target));
        if (target.authority) {
          this.alternativeResolver.setServers([target.authority]);
        }
        const hostPort = (0, uri_parser_1.splitHostPort)(target.path);
        if (hostPort === null) {
          this.ipResult = null;
          this.dnsHostname = null;
          this.port = null;
        } else {
          if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) {
            this.ipResult = [
              {
                addresses: [
                  {
                    host: hostPort.host,
                    port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports.DEFAULT_PORT
                  }
                ]
              }
            ];
            this.dnsHostname = null;
            this.port = null;
          } else {
            this.ipResult = null;
            this.dnsHostname = hostPort.host;
            this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports.DEFAULT_PORT;
          }
        }
        this.percentage = Math.random() * 100;
        if (channelOptions["grpc.service_config_disable_resolution"] === 1) {
          this.isServiceConfigEnabled = false;
        }
        this.defaultResolutionError = {
          code: constants_1.Status.UNAVAILABLE,
          details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`,
          metadata: new metadata_1.Metadata()
        };
        const backoffOptions = {
          initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"],
          maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"]
        };
        this.backoff = new backoff_timeout_1.BackoffTimeout(() => {
          if (this.continueResolving) {
            this.startResolutionWithBackoff();
          }
        }, backoffOptions);
        this.backoff.unref();
        this.minTimeBetweenResolutionsMs = (_c = channelOptions["grpc.dns_min_time_between_resolutions_ms"]) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS;
        this.nextResolutionTimer = setTimeout(() => {
        }, 0);
        clearTimeout(this.nextResolutionTimer);
      }
      /**
       * If the target is an IP address, just provide that address as a result.
       * Otherwise, initiate A, AAAA, and TXT lookups
       */
      startResolution() {
        if (this.ipResult !== null) {
          if (!this.returnedIpResult) {
            trace2("Returning IP address for target " + (0, uri_parser_1.uriToString)(this.target));
            setImmediate(() => {
              this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, "");
            });
            this.returnedIpResult = true;
          }
          this.backoff.stop();
          this.backoff.reset();
          this.stopNextResolutionTimer();
          return;
        }
        if (this.dnsHostname === null) {
          trace2("Failed to parse DNS address " + (0, uri_parser_1.uriToString)(this.target));
          setImmediate(() => {
            this.listener((0, call_interface_1.statusOrFromError)({
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}`
            }), {}, null, "");
          });
          this.stopNextResolutionTimer();
        } else {
          if (this.pendingLookupPromise !== null) {
            return;
          }
          trace2("Looking up DNS hostname " + this.dnsHostname);
          this.latestLookupResult = null;
          const hostname2 = this.dnsHostname;
          this.pendingLookupPromise = this.lookup(hostname2);
          this.pendingLookupPromise.then((addressList) => {
            if (this.pendingLookupPromise === null) {
              return;
            }
            this.pendingLookupPromise = null;
            this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map((address) => ({
              addresses: [address]
            })));
            const allAddressesString = "[" + addressList.map((addr) => addr.host + ":" + addr.port).join(",") + "]";
            trace2("Resolved addresses for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + allAddressesString);
            const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, "");
            this.handleHealthStatus(healthStatus);
          }, (err) => {
            if (this.pendingLookupPromise === null) {
              return;
            }
            trace2("Resolution error for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + err.message);
            this.pendingLookupPromise = null;
            this.stopNextResolutionTimer();
            this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, "");
          });
          if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) {
            this.pendingTxtPromise = this.resolveTxt(hostname2);
            this.pendingTxtPromise.then((txtRecord) => {
              if (this.pendingTxtPromise === null) {
                return;
              }
              this.pendingTxtPromise = null;
              let serviceConfig;
              try {
                serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage);
                if (serviceConfig) {
                  this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig);
                } else {
                  this.latestServiceConfigResult = null;
                }
              } catch (err) {
                this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({
                  code: constants_1.Status.UNAVAILABLE,
                  details: `Parsing service config failed with error ${err.message}`
                });
              }
              if (this.latestLookupResult !== null) {
                this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, "");
              }
            }, (err) => {
            });
          }
        }
      }
      /**
       * The ResolverListener returns a boolean indicating whether the LB policy
       * accepted the resolution result. A false result on an otherwise successful
       * resolution should be treated as a resolution failure.
       * @param healthStatus
       */
      handleHealthStatus(healthStatus) {
        if (healthStatus) {
          this.backoff.stop();
          this.backoff.reset();
        } else {
          this.continueResolving = true;
        }
      }
      async lookup(hostname2) {
        if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
          trace2("Using alternative DNS resolver.");
          const records = await Promise.allSettled([
            this.alternativeResolver.resolve4(hostname2),
            this.alternativeResolver.resolve6(hostname2)
          ]);
          if (records.every((result) => result.status === "rejected")) {
            throw new Error(records[0].reason);
          }
          return records.reduce((acc, result) => {
            return result.status === "fulfilled" ? [...acc, ...result.value] : acc;
          }, []).map((addr) => ({
            host: addr,
            port: +this.port
          }));
        }
        const addressList = await dns_1.promises.lookup(hostname2, { all: true });
        return addressList.map((addr) => ({ host: addr.address, port: +this.port }));
      }
      async resolveTxt(hostname2) {
        if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
          trace2("Using alternative DNS resolver.");
          return this.alternativeResolver.resolveTxt(hostname2);
        }
        return dns_1.promises.resolveTxt(hostname2);
      }
      startNextResolutionTimer() {
        var _a, _b;
        clearTimeout(this.nextResolutionTimer);
        this.nextResolutionTimer = setTimeout(() => {
          this.stopNextResolutionTimer();
          if (this.continueResolving) {
            this.startResolutionWithBackoff();
          }
        }, this.minTimeBetweenResolutionsMs);
        (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
        this.isNextResolutionTimerRunning = true;
      }
      stopNextResolutionTimer() {
        clearTimeout(this.nextResolutionTimer);
        this.isNextResolutionTimerRunning = false;
      }
      startResolutionWithBackoff() {
        if (this.pendingLookupPromise === null) {
          this.continueResolving = false;
          this.backoff.runOnce();
          this.startNextResolutionTimer();
          this.startResolution();
        }
      }
      updateResolution() {
        if (this.pendingLookupPromise === null) {
          if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) {
            if (this.isNextResolutionTimerRunning) {
              trace2('resolution update delayed by "min time between resolutions" rate limit');
            } else {
              trace2("resolution update delayed by backoff timer until " + this.backoff.getEndTime().toISOString());
            }
            this.continueResolving = true;
          } else {
            this.startResolutionWithBackoff();
          }
        }
      }
      /**
       * Reset the resolver to the same state it had when it was created. In-flight
       * DNS requests cannot be cancelled, but they are discarded and their results
       * will be ignored.
       */
      destroy() {
        this.continueResolving = false;
        this.backoff.reset();
        this.backoff.stop();
        this.stopNextResolutionTimer();
        this.pendingLookupPromise = null;
        this.pendingTxtPromise = null;
        this.latestLookupResult = null;
        this.latestServiceConfigResult = null;
        this.returnedIpResult = false;
      }
      /**
       * Get the default authority for the given target. For IP targets, that is
       * the IP address. For DNS targets, it is the hostname.
       * @param target
       */
      static getDefaultAuthority(target) {
        return target.path;
      }
    };
    function setup() {
      (0, resolver_1.registerResolver)("dns", DnsResolver);
      (0, resolver_1.registerDefaultScheme)("dns");
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/http_proxy.js
var require_http_proxy = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/http_proxy.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseCIDR = parseCIDR;
    exports.mapProxyName = mapProxyName;
    exports.getProxiedConnection = getProxiedConnection;
    var logging_1 = require_logging();
    var constants_1 = require_constants2();
    var net_1 = __require("net");
    var http2 = __require("http");
    var logging = require_logging();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var url_1 = __require("url");
    var resolver_dns_1 = require_resolver_dns();
    var TRACER_NAME = "proxy";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    function getProxyInfo() {
      let proxyEnv = "";
      let envVar = "";
      if (process.env.grpc_proxy) {
        envVar = "grpc_proxy";
        proxyEnv = process.env.grpc_proxy;
      } else if (process.env.https_proxy) {
        envVar = "https_proxy";
        proxyEnv = process.env.https_proxy;
      } else if (process.env.http_proxy) {
        envVar = "http_proxy";
        proxyEnv = process.env.http_proxy;
      } else {
        return {};
      }
      let proxyUrl;
      try {
        proxyUrl = new url_1.URL(proxyEnv);
      } catch (e) {
        (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`);
        return {};
      }
      if (proxyUrl.protocol !== "http:") {
        (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`);
        return {};
      }
      let userCred = null;
      if (proxyUrl.username) {
        if (proxyUrl.password) {
          (0, logging_1.log)(constants_1.LogVerbosity.INFO, "userinfo found in proxy URI");
          userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`);
        } else {
          userCred = proxyUrl.username;
        }
      }
      const hostname2 = proxyUrl.hostname;
      let port = proxyUrl.port;
      if (port === "") {
        port = "80";
      }
      const result = {
        address: `${hostname2}:${port}`
      };
      if (userCred) {
        result.creds = userCred;
      }
      trace2("Proxy server " + result.address + " set by environment variable " + envVar);
      return result;
    }
    __name(getProxyInfo, "getProxyInfo");
    function getNoProxyHostList() {
      let noProxyStr = process.env.no_grpc_proxy;
      let envVar = "no_grpc_proxy";
      if (!noProxyStr) {
        noProxyStr = process.env.no_proxy;
        envVar = "no_proxy";
      }
      if (noProxyStr) {
        trace2("No proxy server list set by environment variable " + envVar);
        return noProxyStr.split(",");
      } else {
        return [];
      }
    }
    __name(getNoProxyHostList, "getNoProxyHostList");
    function parseCIDR(cidrString) {
      const splitRange = cidrString.split("/");
      if (splitRange.length !== 2) {
        return null;
      }
      const prefixLength = parseInt(splitRange[1], 10);
      if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) {
        return null;
      }
      return {
        ip: ipToInt(splitRange[0]),
        prefixLength
      };
    }
    __name(parseCIDR, "parseCIDR");
    function ipToInt(ip) {
      return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
    }
    __name(ipToInt, "ipToInt");
    function isIpInCIDR(cidr, serverHost) {
      const ip = cidr.ip;
      const mask = -1 << 32 - cidr.prefixLength;
      const hostIP = ipToInt(serverHost);
      return (hostIP & mask) === (ip & mask);
    }
    __name(isIpInCIDR, "isIpInCIDR");
    function hostMatchesNoProxyList(serverHost) {
      for (const host of getNoProxyHostList()) {
        const parsedCIDR = parseCIDR(host);
        if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) {
          return true;
        } else if (serverHost.endsWith(host)) {
          return true;
        }
      }
      return false;
    }
    __name(hostMatchesNoProxyList, "hostMatchesNoProxyList");
    function mapProxyName(target, options) {
      var _a;
      const noProxyResult = {
        target,
        extraOptions: {}
      };
      if (((_a = options["grpc.enable_http_proxy"]) !== null && _a !== void 0 ? _a : 1) === 0) {
        return noProxyResult;
      }
      if (target.scheme === "unix") {
        return noProxyResult;
      }
      const proxyInfo = getProxyInfo();
      if (!proxyInfo.address) {
        return noProxyResult;
      }
      const hostPort = (0, uri_parser_1.splitHostPort)(target.path);
      if (!hostPort) {
        return noProxyResult;
      }
      const serverHost = hostPort.host;
      if (hostMatchesNoProxyList(serverHost)) {
        trace2("Not using proxy for target in no_proxy list: " + (0, uri_parser_1.uriToString)(target));
        return noProxyResult;
      }
      const extraOptions = {
        "grpc.http_connect_target": (0, uri_parser_1.uriToString)(target)
      };
      if (proxyInfo.creds) {
        extraOptions["grpc.http_connect_creds"] = proxyInfo.creds;
      }
      return {
        target: {
          scheme: "dns",
          path: proxyInfo.address
        },
        extraOptions
      };
    }
    __name(mapProxyName, "mapProxyName");
    function getProxiedConnection(address, channelOptions) {
      var _a;
      if (!("grpc.http_connect_target" in channelOptions)) {
        return Promise.resolve(null);
      }
      const realTarget = channelOptions["grpc.http_connect_target"];
      const parsedTarget = (0, uri_parser_1.parseUri)(realTarget);
      if (parsedTarget === null) {
        return Promise.resolve(null);
      }
      const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path);
      if (splitHostPost === null) {
        return Promise.resolve(null);
      }
      const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`;
      const options = {
        method: "CONNECT",
        path: hostPort
      };
      const headers = {
        Host: hostPort
      };
      if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) {
        options.host = address.host;
        options.port = address.port;
      } else {
        options.socketPath = address.path;
      }
      if ("grpc.http_connect_creds" in channelOptions) {
        headers["Proxy-Authorization"] = "Basic " + Buffer.from(channelOptions["grpc.http_connect_creds"]).toString("base64");
      }
      options.headers = headers;
      const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address);
      trace2("Using proxy " + proxyAddressString + " to connect to " + options.path);
      return new Promise((resolve2, reject) => {
        const request4 = http2.request(options);
        request4.once("connect", (res, socket, head) => {
          request4.removeAllListeners();
          socket.removeAllListeners();
          if (res.statusCode === 200) {
            trace2("Successfully connected to " + options.path + " through proxy " + proxyAddressString);
            if (head.length > 0) {
              socket.unshift(head);
            }
            trace2("Successfully established a plaintext connection to " + options.path + " through proxy " + proxyAddressString);
            resolve2(socket);
          } else {
            (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to " + options.path + " through proxy " + proxyAddressString + " with status " + res.statusCode);
            reject();
          }
        });
        request4.once("error", (err) => {
          request4.removeAllListeners();
          (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to proxy " + proxyAddressString + " with error " + err.message);
          reject();
        });
        request4.end();
      });
    }
    __name(getProxiedConnection, "getProxiedConnection");
  }
});

// node_modules/@grpc/grpc-js/build/src/stream-decoder.js
var require_stream_decoder = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/stream-decoder.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StreamDecoder = void 0;
    var ReadState;
    (function(ReadState2) {
      ReadState2[ReadState2["NO_DATA"] = 0] = "NO_DATA";
      ReadState2[ReadState2["READING_SIZE"] = 1] = "READING_SIZE";
      ReadState2[ReadState2["READING_MESSAGE"] = 2] = "READING_MESSAGE";
    })(ReadState || (ReadState = {}));
    var StreamDecoder = class {
      static {
        __name(this, "StreamDecoder");
      }
      constructor(maxReadMessageLength) {
        this.maxReadMessageLength = maxReadMessageLength;
        this.readState = ReadState.NO_DATA;
        this.readCompressFlag = Buffer.alloc(1);
        this.readPartialSize = Buffer.alloc(4);
        this.readSizeRemaining = 4;
        this.readMessageSize = 0;
        this.readPartialMessage = [];
        this.readMessageRemaining = 0;
      }
      write(data) {
        let readHead = 0;
        let toRead;
        const result = [];
        while (readHead < data.length) {
          switch (this.readState) {
            case ReadState.NO_DATA:
              this.readCompressFlag = data.slice(readHead, readHead + 1);
              readHead += 1;
              this.readState = ReadState.READING_SIZE;
              this.readPartialSize.fill(0);
              this.readSizeRemaining = 4;
              this.readMessageSize = 0;
              this.readMessageRemaining = 0;
              this.readPartialMessage = [];
              break;
            case ReadState.READING_SIZE:
              toRead = Math.min(data.length - readHead, this.readSizeRemaining);
              data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead);
              this.readSizeRemaining -= toRead;
              readHead += toRead;
              if (this.readSizeRemaining === 0) {
                this.readMessageSize = this.readPartialSize.readUInt32BE(0);
                if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) {
                  throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`);
                }
                this.readMessageRemaining = this.readMessageSize;
                if (this.readMessageRemaining > 0) {
                  this.readState = ReadState.READING_MESSAGE;
                } else {
                  const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5);
                  this.readState = ReadState.NO_DATA;
                  result.push(message);
                }
              }
              break;
            case ReadState.READING_MESSAGE:
              toRead = Math.min(data.length - readHead, this.readMessageRemaining);
              this.readPartialMessage.push(data.slice(readHead, readHead + toRead));
              this.readMessageRemaining -= toRead;
              readHead += toRead;
              if (this.readMessageRemaining === 0) {
                const framedMessageBuffers = [
                  this.readCompressFlag,
                  this.readPartialSize
                ].concat(this.readPartialMessage);
                const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5);
                this.readState = ReadState.NO_DATA;
                result.push(framedMessage);
              }
              break;
            default:
              throw new Error("Unexpected read state");
          }
        }
        return result;
      }
    };
    exports.StreamDecoder = StreamDecoder;
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-call.js
var require_subchannel_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-call.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Http2SubchannelCall = void 0;
    var http2 = __require("http2");
    var os4 = __require("os");
    var constants_1 = require_constants2();
    var metadata_1 = require_metadata();
    var stream_decoder_1 = require_stream_decoder();
    var logging = require_logging();
    var constants_2 = require_constants2();
    var TRACER_NAME = "subchannel_call";
    function getSystemErrorName(errno) {
      for (const [name, num] of Object.entries(os4.constants.errno)) {
        if (num === errno) {
          return name;
        }
      }
      return "Unknown system error " + errno;
    }
    __name(getSystemErrorName, "getSystemErrorName");
    function mapHttpStatusCode(code) {
      const details = `Received HTTP status code ${code}`;
      let mappedStatusCode;
      switch (code) {
        // TODO(murgatroid99): handle 100 and 101
        case 400:
          mappedStatusCode = constants_1.Status.INTERNAL;
          break;
        case 401:
          mappedStatusCode = constants_1.Status.UNAUTHENTICATED;
          break;
        case 403:
          mappedStatusCode = constants_1.Status.PERMISSION_DENIED;
          break;
        case 404:
          mappedStatusCode = constants_1.Status.UNIMPLEMENTED;
          break;
        case 429:
        case 502:
        case 503:
        case 504:
          mappedStatusCode = constants_1.Status.UNAVAILABLE;
          break;
        default:
          mappedStatusCode = constants_1.Status.UNKNOWN;
      }
      return {
        code: mappedStatusCode,
        details,
        metadata: new metadata_1.Metadata()
      };
    }
    __name(mapHttpStatusCode, "mapHttpStatusCode");
    var Http2SubchannelCall = class {
      static {
        __name(this, "Http2SubchannelCall");
      }
      constructor(http2Stream, callEventTracker, listener, transport, callId) {
        var _a;
        this.http2Stream = http2Stream;
        this.callEventTracker = callEventTracker;
        this.listener = listener;
        this.transport = transport;
        this.callId = callId;
        this.isReadFilterPending = false;
        this.isPushPending = false;
        this.canPush = false;
        this.readsClosed = false;
        this.statusOutput = false;
        this.unpushedReadMessages = [];
        this.finalStatus = null;
        this.internalError = null;
        this.serverEndedCall = false;
        this.connectionDropped = false;
        const maxReceiveMessageLength = (_a = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength);
        http2Stream.on("response", (headers, flags) => {
          let headersString = "";
          for (const header of Object.keys(headers)) {
            headersString += "		" + header + ": " + headers[header] + "\n";
          }
          this.trace("Received server headers:\n" + headersString);
          this.httpStatusCode = headers[":status"];
          if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) {
            this.handleTrailers(headers);
          } else {
            let metadata;
            try {
              metadata = metadata_1.Metadata.fromHttp2Headers(headers);
            } catch (error) {
              this.endCall({
                code: constants_1.Status.UNKNOWN,
                details: error.message,
                metadata: new metadata_1.Metadata()
              });
              return;
            }
            this.listener.onReceiveMetadata(metadata);
          }
        });
        http2Stream.on("trailers", (headers) => {
          this.handleTrailers(headers);
        });
        http2Stream.on("data", (data) => {
          if (this.statusOutput) {
            return;
          }
          this.trace("receive HTTP/2 data frame of length " + data.length);
          let messages;
          try {
            messages = this.decoder.write(data);
          } catch (e) {
            if (this.httpStatusCode !== void 0 && this.httpStatusCode !== 200) {
              const mappedStatus = mapHttpStatusCode(this.httpStatusCode);
              this.cancelWithStatus(mappedStatus.code, mappedStatus.details);
            } else {
              this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message);
            }
            return;
          }
          for (const message of messages) {
            this.trace("parsed message of length " + message.length);
            this.callEventTracker.addMessageReceived();
            this.tryPush(message);
          }
        });
        http2Stream.on("end", () => {
          this.readsClosed = true;
          this.maybeOutputStatus();
        });
        http2Stream.on("close", () => {
          this.serverEndedCall = true;
          process.nextTick(() => {
            var _a2;
            this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode);
            if (((_a2 = this.finalStatus) === null || _a2 === void 0 ? void 0 : _a2.code) === constants_1.Status.OK) {
              return;
            }
            let code;
            let details = "";
            switch (http2Stream.rstCode) {
              case http2.constants.NGHTTP2_NO_ERROR:
                if (this.finalStatus !== null) {
                  return;
                }
                if (this.httpStatusCode && this.httpStatusCode !== 200) {
                  const mappedStatus = mapHttpStatusCode(this.httpStatusCode);
                  code = mappedStatus.code;
                  details = mappedStatus.details;
                } else {
                  code = constants_1.Status.INTERNAL;
                  details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`;
                }
                break;
              case http2.constants.NGHTTP2_REFUSED_STREAM:
                code = constants_1.Status.UNAVAILABLE;
                details = "Stream refused by server";
                break;
              case http2.constants.NGHTTP2_CANCEL:
                if (this.connectionDropped) {
                  code = constants_1.Status.UNAVAILABLE;
                  details = "Connection dropped";
                } else {
                  code = constants_1.Status.CANCELLED;
                  details = "Call cancelled";
                }
                break;
              case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM:
                code = constants_1.Status.RESOURCE_EXHAUSTED;
                details = "Bandwidth exhausted or memory limit exceeded";
                break;
              case http2.constants.NGHTTP2_INADEQUATE_SECURITY:
                code = constants_1.Status.PERMISSION_DENIED;
                details = "Protocol not secure enough";
                break;
              case http2.constants.NGHTTP2_INTERNAL_ERROR:
                code = constants_1.Status.INTERNAL;
                if (this.internalError === null) {
                  details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`;
                } else {
                  if (this.internalError.code === "ECONNRESET" || this.internalError.code === "ETIMEDOUT") {
                    code = constants_1.Status.UNAVAILABLE;
                    details = this.internalError.message;
                  } else {
                    details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`;
                  }
                }
                break;
              default:
                code = constants_1.Status.INTERNAL;
                details = `Received RST_STREAM with code ${http2Stream.rstCode}`;
            }
            this.endCall({
              code,
              details,
              metadata: new metadata_1.Metadata(),
              rstCode: http2Stream.rstCode
            });
          });
        });
        http2Stream.on("error", (err) => {
          if (err.code !== "ERR_HTTP2_STREAM_ERROR") {
            this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall);
            this.internalError = err;
          }
          this.callEventTracker.onStreamEnd(false);
        });
      }
      getDeadlineInfo() {
        return [`remote_addr=${this.getPeer()}`];
      }
      onDisconnect() {
        this.connectionDropped = true;
        setImmediate(() => {
          this.endCall({
            code: constants_1.Status.UNAVAILABLE,
            details: "Connection dropped",
            metadata: new metadata_1.Metadata()
          });
        });
      }
      outputStatus() {
        if (!this.statusOutput) {
          this.statusOutput = true;
          this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"');
          this.callEventTracker.onCallEnd(this.finalStatus);
          process.nextTick(() => {
            this.listener.onReceiveStatus(this.finalStatus);
          });
          this.http2Stream.resume();
        }
      }
      trace(text) {
        logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text);
      }
      /**
       * On first call, emits a 'status' event with the given StatusObject.
       * Subsequent calls are no-ops.
       * @param status The status of the call.
       */
      endCall(status) {
        if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) {
          this.finalStatus = status;
          this.maybeOutputStatus();
        }
        this.destroyHttp2Stream();
      }
      maybeOutputStatus() {
        if (this.finalStatus !== null) {
          if (this.finalStatus.code !== constants_1.Status.OK || this.readsClosed && this.unpushedReadMessages.length === 0 && !this.isReadFilterPending && !this.isPushPending) {
            this.outputStatus();
          }
        }
      }
      push(message) {
        this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null));
        this.canPush = false;
        this.isPushPending = true;
        process.nextTick(() => {
          this.isPushPending = false;
          if (this.statusOutput) {
            return;
          }
          this.listener.onReceiveMessage(message);
          this.maybeOutputStatus();
        });
      }
      tryPush(messageBytes) {
        if (this.canPush) {
          this.http2Stream.pause();
          this.push(messageBytes);
        } else {
          this.trace("unpushedReadMessages.push message of length " + messageBytes.length);
          this.unpushedReadMessages.push(messageBytes);
        }
      }
      handleTrailers(headers) {
        this.serverEndedCall = true;
        this.callEventTracker.onStreamEnd(true);
        let headersString = "";
        for (const header of Object.keys(headers)) {
          headersString += "		" + header + ": " + headers[header] + "\n";
        }
        this.trace("Received server trailers:\n" + headersString);
        let metadata;
        try {
          metadata = metadata_1.Metadata.fromHttp2Headers(headers);
        } catch (e) {
          metadata = new metadata_1.Metadata();
        }
        const metadataMap = metadata.getMap();
        let status;
        if (typeof metadataMap["grpc-status"] === "string") {
          const receivedStatus = Number(metadataMap["grpc-status"]);
          this.trace("received status code " + receivedStatus + " from server");
          metadata.remove("grpc-status");
          let details = "";
          if (typeof metadataMap["grpc-message"] === "string") {
            try {
              details = decodeURI(metadataMap["grpc-message"]);
            } catch (e) {
              details = metadataMap["grpc-message"];
            }
            metadata.remove("grpc-message");
            this.trace('received status details string "' + details + '" from server');
          }
          status = {
            code: receivedStatus,
            details,
            metadata
          };
        } else if (this.httpStatusCode) {
          status = mapHttpStatusCode(this.httpStatusCode);
          status.metadata = metadata;
        } else {
          status = {
            code: constants_1.Status.UNKNOWN,
            details: "No status information received",
            metadata
          };
        }
        this.endCall(status);
      }
      destroyHttp2Stream() {
        var _a;
        if (this.http2Stream.destroyed) {
          return;
        }
        if (this.serverEndedCall) {
          this.http2Stream.end();
        } else {
          let code;
          if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) {
            code = http2.constants.NGHTTP2_NO_ERROR;
          } else {
            code = http2.constants.NGHTTP2_CANCEL;
          }
          this.trace("close http2 stream with code " + code);
          this.http2Stream.close(code);
        }
      }
      cancelWithStatus(status, details) {
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        this.endCall({ code: status, details, metadata: new metadata_1.Metadata() });
      }
      getStatus() {
        return this.finalStatus;
      }
      getPeer() {
        return this.transport.getPeerName();
      }
      getCallNumber() {
        return this.callId;
      }
      getAuthContext() {
        return this.transport.getAuthContext();
      }
      startRead() {
        if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) {
          this.readsClosed = true;
          this.maybeOutputStatus();
          return;
        }
        this.canPush = true;
        if (this.unpushedReadMessages.length > 0) {
          const nextMessage = this.unpushedReadMessages.shift();
          this.push(nextMessage);
          return;
        }
        this.http2Stream.resume();
      }
      sendMessageWithContext(context2, message) {
        this.trace("write() called with message of length " + message.length);
        const cb = /* @__PURE__ */ __name((error) => {
          process.nextTick(() => {
            var _a;
            let code = constants_1.Status.UNAVAILABLE;
            if ((error === null || error === void 0 ? void 0 : error.code) === "ERR_STREAM_WRITE_AFTER_END") {
              code = constants_1.Status.INTERNAL;
            }
            if (error) {
              this.cancelWithStatus(code, `Write error: ${error.message}`);
            }
            (_a = context2.callback) === null || _a === void 0 ? void 0 : _a.call(context2);
          });
        }, "cb");
        this.trace("sending data chunk of length " + message.length);
        this.callEventTracker.addMessageSent();
        try {
          this.http2Stream.write(message, cb);
        } catch (error) {
          this.endCall({
            code: constants_1.Status.UNAVAILABLE,
            details: `Write failed with error ${error.message}`,
            metadata: new metadata_1.Metadata()
          });
        }
      }
      halfClose() {
        this.trace("end() called");
        this.trace("calling end() on HTTP/2 stream");
        this.http2Stream.end();
      }
    };
    exports.Http2SubchannelCall = Http2SubchannelCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/transport.js
var require_transport = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/transport.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Http2SubchannelConnector = void 0;
    var http2 = __require("http2");
    var tls_1 = __require("tls");
    var channelz_1 = require_channelz();
    var constants_1 = require_constants2();
    var http_proxy_1 = require_http_proxy();
    var logging = require_logging();
    var resolver_1 = require_resolver();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var net = __require("net");
    var subchannel_call_1 = require_subchannel_call();
    var call_number_1 = require_call_number();
    var TRACER_NAME = "transport";
    var FLOW_CONTROL_TRACER_NAME = "transport_flowctrl";
    var clientVersion = require_package().version;
    var { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT } = http2.constants;
    var KEEPALIVE_TIMEOUT_MS = 2e4;
    var tooManyPingsData = Buffer.from("too_many_pings", "ascii");
    var Http2Transport = class {
      static {
        __name(this, "Http2Transport");
      }
      constructor(session, subchannelAddress, options, remoteName) {
        this.session = session;
        this.options = options;
        this.remoteName = remoteName;
        this.keepaliveTimer = null;
        this.pendingSendKeepalivePing = false;
        this.activeCalls = /* @__PURE__ */ new Set();
        this.disconnectListeners = [];
        this.disconnectHandled = false;
        this.channelzEnabled = true;
        this.keepalivesSent = 0;
        this.messagesSent = 0;
        this.messagesReceived = 0;
        this.lastMessageSentTimestamp = null;
        this.lastMessageReceivedTimestamp = null;
        this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress);
        if (options["grpc.enable_channelz"] === 0) {
          this.channelzEnabled = false;
          this.streamTracker = new channelz_1.ChannelzCallTrackerStub();
        } else {
          this.streamTracker = new channelz_1.ChannelzCallTracker();
        }
        this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled);
        this.userAgent = [
          options["grpc.primary_user_agent"],
          `grpc-node-js/${clientVersion}`,
          options["grpc.secondary_user_agent"]
        ].filter((e) => e).join(" ");
        if ("grpc.keepalive_time_ms" in options) {
          this.keepaliveTimeMs = options["grpc.keepalive_time_ms"];
        } else {
          this.keepaliveTimeMs = -1;
        }
        if ("grpc.keepalive_timeout_ms" in options) {
          this.keepaliveTimeoutMs = options["grpc.keepalive_timeout_ms"];
        } else {
          this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS;
        }
        if ("grpc.keepalive_permit_without_calls" in options) {
          this.keepaliveWithoutCalls = options["grpc.keepalive_permit_without_calls"] === 1;
        } else {
          this.keepaliveWithoutCalls = false;
        }
        session.once("close", () => {
          this.trace("session closed");
          this.handleDisconnect();
        });
        session.once("goaway", (errorCode, lastStreamID, opaqueData) => {
          let tooManyPings = false;
          if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && opaqueData && opaqueData.equals(tooManyPingsData)) {
            tooManyPings = true;
          }
          this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString()));
          this.reportDisconnectToOwner(tooManyPings);
        });
        session.once("error", (error) => {
          this.trace("connection closed with error " + error.message);
          this.handleDisconnect();
        });
        session.socket.once("close", (hadError) => {
          this.trace("connection closed. hadError=" + hadError);
          this.handleDisconnect();
        });
        if (logging.isTracerEnabled(TRACER_NAME)) {
          session.on("remoteSettings", (settings) => {
            this.trace("new settings received" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings));
          });
          session.on("localSettings", (settings) => {
            this.trace("local settings acknowledged by remote" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings));
          });
        }
        if (this.keepaliveWithoutCalls) {
          this.maybeStartKeepalivePingTimer();
        }
        if (session.socket instanceof tls_1.TLSSocket) {
          this.authContext = {
            transportSecurityType: "ssl",
            sslPeerCertificate: session.socket.getPeerCertificate()
          };
        } else {
          this.authContext = {};
        }
      }
      getChannelzInfo() {
        var _a, _b, _c;
        const sessionSocket = this.session.socket;
        const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null;
        const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null;
        let tlsInfo;
        if (this.session.encrypted) {
          const tlsSocket = sessionSocket;
          const cipherInfo = tlsSocket.getCipher();
          const certificate = tlsSocket.getCertificate();
          const peerCertificate = tlsSocket.getPeerCertificate();
          tlsInfo = {
            cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null,
            cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name,
            localCertificate: certificate && "raw" in certificate ? certificate.raw : null,
            remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null
          };
        } else {
          tlsInfo = null;
        }
        const socketInfo = {
          remoteAddress,
          localAddress,
          security: tlsInfo,
          remoteName: this.remoteName,
          streamsStarted: this.streamTracker.callsStarted,
          streamsSucceeded: this.streamTracker.callsSucceeded,
          streamsFailed: this.streamTracker.callsFailed,
          messagesSent: this.messagesSent,
          messagesReceived: this.messagesReceived,
          keepAlivesSent: this.keepalivesSent,
          lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp,
          lastRemoteStreamCreatedTimestamp: null,
          lastMessageSentTimestamp: this.lastMessageSentTimestamp,
          lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp,
          localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null,
          remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null
        };
        return socketInfo;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      keepaliveTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      flowControlTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      internalsTrace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text);
      }
      /**
       * Indicate to the owner of this object that this transport should no longer
       * be used. That happens if the connection drops, or if the server sends a
       * GOAWAY.
       * @param tooManyPings If true, this was triggered by a GOAWAY with data
       * indicating that the session was closed becaues the client sent too many
       * pings.
       * @returns
       */
      reportDisconnectToOwner(tooManyPings) {
        if (this.disconnectHandled) {
          return;
        }
        this.disconnectHandled = true;
        this.disconnectListeners.forEach((listener) => listener(tooManyPings));
      }
      /**
       * Handle connection drops, but not GOAWAYs.
       */
      handleDisconnect() {
        this.clearKeepaliveTimeout();
        this.reportDisconnectToOwner(false);
        for (const call of this.activeCalls) {
          call.onDisconnect();
        }
        setImmediate(() => {
          this.session.destroy();
        });
      }
      addDisconnectListener(listener) {
        this.disconnectListeners.push(listener);
      }
      canSendPing() {
        return !this.session.destroyed && this.keepaliveTimeMs > 0 && (this.keepaliveWithoutCalls || this.activeCalls.size > 0);
      }
      maybeSendPing() {
        var _a, _b;
        if (!this.canSendPing()) {
          this.pendingSendKeepalivePing = true;
          return;
        }
        if (this.keepaliveTimer) {
          console.error("keepaliveTimeout is not null");
          return;
        }
        if (this.channelzEnabled) {
          this.keepalivesSent += 1;
        }
        this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
        this.keepaliveTimer = setTimeout(() => {
          this.keepaliveTimer = null;
          this.keepaliveTrace("Ping timeout passed without response");
          this.handleDisconnect();
        }, this.keepaliveTimeoutMs);
        (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
        let pingSendError = "";
        try {
          const pingSentSuccessfully = this.session.ping((err, duration, payload) => {
            this.clearKeepaliveTimeout();
            if (err) {
              this.keepaliveTrace("Ping failed with error " + err.message);
              this.handleDisconnect();
            } else {
              this.keepaliveTrace("Received ping response");
              this.maybeStartKeepalivePingTimer();
            }
          });
          if (!pingSentSuccessfully) {
            pingSendError = "Ping returned false";
          }
        } catch (e) {
          pingSendError = (e instanceof Error ? e.message : "") || "Unknown error";
        }
        if (pingSendError) {
          this.keepaliveTrace("Ping send failed: " + pingSendError);
          this.handleDisconnect();
        }
      }
      /**
       * Starts the keepalive ping timer if appropriate. If the timer already ran
       * out while there were no active requests, instead send a ping immediately.
       * If the ping timer is already running or a ping is currently in flight,
       * instead do nothing and wait for them to resolve.
       */
      maybeStartKeepalivePingTimer() {
        var _a, _b;
        if (!this.canSendPing()) {
          return;
        }
        if (this.pendingSendKeepalivePing) {
          this.pendingSendKeepalivePing = false;
          this.maybeSendPing();
        } else if (!this.keepaliveTimer) {
          this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
          this.keepaliveTimer = setTimeout(() => {
            this.keepaliveTimer = null;
            this.maybeSendPing();
          }, this.keepaliveTimeMs);
          (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
        }
      }
      /**
       * Clears whichever keepalive timeout is currently active, if any.
       */
      clearKeepaliveTimeout() {
        if (this.keepaliveTimer) {
          clearTimeout(this.keepaliveTimer);
          this.keepaliveTimer = null;
        }
      }
      removeActiveCall(call) {
        this.activeCalls.delete(call);
        if (this.activeCalls.size === 0) {
          this.session.unref();
        }
      }
      addActiveCall(call) {
        this.activeCalls.add(call);
        if (this.activeCalls.size === 1) {
          this.session.ref();
          if (!this.keepaliveWithoutCalls) {
            this.maybeStartKeepalivePingTimer();
          }
        }
      }
      createCall(metadata, host, method, listener, subchannelCallStatsTracker) {
        const headers = metadata.toHttp2Headers();
        headers[HTTP2_HEADER_AUTHORITY] = host;
        headers[HTTP2_HEADER_USER_AGENT] = this.userAgent;
        headers[HTTP2_HEADER_CONTENT_TYPE] = "application/grpc";
        headers[HTTP2_HEADER_METHOD] = "POST";
        headers[HTTP2_HEADER_PATH] = method;
        headers[HTTP2_HEADER_TE] = "trailers";
        let http2Stream;
        try {
          http2Stream = this.session.request(headers);
        } catch (e) {
          this.handleDisconnect();
          throw e;
        }
        this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize);
        this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed);
        let eventTracker;
        let call;
        if (this.channelzEnabled) {
          this.streamTracker.addCallStarted();
          eventTracker = {
            addMessageSent: /* @__PURE__ */ __name(() => {
              var _a;
              this.messagesSent += 1;
              this.lastMessageSentTimestamp = /* @__PURE__ */ new Date();
              (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker);
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              var _a;
              this.messagesReceived += 1;
              this.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date();
              (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker);
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              var _a;
              (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status);
              this.removeActiveCall(call);
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              var _a;
              if (success) {
                this.streamTracker.addCallSucceeded();
              } else {
                this.streamTracker.addCallFailed();
              }
              (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success);
            }, "onStreamEnd")
          };
        } else {
          eventTracker = {
            addMessageSent: /* @__PURE__ */ __name(() => {
              var _a;
              (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker);
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              var _a;
              (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker);
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              var _a;
              (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status);
              this.removeActiveCall(call);
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              var _a;
              (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success);
            }, "onStreamEnd")
          };
        }
        call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)());
        this.addActiveCall(call);
        return call;
      }
      getChannelzRef() {
        return this.channelzRef;
      }
      getPeerName() {
        return this.subchannelAddressString;
      }
      getOptions() {
        return this.options;
      }
      getAuthContext() {
        return this.authContext;
      }
      shutdown() {
        this.session.close();
        (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
      }
    };
    var Http2SubchannelConnector = class {
      static {
        __name(this, "Http2SubchannelConnector");
      }
      constructor(channelTarget) {
        this.channelTarget = channelTarget;
        this.session = null;
        this.isShutdown = false;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text);
      }
      createSession(secureConnectResult, address, options) {
        if (this.isShutdown) {
          return Promise.reject();
        }
        if (secureConnectResult.socket.closed) {
          return Promise.reject("Connection closed before starting HTTP/2 handshake");
        }
        return new Promise((resolve2, reject) => {
          var _a, _b, _c, _d, _e, _f, _g, _h;
          let remoteName = null;
          let realTarget = this.channelTarget;
          if ("grpc.http_connect_target" in options) {
            const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]);
            if (parsedTarget) {
              realTarget = parsedTarget;
              remoteName = (0, uri_parser_1.uriToString)(parsedTarget);
            }
          }
          const scheme = secureConnectResult.secure ? "https" : "http";
          const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget);
          const closeHandler = /* @__PURE__ */ __name(() => {
            var _a2;
            (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy();
            this.session = null;
            setImmediate(() => {
              if (!reportedError) {
                reportedError = true;
                reject(`${errorMessage2.trim()} (${(/* @__PURE__ */ new Date()).toISOString()})`);
              }
            });
          }, "closeHandler");
          const errorHandler = /* @__PURE__ */ __name((error) => {
            var _a2;
            (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy();
            errorMessage2 = error.message;
            this.trace("connection failed with error " + errorMessage2);
            if (!reportedError) {
              reportedError = true;
              reject(`${errorMessage2} (${(/* @__PURE__ */ new Date()).toISOString()})`);
            }
          }, "errorHandler");
          const sessionOptions = {
            createConnection: /* @__PURE__ */ __name((authority, option) => {
              return secureConnectResult.socket;
            }, "createConnection"),
            settings: {
              initialWindowSize: (_d = (_a = options["grpc-node.flow_control_window"]) !== null && _a !== void 0 ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === void 0 ? void 0 : _b.call(http2)) === null || _c === void 0 ? void 0 : _c.initialWindowSize) !== null && _d !== void 0 ? _d : 65535
            },
            maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER,
            /* By default, set a very large max session memory limit, to effectively
             * disable enforcement of the limit. Some testing indicates that Node's
             * behavior degrades badly when this limit is reached, so we solve that
             * by disabling the check entirely. */
            maxSessionMemory: (_e = options["grpc-node.max_session_memory"]) !== null && _e !== void 0 ? _e : Number.MAX_SAFE_INTEGER
          };
          const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions);
          const defaultWin = (_h = (_g = (_f = http2.getDefaultSettings) === null || _f === void 0 ? void 0 : _f.call(http2)) === null || _g === void 0 ? void 0 : _g.initialWindowSize) !== null && _h !== void 0 ? _h : 65535;
          const connWin = options["grpc-node.flow_control_window"];
          this.session = session;
          let errorMessage2 = "Failed to connect";
          let reportedError = false;
          session.unref();
          session.once("remoteSettings", () => {
            var _a2;
            if (connWin && connWin > defaultWin) {
              try {
                session.setLocalWindowSize(connWin);
              } catch (_b2) {
                const delta = connWin - ((_a2 = session.state.localWindowSize) !== null && _a2 !== void 0 ? _a2 : defaultWin);
                if (delta > 0)
                  session.incrementWindowSize(delta);
              }
            }
            session.removeAllListeners();
            secureConnectResult.socket.removeListener("close", closeHandler);
            secureConnectResult.socket.removeListener("error", errorHandler);
            resolve2(new Http2Transport(session, address, options, remoteName));
            this.session = null;
          });
          session.once("close", closeHandler);
          session.once("error", errorHandler);
          secureConnectResult.socket.once("close", closeHandler);
          secureConnectResult.socket.once("error", errorHandler);
        });
      }
      tcpConnect(address, options) {
        return (0, http_proxy_1.getProxiedConnection)(address, options).then((proxiedSocket) => {
          if (proxiedSocket) {
            return proxiedSocket;
          } else {
            return new Promise((resolve2, reject) => {
              const closeCallback = /* @__PURE__ */ __name(() => {
                reject(new Error("Socket closed"));
              }, "closeCallback");
              const errorCallback = /* @__PURE__ */ __name((error) => {
                reject(error);
              }, "errorCallback");
              const socket = net.connect(address, () => {
                socket.removeListener("close", closeCallback);
                socket.removeListener("error", errorCallback);
                resolve2(socket);
              });
              socket.once("close", closeCallback);
              socket.once("error", errorCallback);
            });
          }
        });
      }
      async connect(address, secureConnector, options) {
        if (this.isShutdown) {
          return Promise.reject();
        }
        let tcpConnection = null;
        let secureConnectResult = null;
        const addressString = (0, subchannel_address_1.subchannelAddressToString)(address);
        try {
          this.trace(addressString + " Waiting for secureConnector to be ready");
          await secureConnector.waitForReady();
          this.trace(addressString + " secureConnector is ready");
          tcpConnection = await this.tcpConnect(address, options);
          tcpConnection.setNoDelay();
          this.trace(addressString + " Established TCP connection");
          secureConnectResult = await secureConnector.connect(tcpConnection);
          this.trace(addressString + " Established secure connection");
          return this.createSession(secureConnectResult, address, options);
        } catch (e) {
          tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy();
          secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy();
          throw e;
        }
      }
      shutdown() {
        var _a;
        this.isShutdown = true;
        (_a = this.session) === null || _a === void 0 ? void 0 : _a.close();
        this.session = null;
      }
    };
    exports.Http2SubchannelConnector = Http2SubchannelConnector;
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-pool.js
var require_subchannel_pool = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-pool.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SubchannelPool = void 0;
    exports.getSubchannelPool = getSubchannelPool;
    var channel_options_1 = require_channel_options();
    var subchannel_1 = require_subchannel();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var transport_1 = require_transport();
    var REF_CHECK_INTERVAL = 1e4;
    var SubchannelPool = class {
      static {
        __name(this, "SubchannelPool");
      }
      /**
       * A pool of subchannels use for making connections. Subchannels with the
       * exact same parameters will be reused.
       */
      constructor() {
        this.pool = /* @__PURE__ */ Object.create(null);
        this.cleanupTimer = null;
      }
      /**
       * Unrefs all unused subchannels and cancels the cleanup task if all
       * subchannels have been unrefed.
       */
      unrefUnusedSubchannels() {
        let allSubchannelsUnrefed = true;
        for (const channelTarget in this.pool) {
          const subchannelObjArray = this.pool[channelTarget];
          const refedSubchannels = subchannelObjArray.filter((value) => !value.subchannel.unrefIfOneRef());
          if (refedSubchannels.length > 0) {
            allSubchannelsUnrefed = false;
          }
          this.pool[channelTarget] = refedSubchannels;
        }
        if (allSubchannelsUnrefed && this.cleanupTimer !== null) {
          clearInterval(this.cleanupTimer);
          this.cleanupTimer = null;
        }
      }
      /**
       * Ensures that the cleanup task is spawned.
       */
      ensureCleanupTask() {
        var _a, _b;
        if (this.cleanupTimer === null) {
          this.cleanupTimer = setInterval(() => {
            this.unrefUnusedSubchannels();
          }, REF_CHECK_INTERVAL);
          (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
        }
      }
      /**
       * Get a subchannel if one already exists with exactly matching parameters.
       * Otherwise, create and save a subchannel with those parameters.
       * @param channelTarget
       * @param subchannelTarget
       * @param channelArguments
       * @param channelCredentials
       */
      getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) {
        this.ensureCleanupTask();
        const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri);
        if (channelTarget in this.pool) {
          const subchannelObjArray = this.pool[channelTarget];
          for (const subchannelObj of subchannelObjArray) {
            if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && channelCredentials._equals(subchannelObj.channelCredentials)) {
              return subchannelObj.subchannel;
            }
          }
        }
        const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri));
        if (!(channelTarget in this.pool)) {
          this.pool[channelTarget] = [];
        }
        this.pool[channelTarget].push({
          subchannelAddress: subchannelTarget,
          channelArguments,
          channelCredentials,
          subchannel
        });
        subchannel.ref();
        return subchannel;
      }
    };
    exports.SubchannelPool = SubchannelPool;
    var globalSubchannelPool = new SubchannelPool();
    function getSubchannelPool(global2) {
      if (global2) {
        return globalSubchannelPool;
      } else {
        return new SubchannelPool();
      }
    }
    __name(getSubchannelPool, "getSubchannelPool");
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancing-call.js
var require_load_balancing_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancing-call.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LoadBalancingCall = void 0;
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants2();
    var deadline_1 = require_deadline();
    var metadata_1 = require_metadata();
    var picker_1 = require_picker();
    var uri_parser_1 = require_uri_parser();
    var logging = require_logging();
    var control_plane_status_1 = require_control_plane_status();
    var http2 = __require("http2");
    var TRACER_NAME = "load_balancing_call";
    var LoadBalancingCall = class {
      static {
        __name(this, "LoadBalancingCall");
      }
      constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) {
        var _a, _b;
        this.channel = channel;
        this.callConfig = callConfig;
        this.methodName = methodName;
        this.host = host;
        this.credentials = credentials;
        this.deadline = deadline;
        this.callNumber = callNumber;
        this.child = null;
        this.readPending = false;
        this.pendingMessage = null;
        this.pendingHalfClose = false;
        this.ended = false;
        this.metadata = null;
        this.listener = null;
        this.onCallEnded = null;
        this.childStartTime = null;
        const splitPath = this.methodName.split("/");
        let serviceName = "";
        if (splitPath.length >= 2) {
          serviceName = splitPath[1];
        }
        const hostname2 = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost";
        this.serviceUrl = `https://${hostname2}/${serviceName}`;
        this.startTime = /* @__PURE__ */ new Date();
      }
      getDeadlineInfo() {
        var _a, _b;
        const deadlineInfo = [];
        if (this.childStartTime) {
          if (this.childStartTime > this.startTime) {
            if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) {
              deadlineInfo.push("wait_for_ready");
            }
            deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`);
          }
          deadlineInfo.push(...this.child.getDeadlineInfo());
          return deadlineInfo;
        } else {
          if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) {
            deadlineInfo.push("wait_for_ready");
          }
          deadlineInfo.push("Waiting for LB pick");
        }
        return deadlineInfo;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text);
      }
      outputStatus(status, progress) {
        var _a, _b;
        if (!this.ended) {
          this.ended = true;
          this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + this.startTime.toISOString());
          const finalStatus = Object.assign(Object.assign({}, status), { progress });
          (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus);
          (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata);
        }
      }
      doPick() {
        var _a, _b;
        if (this.ended) {
          return;
        }
        if (!this.metadata) {
          throw new Error("doPick called before start");
        }
        this.trace("Pick called");
        const finalMetadata = this.metadata.clone();
        const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation);
        const subchannelString = pickResult.subchannel ? "(" + pickResult.subchannel.getChannelzRef().id + ") " + pickResult.subchannel.getAddress() : "" + pickResult.subchannel;
        this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + subchannelString + " status: " + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + " " + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details));
        switch (pickResult.pickResultType) {
          case picker_1.PickResultType.COMPLETE:
            const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials());
            combinedCallCredentials.generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }).then((credsMetadata) => {
              var _a2;
              if (this.ended) {
                this.trace("Credentials metadata generation finished after call ended");
                return;
              }
              finalMetadata.merge(credsMetadata);
              if (finalMetadata.get("authorization").length > 1) {
                this.outputStatus({
                  code: constants_1.Status.INTERNAL,
                  details: '"authorization" metadata cannot have multiple values',
                  metadata: new metadata_1.Metadata()
                }, "PROCESSED");
              }
              if (pickResult.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) {
                this.trace("Picked subchannel " + subchannelString + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick");
                this.doPick();
                return;
              }
              if (this.deadline !== Infinity) {
                finalMetadata.set("grpc-timeout", (0, deadline_1.getDeadlineTimeoutString)(this.deadline));
              }
              try {
                this.child = pickResult.subchannel.getRealSubchannel().createCall(finalMetadata, this.host, this.methodName, {
                  onReceiveMetadata: /* @__PURE__ */ __name((metadata) => {
                    this.trace("Received metadata");
                    this.listener.onReceiveMetadata(metadata);
                  }, "onReceiveMetadata"),
                  onReceiveMessage: /* @__PURE__ */ __name((message) => {
                    this.trace("Received message");
                    this.listener.onReceiveMessage(message);
                  }, "onReceiveMessage"),
                  onReceiveStatus: /* @__PURE__ */ __name((status) => {
                    this.trace("Received status");
                    if (status.rstCode === http2.constants.NGHTTP2_REFUSED_STREAM) {
                      this.outputStatus(status, "REFUSED");
                    } else {
                      this.outputStatus(status, "PROCESSED");
                    }
                  }, "onReceiveStatus")
                });
                this.childStartTime = /* @__PURE__ */ new Date();
              } catch (error) {
                this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error.message);
                this.outputStatus({
                  code: constants_1.Status.INTERNAL,
                  details: "Failed to start HTTP/2 stream with error " + error.message,
                  metadata: new metadata_1.Metadata()
                }, "NOT_STARTED");
                return;
              }
              (_a2 = pickResult.onCallStarted) === null || _a2 === void 0 ? void 0 : _a2.call(pickResult);
              this.onCallEnded = pickResult.onCallEnded;
              this.trace("Created child call [" + this.child.getCallNumber() + "]");
              if (this.readPending) {
                this.child.startRead();
              }
              if (this.pendingMessage) {
                this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message);
              }
              if (this.pendingHalfClose) {
                this.child.halfClose();
              }
            }, (error) => {
              const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === "number" ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`);
              this.outputStatus({
                code: code2,
                details: details2,
                metadata: new metadata_1.Metadata()
              }, "PROCESSED");
            });
            break;
          case picker_1.PickResultType.DROP:
            const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details);
            setImmediate(() => {
              this.outputStatus({ code, details, metadata: pickResult.status.metadata }, "DROP");
            });
            break;
          case picker_1.PickResultType.TRANSIENT_FAILURE:
            if (this.metadata.getOptions().waitForReady) {
              this.channel.queueCallForPick(this);
            } else {
              const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details);
              setImmediate(() => {
                this.outputStatus({ code: code2, details: details2, metadata: pickResult.status.metadata }, "PROCESSED");
              });
            }
            break;
          case picker_1.PickResultType.QUEUE:
            this.channel.queueCallForPick(this);
        }
      }
      cancelWithStatus(status, details) {
        var _a;
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details);
        this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata() }, "PROCESSED");
      }
      getPeer() {
        var _a, _b;
        return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget();
      }
      start(metadata, listener) {
        this.trace("start called");
        this.listener = listener;
        this.metadata = metadata;
        this.doPick();
      }
      sendMessageWithContext(context2, message) {
        this.trace("write() called with message of length " + message.length);
        if (this.child) {
          this.child.sendMessageWithContext(context2, message);
        } else {
          this.pendingMessage = { context: context2, message };
        }
      }
      startRead() {
        this.trace("startRead called");
        if (this.child) {
          this.child.startRead();
        } else {
          this.readPending = true;
        }
      }
      halfClose() {
        this.trace("halfClose called");
        if (this.child) {
          this.child.halfClose();
        } else {
          this.pendingHalfClose = true;
        }
      }
      setCredentials(credentials) {
        throw new Error("Method not implemented.");
      }
      getCallNumber() {
        return this.callNumber;
      }
      getAuthContext() {
        if (this.child) {
          return this.child.getAuthContext();
        } else {
          return null;
        }
      }
    };
    exports.LoadBalancingCall = LoadBalancingCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/resolving-call.js
var require_resolving_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolving-call.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResolvingCall = void 0;
    var call_credentials_1 = require_call_credentials();
    var constants_1 = require_constants2();
    var deadline_1 = require_deadline();
    var metadata_1 = require_metadata();
    var logging = require_logging();
    var control_plane_status_1 = require_control_plane_status();
    var TRACER_NAME = "resolving_call";
    var ResolvingCall = class {
      static {
        __name(this, "ResolvingCall");
      }
      constructor(channel, method, options, filterStackFactory, callNumber) {
        this.channel = channel;
        this.method = method;
        this.filterStackFactory = filterStackFactory;
        this.callNumber = callNumber;
        this.child = null;
        this.readPending = false;
        this.pendingMessage = null;
        this.pendingHalfClose = false;
        this.ended = false;
        this.readFilterPending = false;
        this.writeFilterPending = false;
        this.pendingChildStatus = null;
        this.metadata = null;
        this.listener = null;
        this.statusWatchers = [];
        this.deadlineTimer = setTimeout(() => {
        }, 0);
        this.filterStack = null;
        this.deadlineStartTime = null;
        this.configReceivedTime = null;
        this.childStartTime = null;
        this.credentials = call_credentials_1.CallCredentials.createEmpty();
        this.deadline = options.deadline;
        this.host = options.host;
        if (options.parentCall) {
          if (options.flags & constants_1.Propagate.CANCELLATION) {
            options.parentCall.on("cancelled", () => {
              this.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled by parent call");
            });
          }
          if (options.flags & constants_1.Propagate.DEADLINE) {
            this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline());
            this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline());
          }
        }
        this.trace("Created");
        this.runDeadlineTimer();
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text);
      }
      runDeadlineTimer() {
        clearTimeout(this.deadlineTimer);
        this.deadlineStartTime = /* @__PURE__ */ new Date();
        this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline));
        const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline);
        if (timeout !== Infinity) {
          this.trace("Deadline will be reached in " + timeout + "ms");
          const handleDeadline = /* @__PURE__ */ __name(() => {
            if (!this.deadlineStartTime) {
              this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded");
              return;
            }
            const deadlineInfo = [];
            const deadlineEndTime = /* @__PURE__ */ new Date();
            deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`);
            if (this.configReceivedTime) {
              if (this.configReceivedTime > this.deadlineStartTime) {
                deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`);
              }
              if (this.childStartTime) {
                if (this.childStartTime > this.configReceivedTime) {
                  deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`);
                }
              } else {
                deadlineInfo.push("waiting for metadata filters");
              }
            } else {
              deadlineInfo.push("waiting for name resolution");
            }
            if (this.child) {
              deadlineInfo.push(...this.child.getDeadlineInfo());
            }
            this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(","));
          }, "handleDeadline");
          if (timeout <= 0) {
            process.nextTick(handleDeadline);
          } else {
            this.deadlineTimer = setTimeout(handleDeadline, timeout);
          }
        }
      }
      outputStatus(status) {
        if (!this.ended) {
          this.ended = true;
          if (!this.filterStack) {
            this.filterStack = this.filterStackFactory.createFilter();
          }
          clearTimeout(this.deadlineTimer);
          const filteredStatus = this.filterStack.receiveTrailers(status);
          this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"');
          this.statusWatchers.forEach((watcher) => watcher(filteredStatus));
          process.nextTick(() => {
            var _a;
            (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus);
          });
        }
      }
      sendMessageOnChild(context2, message) {
        if (!this.child) {
          throw new Error("sendMessageonChild called with child not populated");
        }
        const child = this.child;
        this.writeFilterPending = true;
        this.filterStack.sendMessage(Promise.resolve({ message, flags: context2.flags })).then((filteredMessage) => {
          this.writeFilterPending = false;
          child.sendMessageWithContext(context2, filteredMessage.message);
          if (this.pendingHalfClose) {
            child.halfClose();
          }
        }, (status) => {
          this.cancelWithStatus(status.code, status.details);
        });
      }
      getConfig() {
        if (this.ended) {
          return;
        }
        if (!this.metadata || !this.listener) {
          throw new Error("getConfig called before start");
        }
        const configResult = this.channel.getConfig(this.method, this.metadata);
        if (configResult.type === "NONE") {
          this.channel.queueCallForConfig(this);
          return;
        } else if (configResult.type === "ERROR") {
          if (this.metadata.getOptions().waitForReady) {
            this.channel.queueCallForConfig(this);
          } else {
            this.outputStatus(configResult.error);
          }
          return;
        }
        this.configReceivedTime = /* @__PURE__ */ new Date();
        const config = configResult.config;
        if (config.status !== constants_1.Status.OK) {
          const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, "Failed to route call to method " + this.method);
          this.outputStatus({
            code,
            details,
            metadata: new metadata_1.Metadata()
          });
          return;
        }
        if (config.methodConfig.timeout) {
          const configDeadline = /* @__PURE__ */ new Date();
          configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds);
          configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config.methodConfig.timeout.nanos / 1e6);
          this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline);
          this.runDeadlineTimer();
        }
        this.filterStackFactory.push(config.dynamicFilterFactories);
        this.filterStack = this.filterStackFactory.createFilter();
        this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => {
          this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline);
          this.trace("Created child [" + this.child.getCallNumber() + "]");
          this.childStartTime = /* @__PURE__ */ new Date();
          this.child.start(filteredMetadata, {
            onReceiveMetadata: /* @__PURE__ */ __name((metadata) => {
              this.trace("Received metadata");
              this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata));
            }, "onReceiveMetadata"),
            onReceiveMessage: /* @__PURE__ */ __name((message) => {
              this.trace("Received message");
              this.readFilterPending = true;
              this.filterStack.receiveMessage(message).then((filteredMesssage) => {
                this.trace("Finished filtering received message");
                this.readFilterPending = false;
                this.listener.onReceiveMessage(filteredMesssage);
                if (this.pendingChildStatus) {
                  this.outputStatus(this.pendingChildStatus);
                }
              }, (status) => {
                this.cancelWithStatus(status.code, status.details);
              });
            }, "onReceiveMessage"),
            onReceiveStatus: /* @__PURE__ */ __name((status) => {
              this.trace("Received status");
              if (this.readFilterPending) {
                this.pendingChildStatus = status;
              } else {
                this.outputStatus(status);
              }
            }, "onReceiveStatus")
          });
          if (this.readPending) {
            this.child.startRead();
          }
          if (this.pendingMessage) {
            this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message);
          } else if (this.pendingHalfClose) {
            this.child.halfClose();
          }
        }, (status) => {
          this.outputStatus(status);
        });
      }
      reportResolverError(status) {
        var _a;
        if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) {
          this.channel.queueCallForConfig(this);
        } else {
          this.outputStatus(status);
        }
      }
      cancelWithStatus(status, details) {
        var _a;
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details);
        this.outputStatus({
          code: status,
          details,
          metadata: new metadata_1.Metadata()
        });
      }
      getPeer() {
        var _a, _b;
        return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget();
      }
      start(metadata, listener) {
        this.trace("start called");
        this.metadata = metadata.clone();
        this.listener = listener;
        this.getConfig();
      }
      sendMessageWithContext(context2, message) {
        this.trace("write() called with message of length " + message.length);
        if (this.child) {
          this.sendMessageOnChild(context2, message);
        } else {
          this.pendingMessage = { context: context2, message };
        }
      }
      startRead() {
        this.trace("startRead called");
        if (this.child) {
          this.child.startRead();
        } else {
          this.readPending = true;
        }
      }
      halfClose() {
        this.trace("halfClose called");
        if (this.child && !this.writeFilterPending) {
          this.child.halfClose();
        } else {
          this.pendingHalfClose = true;
        }
      }
      setCredentials(credentials) {
        this.credentials = credentials;
      }
      addStatusWatcher(watcher) {
        this.statusWatchers.push(watcher);
      }
      getCallNumber() {
        return this.callNumber;
      }
      getAuthContext() {
        if (this.child) {
          return this.child.getAuthContext();
        } else {
          return null;
        }
      }
    };
    exports.ResolvingCall = ResolvingCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/retrying-call.js
var require_retrying_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/retrying-call.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RetryingCall = exports.MessageBufferTracker = exports.RetryThrottler = void 0;
    var constants_1 = require_constants2();
    var deadline_1 = require_deadline();
    var metadata_1 = require_metadata();
    var logging = require_logging();
    var TRACER_NAME = "retrying_call";
    var RetryThrottler = class {
      static {
        __name(this, "RetryThrottler");
      }
      constructor(maxTokens, tokenRatio, previousRetryThrottler) {
        this.maxTokens = maxTokens;
        this.tokenRatio = tokenRatio;
        if (previousRetryThrottler) {
          this.tokens = previousRetryThrottler.tokens * (maxTokens / previousRetryThrottler.maxTokens);
        } else {
          this.tokens = maxTokens;
        }
      }
      addCallSucceeded() {
        this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens);
      }
      addCallFailed() {
        this.tokens = Math.max(this.tokens - 1, 0);
      }
      canRetryCall() {
        return this.tokens > this.maxTokens / 2;
      }
    };
    exports.RetryThrottler = RetryThrottler;
    var MessageBufferTracker = class {
      static {
        __name(this, "MessageBufferTracker");
      }
      constructor(totalLimit, limitPerCall) {
        this.totalLimit = totalLimit;
        this.limitPerCall = limitPerCall;
        this.totalAllocated = 0;
        this.allocatedPerCall = /* @__PURE__ */ new Map();
      }
      allocate(size, callId) {
        var _a;
        const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0;
        if (this.limitPerCall - currentPerCall < size || this.totalLimit - this.totalAllocated < size) {
          return false;
        }
        this.allocatedPerCall.set(callId, currentPerCall + size);
        this.totalAllocated += size;
        return true;
      }
      free(size, callId) {
        var _a;
        if (this.totalAllocated < size) {
          throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`);
        }
        this.totalAllocated -= size;
        const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0;
        if (currentPerCall < size) {
          throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`);
        }
        this.allocatedPerCall.set(callId, currentPerCall - size);
      }
      freeAll(callId) {
        var _a;
        const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0;
        if (this.totalAllocated < currentPerCall) {
          throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`);
        }
        this.totalAllocated -= currentPerCall;
        this.allocatedPerCall.delete(callId);
      }
    };
    exports.MessageBufferTracker = MessageBufferTracker;
    var PREVIONS_RPC_ATTEMPTS_METADATA_KEY = "grpc-previous-rpc-attempts";
    var DEFAULT_MAX_ATTEMPTS_LIMIT = 5;
    var RetryingCall = class {
      static {
        __name(this, "RetryingCall");
      }
      constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) {
        var _a;
        this.channel = channel;
        this.callConfig = callConfig;
        this.methodName = methodName;
        this.host = host;
        this.credentials = credentials;
        this.deadline = deadline;
        this.callNumber = callNumber;
        this.bufferTracker = bufferTracker;
        this.retryThrottler = retryThrottler;
        this.listener = null;
        this.initialMetadata = null;
        this.underlyingCalls = [];
        this.writeBuffer = [];
        this.writeBufferOffset = 0;
        this.readStarted = false;
        this.transparentRetryUsed = false;
        this.attempts = 0;
        this.hedgingTimer = null;
        this.committedCallIndex = null;
        this.initialRetryBackoffSec = 0;
        this.nextRetryBackoffSec = 0;
        const maxAttemptsLimit = (_a = channel.getOptions()["grpc-node.retry_max_attempts_limit"]) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT;
        if (channel.getOptions()["grpc.enable_retries"] === 0) {
          this.state = "NO_RETRY";
          this.maxAttempts = 1;
        } else if (callConfig.methodConfig.retryPolicy) {
          this.state = "RETRY";
          const retryPolicy = callConfig.methodConfig.retryPolicy;
          this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1));
          this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit);
        } else if (callConfig.methodConfig.hedgingPolicy) {
          this.state = "HEDGING";
          this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit);
        } else {
          this.state = "TRANSPARENT_ONLY";
          this.maxAttempts = 1;
        }
        this.startTime = /* @__PURE__ */ new Date();
      }
      getDeadlineInfo() {
        if (this.underlyingCalls.length === 0) {
          return [];
        }
        const deadlineInfo = [];
        const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1];
        if (this.underlyingCalls.length > 1) {
          deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`);
        }
        if (latestCall.startTime > this.startTime) {
          deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`);
        }
        deadlineInfo.push(...latestCall.call.getDeadlineInfo());
        return deadlineInfo;
      }
      getCallNumber() {
        return this.callNumber;
      }
      trace(text) {
        logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text);
      }
      reportStatus(statusObject) {
        this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + this.startTime.toISOString());
        this.bufferTracker.freeAll(this.callNumber);
        this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length;
        this.writeBuffer = [];
        process.nextTick(() => {
          var _a;
          (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({
            code: statusObject.code,
            details: statusObject.details,
            metadata: statusObject.metadata
          });
        });
      }
      cancelWithStatus(status, details) {
        this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"');
        this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() });
        for (const { call } of this.underlyingCalls) {
          call.cancelWithStatus(status, details);
        }
      }
      getPeer() {
        if (this.committedCallIndex !== null) {
          return this.underlyingCalls[this.committedCallIndex].call.getPeer();
        } else {
          return "unknown";
        }
      }
      getBufferEntry(messageIndex) {
        var _a;
        return (_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : {
          entryType: "FREED",
          allocated: false
        };
      }
      getNextBufferIndex() {
        return this.writeBufferOffset + this.writeBuffer.length;
      }
      clearSentMessages() {
        if (this.state !== "COMMITTED") {
          return;
        }
        let earliestNeededMessageIndex;
        if (this.underlyingCalls[this.committedCallIndex].state === "COMPLETED") {
          earliestNeededMessageIndex = this.getNextBufferIndex();
        } else {
          earliestNeededMessageIndex = this.underlyingCalls[this.committedCallIndex].nextMessageToSend;
        }
        for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) {
          const bufferEntry = this.getBufferEntry(messageIndex);
          if (bufferEntry.allocated) {
            this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber);
          }
        }
        this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset);
        this.writeBufferOffset = earliestNeededMessageIndex;
      }
      commitCall(index) {
        var _a, _b;
        if (this.state === "COMMITTED") {
          return;
        }
        this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index);
        this.state = "COMMITTED";
        (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a);
        this.committedCallIndex = index;
        for (let i = 0; i < this.underlyingCalls.length; i++) {
          if (i === index) {
            continue;
          }
          if (this.underlyingCalls[i].state === "COMPLETED") {
            continue;
          }
          this.underlyingCalls[i].state = "COMPLETED";
          this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, "Discarded in favor of other hedged attempt");
        }
        this.clearSentMessages();
      }
      commitCallWithMostMessages() {
        if (this.state === "COMMITTED") {
          return;
        }
        let mostMessages = -1;
        let callWithMostMessages = -1;
        for (const [index, childCall] of this.underlyingCalls.entries()) {
          if (childCall.state === "ACTIVE" && childCall.nextMessageToSend > mostMessages) {
            mostMessages = childCall.nextMessageToSend;
            callWithMostMessages = index;
          }
        }
        if (callWithMostMessages === -1) {
          this.state = "TRANSPARENT_ONLY";
        } else {
          this.commitCall(callWithMostMessages);
        }
      }
      isStatusCodeInList(list, code) {
        return list.some((value) => {
          var _a;
          return value === code || value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === void 0 ? void 0 : _a.toLowerCase());
        });
      }
      getNextRetryJitter() {
        return Math.random() * (1.2 - 0.8) + 0.8;
      }
      getNextRetryBackoffMs() {
        var _a;
        const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy;
        if (!retryPolicy) {
          return 0;
        }
        const jitter = this.getNextRetryJitter();
        const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1e3;
        const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1));
        this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec);
        return nextBackoffMs;
      }
      maybeRetryCall(pushback, callback) {
        if (this.state !== "RETRY") {
          callback(false);
          return;
        }
        if (this.attempts >= this.maxAttempts) {
          callback(false);
          return;
        }
        let retryDelayMs;
        if (pushback === null) {
          retryDelayMs = this.getNextRetryBackoffMs();
        } else if (pushback < 0) {
          this.state = "TRANSPARENT_ONLY";
          callback(false);
          return;
        } else {
          retryDelayMs = pushback;
          this.nextRetryBackoffSec = this.initialRetryBackoffSec;
        }
        setTimeout(() => {
          var _a, _b;
          if (this.state !== "RETRY") {
            callback(false);
            return;
          }
          if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) {
            callback(true);
            this.attempts += 1;
            this.startNewAttempt();
          } else {
            this.trace("Retry attempt denied by throttling policy");
            callback(false);
          }
        }, retryDelayMs);
      }
      countActiveCalls() {
        let count = 0;
        for (const call of this.underlyingCalls) {
          if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") {
            count += 1;
          }
        }
        return count;
      }
      handleProcessedStatus(status, callIndex, pushback) {
        var _a, _b, _c;
        switch (this.state) {
          case "COMMITTED":
          case "NO_RETRY":
          case "TRANSPARENT_ONLY":
            this.commitCall(callIndex);
            this.reportStatus(status);
            break;
          case "HEDGING":
            if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) {
              (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed();
              let delayMs;
              if (pushback === null) {
                delayMs = 0;
              } else if (pushback < 0) {
                this.state = "TRANSPARENT_ONLY";
                this.commitCall(callIndex);
                this.reportStatus(status);
                return;
              } else {
                delayMs = pushback;
              }
              setTimeout(() => {
                this.maybeStartHedgingAttempt();
                if (this.countActiveCalls() === 0) {
                  this.commitCall(callIndex);
                  this.reportStatus(status);
                }
              }, delayMs);
            } else {
              this.commitCall(callIndex);
              this.reportStatus(status);
            }
            break;
          case "RETRY":
            if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) {
              (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed();
              this.maybeRetryCall(pushback, (retried) => {
                if (!retried) {
                  this.commitCall(callIndex);
                  this.reportStatus(status);
                }
              });
            } else {
              this.commitCall(callIndex);
              this.reportStatus(status);
            }
            break;
        }
      }
      getPushback(metadata) {
        const mdValue = metadata.get("grpc-retry-pushback-ms");
        if (mdValue.length === 0) {
          return null;
        }
        try {
          return parseInt(mdValue[0]);
        } catch (e) {
          return -1;
        }
      }
      handleChildStatus(status, callIndex) {
        var _a;
        if (this.underlyingCalls[callIndex].state === "COMPLETED") {
          return;
        }
        this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state);
        this.underlyingCalls[callIndex].state = "COMPLETED";
        if (status.code === constants_1.Status.OK) {
          (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded();
          this.commitCall(callIndex);
          this.reportStatus(status);
          return;
        }
        if (this.state === "NO_RETRY") {
          this.commitCall(callIndex);
          this.reportStatus(status);
          return;
        }
        if (this.state === "COMMITTED") {
          this.reportStatus(status);
          return;
        }
        const pushback = this.getPushback(status.metadata);
        switch (status.progress) {
          case "NOT_STARTED":
            this.startNewAttempt();
            break;
          case "REFUSED":
            if (this.transparentRetryUsed) {
              this.handleProcessedStatus(status, callIndex, pushback);
            } else {
              this.transparentRetryUsed = true;
              this.startNewAttempt();
            }
            break;
          case "DROP":
            this.commitCall(callIndex);
            this.reportStatus(status);
            break;
          case "PROCESSED":
            this.handleProcessedStatus(status, callIndex, pushback);
            break;
        }
      }
      maybeStartHedgingAttempt() {
        if (this.state !== "HEDGING") {
          return;
        }
        if (!this.callConfig.methodConfig.hedgingPolicy) {
          return;
        }
        if (this.attempts >= this.maxAttempts) {
          return;
        }
        this.attempts += 1;
        this.startNewAttempt();
        this.maybeStartHedgingTimer();
      }
      maybeStartHedgingTimer() {
        var _a, _b, _c;
        if (this.hedgingTimer) {
          clearTimeout(this.hedgingTimer);
        }
        if (this.state !== "HEDGING") {
          return;
        }
        if (!this.callConfig.methodConfig.hedgingPolicy) {
          return;
        }
        const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy;
        if (this.attempts >= this.maxAttempts) {
          return;
        }
        const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : "0s";
        const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1));
        this.hedgingTimer = setTimeout(() => {
          this.maybeStartHedgingAttempt();
        }, hedgingDelaySec * 1e3);
        (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b);
      }
      startNewAttempt() {
        const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline);
        this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts);
        const index = this.underlyingCalls.length;
        this.underlyingCalls.push({
          state: "ACTIVE",
          call: child,
          nextMessageToSend: 0,
          startTime: /* @__PURE__ */ new Date()
        });
        const previousAttempts = this.attempts - 1;
        const initialMetadata = this.initialMetadata.clone();
        if (previousAttempts > 0) {
          initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`);
        }
        let receivedMetadata = false;
        child.start(initialMetadata, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata) => {
            this.trace("Received metadata from child [" + child.getCallNumber() + "]");
            this.commitCall(index);
            receivedMetadata = true;
            if (previousAttempts > 0) {
              metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`);
            }
            if (this.underlyingCalls[index].state === "ACTIVE") {
              this.listener.onReceiveMetadata(metadata);
            }
          }, "onReceiveMetadata"),
          onReceiveMessage: /* @__PURE__ */ __name((message) => {
            this.trace("Received message from child [" + child.getCallNumber() + "]");
            this.commitCall(index);
            if (this.underlyingCalls[index].state === "ACTIVE") {
              this.listener.onReceiveMessage(message);
            }
          }, "onReceiveMessage"),
          onReceiveStatus: /* @__PURE__ */ __name((status) => {
            this.trace("Received status from child [" + child.getCallNumber() + "]");
            if (!receivedMetadata && previousAttempts > 0) {
              status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`);
            }
            this.handleChildStatus(status, index);
          }, "onReceiveStatus")
        });
        this.sendNextChildMessage(index);
        if (this.readStarted) {
          child.startRead();
        }
      }
      start(metadata, listener) {
        this.trace("start called");
        this.listener = listener;
        this.initialMetadata = metadata;
        this.attempts += 1;
        this.startNewAttempt();
        this.maybeStartHedgingTimer();
      }
      handleChildWriteCompleted(childIndex, messageIndex) {
        var _a, _b;
        (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a);
        this.clearSentMessages();
        const childCall = this.underlyingCalls[childIndex];
        childCall.nextMessageToSend += 1;
        this.sendNextChildMessage(childIndex);
      }
      sendNextChildMessage(childIndex) {
        const childCall = this.underlyingCalls[childIndex];
        if (childCall.state === "COMPLETED") {
          return;
        }
        const messageIndex = childCall.nextMessageToSend;
        if (this.getBufferEntry(messageIndex)) {
          const bufferEntry = this.getBufferEntry(messageIndex);
          switch (bufferEntry.entryType) {
            case "MESSAGE":
              childCall.call.sendMessageWithContext({
                callback: /* @__PURE__ */ __name((error) => {
                  this.handleChildWriteCompleted(childIndex, messageIndex);
                }, "callback")
              }, bufferEntry.message.message);
              const nextEntry = this.getBufferEntry(messageIndex + 1);
              if (nextEntry.entryType === "HALF_CLOSE") {
                this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message");
                childCall.nextMessageToSend += 1;
                childCall.call.halfClose();
              }
              break;
            case "HALF_CLOSE":
              childCall.nextMessageToSend += 1;
              childCall.call.halfClose();
              break;
            case "FREED":
              break;
          }
        }
      }
      sendMessageWithContext(context2, message) {
        this.trace("write() called with message of length " + message.length);
        const writeObj = {
          message,
          flags: context2.flags
        };
        const messageIndex = this.getNextBufferIndex();
        const bufferEntry = {
          entryType: "MESSAGE",
          message: writeObj,
          allocated: this.bufferTracker.allocate(message.length, this.callNumber)
        };
        this.writeBuffer.push(bufferEntry);
        if (bufferEntry.allocated) {
          process.nextTick(() => {
            var _a;
            (_a = context2.callback) === null || _a === void 0 ? void 0 : _a.call(context2);
          });
          for (const [callIndex, call] of this.underlyingCalls.entries()) {
            if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) {
              call.call.sendMessageWithContext({
                callback: /* @__PURE__ */ __name((error) => {
                  this.handleChildWriteCompleted(callIndex, messageIndex);
                }, "callback")
              }, message);
            }
          }
        } else {
          this.commitCallWithMostMessages();
          if (this.committedCallIndex === null) {
            return;
          }
          const call = this.underlyingCalls[this.committedCallIndex];
          bufferEntry.callback = context2.callback;
          if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) {
            call.call.sendMessageWithContext({
              callback: /* @__PURE__ */ __name((error) => {
                this.handleChildWriteCompleted(this.committedCallIndex, messageIndex);
              }, "callback")
            }, message);
          }
        }
      }
      startRead() {
        this.trace("startRead called");
        this.readStarted = true;
        for (const underlyingCall of this.underlyingCalls) {
          if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === "ACTIVE") {
            underlyingCall.call.startRead();
          }
        }
      }
      halfClose() {
        this.trace("halfClose called");
        const halfCloseIndex = this.getNextBufferIndex();
        this.writeBuffer.push({
          entryType: "HALF_CLOSE",
          allocated: false
        });
        for (const call of this.underlyingCalls) {
          if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") {
            if (call.nextMessageToSend === halfCloseIndex || call.nextMessageToSend === halfCloseIndex - 1) {
              this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent");
              call.nextMessageToSend += 1;
              call.call.halfClose();
            }
          }
        }
      }
      setCredentials(newCredentials) {
        throw new Error("Method not implemented.");
      }
      getMethod() {
        return this.methodName;
      }
      getHost() {
        return this.host;
      }
      getAuthContext() {
        if (this.committedCallIndex !== null) {
          return this.underlyingCalls[this.committedCallIndex].call.getAuthContext();
        } else {
          return null;
        }
      }
    };
    exports.RetryingCall = RetryingCall;
  }
});

// node_modules/@grpc/grpc-js/build/src/subchannel-interface.js
var require_subchannel_interface = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/subchannel-interface.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseSubchannelWrapper = void 0;
    var BaseSubchannelWrapper = class {
      static {
        __name(this, "BaseSubchannelWrapper");
      }
      constructor(child) {
        this.child = child;
        this.healthy = true;
        this.healthListeners = /* @__PURE__ */ new Set();
        this.refcount = 0;
        this.dataWatchers = /* @__PURE__ */ new Set();
        child.addHealthStateWatcher((childHealthy) => {
          if (this.healthy) {
            this.updateHealthListeners();
          }
        });
      }
      updateHealthListeners() {
        for (const listener of this.healthListeners) {
          listener(this.isHealthy());
        }
      }
      getConnectivityState() {
        return this.child.getConnectivityState();
      }
      addConnectivityStateListener(listener) {
        this.child.addConnectivityStateListener(listener);
      }
      removeConnectivityStateListener(listener) {
        this.child.removeConnectivityStateListener(listener);
      }
      startConnecting() {
        this.child.startConnecting();
      }
      getAddress() {
        return this.child.getAddress();
      }
      throttleKeepalive(newKeepaliveTime) {
        this.child.throttleKeepalive(newKeepaliveTime);
      }
      ref() {
        this.child.ref();
        this.refcount += 1;
      }
      unref() {
        this.child.unref();
        this.refcount -= 1;
        if (this.refcount === 0) {
          this.destroy();
        }
      }
      destroy() {
        for (const watcher of this.dataWatchers) {
          watcher.destroy();
        }
      }
      getChannelzRef() {
        return this.child.getChannelzRef();
      }
      isHealthy() {
        return this.healthy && this.child.isHealthy();
      }
      addHealthStateWatcher(listener) {
        this.healthListeners.add(listener);
      }
      removeHealthStateWatcher(listener) {
        this.healthListeners.delete(listener);
      }
      addDataWatcher(dataWatcher) {
        dataWatcher.setSubchannel(this.getRealSubchannel());
        this.dataWatchers.add(dataWatcher);
      }
      setHealthy(healthy) {
        if (healthy !== this.healthy) {
          this.healthy = healthy;
          if (this.child.isHealthy()) {
            this.updateHealthListeners();
          }
        }
      }
      getRealSubchannel() {
        return this.child.getRealSubchannel();
      }
      realSubchannelEquals(other) {
        return this.getRealSubchannel() === other.getRealSubchannel();
      }
      getCallCredentials() {
        return this.child.getCallCredentials();
      }
      getChannel() {
        return this.child.getChannel();
      }
    };
    exports.BaseSubchannelWrapper = BaseSubchannelWrapper;
  }
});

// node_modules/@grpc/grpc-js/build/src/internal-channel.js
var require_internal_channel = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/internal-channel.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InternalChannel = exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0;
    var channel_credentials_1 = require_channel_credentials();
    var resolving_load_balancer_1 = require_resolving_load_balancer();
    var subchannel_pool_1 = require_subchannel_pool();
    var picker_1 = require_picker();
    var metadata_1 = require_metadata();
    var constants_1 = require_constants2();
    var filter_stack_1 = require_filter_stack();
    var compression_filter_1 = require_compression_filter();
    var resolver_1 = require_resolver();
    var logging_1 = require_logging();
    var http_proxy_1 = require_http_proxy();
    var uri_parser_1 = require_uri_parser();
    var connectivity_state_1 = require_connectivity_state();
    var channelz_1 = require_channelz();
    var load_balancing_call_1 = require_load_balancing_call();
    var deadline_1 = require_deadline();
    var resolving_call_1 = require_resolving_call();
    var call_number_1 = require_call_number();
    var control_plane_status_1 = require_control_plane_status();
    var retrying_call_1 = require_retrying_call();
    var subchannel_interface_1 = require_subchannel_interface();
    var MAX_TIMEOUT_TIME = 2147483647;
    var MIN_IDLE_TIMEOUT_MS = 1e3;
    var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
    var RETRY_THROTTLER_MAP = /* @__PURE__ */ new Map();
    var DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24;
    var DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20;
    var ChannelSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper {
      static {
        __name(this, "ChannelSubchannelWrapper");
      }
      constructor(childSubchannel, channel) {
        super(childSubchannel);
        this.channel = channel;
        this.refCount = 0;
        this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => {
          channel.throttleKeepalive(keepaliveTime);
        };
      }
      ref() {
        if (this.refCount === 0) {
          this.child.addConnectivityStateListener(this.subchannelStateListener);
          this.channel.addWrappedSubchannel(this);
        }
        this.child.ref();
        this.refCount += 1;
      }
      unref() {
        this.child.unref();
        this.refCount -= 1;
        if (this.refCount <= 0) {
          this.child.removeConnectivityStateListener(this.subchannelStateListener);
          this.channel.removeWrappedSubchannel(this);
        }
      }
    };
    var ShutdownPicker = class {
      static {
        __name(this, "ShutdownPicker");
      }
      pick(pickArgs) {
        return {
          pickResultType: picker_1.PickResultType.DROP,
          status: {
            code: constants_1.Status.UNAVAILABLE,
            details: "Channel closed before call started",
            metadata: new metadata_1.Metadata()
          },
          subchannel: null,
          onCallStarted: null,
          onCallEnded: null
        };
      }
    };
    exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = "grpc.internal.no_subchannel";
    var ChannelzInfoTracker = class {
      static {
        __name(this, "ChannelzInfoTracker");
      }
      constructor(target) {
        this.target = target;
        this.trace = new channelz_1.ChannelzTrace();
        this.callTracker = new channelz_1.ChannelzCallTracker();
        this.childrenTracker = new channelz_1.ChannelzChildrenTracker();
        this.state = connectivity_state_1.ConnectivityState.IDLE;
      }
      getChannelzInfoCallback() {
        return () => {
          return {
            target: this.target,
            state: this.state,
            trace: this.trace,
            callTracker: this.callTracker,
            children: this.childrenTracker.getChildLists()
          };
        };
      }
    };
    var InternalChannel = class {
      static {
        __name(this, "InternalChannel");
      }
      constructor(target, credentials, options) {
        var _a, _b, _c, _d, _e, _f;
        this.credentials = credentials;
        this.options = options;
        this.connectivityState = connectivity_state_1.ConnectivityState.IDLE;
        this.currentPicker = new picker_1.UnavailablePicker();
        this.configSelectionQueue = [];
        this.pickQueue = [];
        this.connectivityStateWatchers = [];
        this.callRefTimer = null;
        this.configSelector = null;
        this.currentResolutionError = null;
        this.wrappedSubchannels = /* @__PURE__ */ new Set();
        this.callCount = 0;
        this.idleTimer = null;
        this.channelzEnabled = true;
        this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
        if (typeof target !== "string") {
          throw new TypeError("Channel target must be a string");
        }
        if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) {
          throw new TypeError("Channel credentials must be a ChannelCredentials object");
        }
        if (options) {
          if (typeof options !== "object") {
            throw new TypeError("Channel options must be an object");
          }
        }
        this.channelzInfoTracker = new ChannelzInfoTracker(target);
        const originalTargetUri = (0, uri_parser_1.parseUri)(target);
        if (originalTargetUri === null) {
          throw new Error(`Could not parse target name "${target}"`);
        }
        const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri);
        if (defaultSchemeMapResult === null) {
          throw new Error(`Could not find a default scheme for target name "${target}"`);
        }
        if (this.options["grpc.enable_channelz"] === 0) {
          this.channelzEnabled = false;
        }
        this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled);
        if (this.channelzEnabled) {
          this.channelzInfoTracker.trace.addTrace("CT_INFO", "Channel created");
        }
        if (this.options["grpc.default_authority"]) {
          this.defaultAuthority = this.options["grpc.default_authority"];
        } else {
          this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult);
        }
        const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options);
        this.target = proxyMapResult.target;
        this.options = Object.assign({}, this.options, proxyMapResult.extraOptions);
        this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options["grpc.use_local_subchannel_pool"]) !== null && _a !== void 0 ? _a : 0) === 0);
        this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options["grpc.retry_buffer_size"]) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options["grpc.per_rpc_retry_buffer_size"]) !== null && _c !== void 0 ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES);
        this.keepaliveTime = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : -1;
        this.idleTimeoutMs = Math.max((_e = this.options["grpc.client_idle_timeout_ms"]) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS);
        const channelControlHelper = {
          createSubchannel: /* @__PURE__ */ __name((subchannelAddress, subchannelArgs) => {
            const finalSubchannelArgs = {};
            for (const [key, value] of Object.entries(subchannelArgs)) {
              if (!key.startsWith(exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) {
                finalSubchannelArgs[key] = value;
              }
            }
            const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials);
            subchannel.throttleKeepalive(this.keepaliveTime);
            if (this.channelzEnabled) {
              this.channelzInfoTracker.trace.addTrace("CT_INFO", "Created subchannel or used existing subchannel", subchannel.getChannelzRef());
            }
            const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this);
            return wrappedSubchannel;
          }, "createSubchannel"),
          updateState: /* @__PURE__ */ __name((connectivityState, picker) => {
            this.currentPicker = picker;
            const queueCopy = this.pickQueue.slice();
            this.pickQueue = [];
            if (queueCopy.length > 0) {
              this.callRefTimerUnref();
            }
            for (const call of queueCopy) {
              call.doPick();
            }
            this.updateState(connectivityState);
          }, "updateState"),
          requestReresolution: /* @__PURE__ */ __name(() => {
            throw new Error("Resolving load balancer should never call requestReresolution");
          }, "requestReresolution"),
          addChannelzChild: /* @__PURE__ */ __name((child) => {
            if (this.channelzEnabled) {
              this.channelzInfoTracker.childrenTracker.refChild(child);
            }
          }, "addChannelzChild"),
          removeChannelzChild: /* @__PURE__ */ __name((child) => {
            if (this.channelzEnabled) {
              this.channelzInfoTracker.childrenTracker.unrefChild(child);
            }
          }, "removeChannelzChild")
        };
        this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => {
          var _a2;
          if (serviceConfig.retryThrottling) {
            RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget())));
          } else {
            RETRY_THROTTLER_MAP.delete(this.getTarget());
          }
          if (this.channelzEnabled) {
            this.channelzInfoTracker.trace.addTrace("CT_INFO", "Address resolution succeeded");
          }
          (_a2 = this.configSelector) === null || _a2 === void 0 ? void 0 : _a2.unref();
          this.configSelector = configSelector;
          this.currentResolutionError = null;
          process.nextTick(() => {
            const localQueue = this.configSelectionQueue;
            this.configSelectionQueue = [];
            if (localQueue.length > 0) {
              this.callRefTimerUnref();
            }
            for (const call of localQueue) {
              call.getConfig();
            }
          });
        }, (status) => {
          if (this.channelzEnabled) {
            this.channelzInfoTracker.trace.addTrace("CT_WARNING", "Address resolution failed with code " + status.code + ' and details "' + status.details + '"');
          }
          if (this.configSelectionQueue.length > 0) {
            this.trace("Name resolution failed with calls queued for config selection");
          }
          if (this.configSelector === null) {
            this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata });
          }
          const localQueue = this.configSelectionQueue;
          this.configSelectionQueue = [];
          if (localQueue.length > 0) {
            this.callRefTimerUnref();
          }
          for (const call of localQueue) {
            call.reportResolverError(status);
          }
        });
        this.filterStackFactory = new filter_stack_1.FilterStackFactory([
          new compression_filter_1.CompressionFilterFactory(this, this.options)
        ]);
        this.trace("Channel constructed with options " + JSON.stringify(options, void 0, 2));
        const error = new Error();
        if ((0, logging_1.isTracerEnabled)("channel_stacktrace")) {
          (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") Channel constructed \n" + ((_f = error.stack) === null || _f === void 0 ? void 0 : _f.substring(error.stack.indexOf("\n") + 1)));
        }
        this.lastActivityTimestamp = /* @__PURE__ */ new Date();
      }
      trace(text, verbosityOverride) {
        (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text);
      }
      callRefTimerRef() {
        var _a, _b, _c, _d;
        if (!this.callRefTimer) {
          this.callRefTimer = setInterval(() => {
          }, MAX_TIMEOUT_TIME);
        }
        if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) {
          this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length);
          (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c);
        }
      }
      callRefTimerUnref() {
        var _a, _b, _c;
        if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) {
          this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length);
          (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b);
        }
      }
      removeConnectivityStateWatcher(watcherObject) {
        const watcherIndex = this.connectivityStateWatchers.findIndex((value) => value === watcherObject);
        if (watcherIndex >= 0) {
          this.connectivityStateWatchers.splice(watcherIndex, 1);
        }
      }
      updateState(newState) {
        (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "connectivity_state", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        if (this.channelzEnabled) {
          this.channelzInfoTracker.trace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]);
        }
        this.connectivityState = newState;
        this.channelzInfoTracker.state = newState;
        const watchersCopy = this.connectivityStateWatchers.slice();
        for (const watcherObject of watchersCopy) {
          if (newState !== watcherObject.currentState) {
            if (watcherObject.timer) {
              clearTimeout(watcherObject.timer);
            }
            this.removeConnectivityStateWatcher(watcherObject);
            watcherObject.callback();
          }
        }
        if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
          this.currentResolutionError = null;
        }
      }
      throttleKeepalive(newKeepaliveTime) {
        if (newKeepaliveTime > this.keepaliveTime) {
          this.keepaliveTime = newKeepaliveTime;
          for (const wrappedSubchannel of this.wrappedSubchannels) {
            wrappedSubchannel.throttleKeepalive(newKeepaliveTime);
          }
        }
      }
      addWrappedSubchannel(wrappedSubchannel) {
        this.wrappedSubchannels.add(wrappedSubchannel);
      }
      removeWrappedSubchannel(wrappedSubchannel) {
        this.wrappedSubchannels.delete(wrappedSubchannel);
      }
      doPick(metadata, extraPickInfo) {
        return this.currentPicker.pick({
          metadata,
          extraPickInfo
        });
      }
      queueCallForPick(call) {
        this.pickQueue.push(call);
        this.callRefTimerRef();
      }
      getConfig(method, metadata) {
        if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) {
          this.resolvingLoadBalancer.exitIdle();
        }
        if (this.configSelector) {
          return {
            type: "SUCCESS",
            config: this.configSelector.invoke(method, metadata, this.randomChannelId)
          };
        } else {
          if (this.currentResolutionError) {
            return {
              type: "ERROR",
              error: this.currentResolutionError
            };
          } else {
            return {
              type: "NONE"
            };
          }
        }
      }
      queueCallForConfig(call) {
        this.configSelectionQueue.push(call);
        this.callRefTimerRef();
      }
      enterIdle() {
        this.resolvingLoadBalancer.destroy();
        this.updateState(connectivity_state_1.ConnectivityState.IDLE);
        this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer);
        if (this.idleTimer) {
          clearTimeout(this.idleTimer);
          this.idleTimer = null;
        }
        if (this.callRefTimer) {
          clearInterval(this.callRefTimer);
          this.callRefTimer = null;
        }
      }
      startIdleTimeout(timeoutMs) {
        var _a, _b;
        this.idleTimer = setTimeout(() => {
          if (this.callCount > 0) {
            this.startIdleTimeout(this.idleTimeoutMs);
            return;
          }
          const now = /* @__PURE__ */ new Date();
          const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf();
          if (timeSinceLastActivity >= this.idleTimeoutMs) {
            this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity");
            this.enterIdle();
          } else {
            this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity);
          }
        }, timeoutMs);
        (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
      }
      maybeStartIdleTimer() {
        if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && !this.idleTimer) {
          this.startIdleTimeout(this.idleTimeoutMs);
        }
      }
      onCallStart() {
        if (this.channelzEnabled) {
          this.channelzInfoTracker.callTracker.addCallStarted();
        }
        this.callCount += 1;
      }
      onCallEnd(status) {
        if (this.channelzEnabled) {
          if (status.code === constants_1.Status.OK) {
            this.channelzInfoTracker.callTracker.addCallSucceeded();
          } else {
            this.channelzInfoTracker.callTracker.addCallFailed();
          }
        }
        this.callCount -= 1;
        this.lastActivityTimestamp = /* @__PURE__ */ new Date();
        this.maybeStartIdleTimer();
      }
      createLoadBalancingCall(callConfig, method, host, credentials, deadline) {
        const callNumber = (0, call_number_1.getNextCallNumber)();
        this.trace("createLoadBalancingCall [" + callNumber + '] method="' + method + '"');
        return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber);
      }
      createRetryingCall(callConfig, method, host, credentials, deadline) {
        const callNumber = (0, call_number_1.getNextCallNumber)();
        this.trace("createRetryingCall [" + callNumber + '] method="' + method + '"');
        return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget()));
      }
      createResolvingCall(method, deadline, host, parentCall, propagateFlags) {
        const callNumber = (0, call_number_1.getNextCallNumber)();
        this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline));
        const finalOptions = {
          deadline,
          flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS,
          host: host !== null && host !== void 0 ? host : this.defaultAuthority,
          parentCall
        };
        const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber);
        this.onCallStart();
        call.addStatusWatcher((status) => {
          this.onCallEnd(status);
        });
        return call;
      }
      close() {
        var _a;
        this.resolvingLoadBalancer.destroy();
        this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN);
        this.currentPicker = new ShutdownPicker();
        for (const call of this.configSelectionQueue) {
          call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started");
        }
        this.configSelectionQueue = [];
        for (const call of this.pickQueue) {
          call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started");
        }
        this.pickQueue = [];
        if (this.callRefTimer) {
          clearInterval(this.callRefTimer);
        }
        if (this.idleTimer) {
          clearTimeout(this.idleTimer);
        }
        if (this.channelzEnabled) {
          (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
        }
        this.subchannelPool.unrefUnusedSubchannels();
        (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref();
        this.configSelector = null;
      }
      getTarget() {
        return (0, uri_parser_1.uriToString)(this.target);
      }
      getConnectivityState(tryToConnect) {
        const connectivityState = this.connectivityState;
        if (tryToConnect) {
          this.resolvingLoadBalancer.exitIdle();
          this.lastActivityTimestamp = /* @__PURE__ */ new Date();
          this.maybeStartIdleTimer();
        }
        return connectivityState;
      }
      watchConnectivityState(currentState, deadline, callback) {
        if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) {
          throw new Error("Channel has been shut down");
        }
        let timer = null;
        if (deadline !== Infinity) {
          const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline);
          const now = /* @__PURE__ */ new Date();
          if (deadline === -Infinity || deadlineDate <= now) {
            process.nextTick(callback, new Error("Deadline passed without connectivity state change"));
            return;
          }
          timer = setTimeout(() => {
            this.removeConnectivityStateWatcher(watcherObject);
            callback(new Error("Deadline passed without connectivity state change"));
          }, deadlineDate.getTime() - now.getTime());
        }
        const watcherObject = {
          currentState,
          callback,
          timer
        };
        this.connectivityStateWatchers.push(watcherObject);
      }
      /**
       * Get the channelz reference object for this channel. The returned value is
       * garbage if channelz is disabled for this channel.
       * @returns
       */
      getChannelzRef() {
        return this.channelzRef;
      }
      createCall(method, deadline, host, parentCall, propagateFlags) {
        if (typeof method !== "string") {
          throw new TypeError("Channel#createCall: method must be a string");
        }
        if (!(typeof deadline === "number" || deadline instanceof Date)) {
          throw new TypeError("Channel#createCall: deadline must be a number or Date");
        }
        if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) {
          throw new Error("Channel has been shut down");
        }
        return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags);
      }
      getOptions() {
        return this.options;
      }
    };
    exports.InternalChannel = InternalChannel;
  }
});

// node_modules/@grpc/grpc-js/build/src/channel.js
var require_channel = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/channel.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChannelImplementation = void 0;
    var channel_credentials_1 = require_channel_credentials();
    var internal_channel_1 = require_internal_channel();
    var ChannelImplementation = class {
      static {
        __name(this, "ChannelImplementation");
      }
      constructor(target, credentials, options) {
        if (typeof target !== "string") {
          throw new TypeError("Channel target must be a string");
        }
        if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) {
          throw new TypeError("Channel credentials must be a ChannelCredentials object");
        }
        if (options) {
          if (typeof options !== "object") {
            throw new TypeError("Channel options must be an object");
          }
        }
        this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options);
      }
      close() {
        this.internalChannel.close();
      }
      getTarget() {
        return this.internalChannel.getTarget();
      }
      getConnectivityState(tryToConnect) {
        return this.internalChannel.getConnectivityState(tryToConnect);
      }
      watchConnectivityState(currentState, deadline, callback) {
        this.internalChannel.watchConnectivityState(currentState, deadline, callback);
      }
      /**
       * Get the channelz reference object for this channel. The returned value is
       * garbage if channelz is disabled for this channel.
       * @returns
       */
      getChannelzRef() {
        return this.internalChannel.getChannelzRef();
      }
      createCall(method, deadline, host, parentCall, propagateFlags) {
        if (typeof method !== "string") {
          throw new TypeError("Channel#createCall: method must be a string");
        }
        if (!(typeof deadline === "number" || deadline instanceof Date)) {
          throw new TypeError("Channel#createCall: deadline must be a number or Date");
        }
        return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags);
      }
    };
    exports.ChannelImplementation = ChannelImplementation;
  }
});

// node_modules/@grpc/grpc-js/build/src/server-call.js
var require_server_call = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server-call.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = void 0;
    exports.serverErrorToStatus = serverErrorToStatus;
    var events_1 = __require("events");
    var stream_1 = __require("stream");
    var constants_1 = require_constants2();
    var metadata_1 = require_metadata();
    function serverErrorToStatus(error, overrideTrailers) {
      var _a;
      const status = {
        code: constants_1.Status.UNKNOWN,
        details: "message" in error ? error.message : "Unknown Error",
        metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error.metadata) !== null && _a !== void 0 ? _a : null
      };
      if ("code" in error && typeof error.code === "number" && Number.isInteger(error.code)) {
        status.code = error.code;
        if ("details" in error && typeof error.details === "string") {
          status.details = error.details;
        }
      }
      return status;
    }
    __name(serverErrorToStatus, "serverErrorToStatus");
    var ServerUnaryCallImpl = class extends events_1.EventEmitter {
      static {
        __name(this, "ServerUnaryCallImpl");
      }
      constructor(path11, call, metadata, request4) {
        super();
        this.path = path11;
        this.call = call;
        this.metadata = metadata;
        this.request = request4;
        this.cancelled = false;
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
      getAuthContext() {
        return this.call.getAuthContext();
      }
      getMetricsRecorder() {
        return this.call.getMetricsRecorder();
      }
    };
    exports.ServerUnaryCallImpl = ServerUnaryCallImpl;
    var ServerReadableStreamImpl = class extends stream_1.Readable {
      static {
        __name(this, "ServerReadableStreamImpl");
      }
      constructor(path11, call, metadata) {
        super({ objectMode: true });
        this.path = path11;
        this.call = call;
        this.metadata = metadata;
        this.cancelled = false;
      }
      _read(size) {
        this.call.startRead();
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
      getAuthContext() {
        return this.call.getAuthContext();
      }
      getMetricsRecorder() {
        return this.call.getMetricsRecorder();
      }
    };
    exports.ServerReadableStreamImpl = ServerReadableStreamImpl;
    var ServerWritableStreamImpl = class extends stream_1.Writable {
      static {
        __name(this, "ServerWritableStreamImpl");
      }
      constructor(path11, call, metadata, request4) {
        super({ objectMode: true });
        this.path = path11;
        this.call = call;
        this.metadata = metadata;
        this.request = request4;
        this.pendingStatus = {
          code: constants_1.Status.OK,
          details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata();
        this.on("error", (err) => {
          this.pendingStatus = serverErrorToStatus(err);
          this.end();
        });
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
      getAuthContext() {
        return this.call.getAuthContext();
      }
      getMetricsRecorder() {
        return this.call.getMetricsRecorder();
      }
      _write(chunk, encoding, callback) {
        this.call.sendMessage(chunk, callback);
      }
      _final(callback) {
        var _a;
        callback(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata }));
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      end(metadata) {
        if (metadata) {
          this.trailingMetadata = metadata;
        }
        return super.end();
      }
    };
    exports.ServerWritableStreamImpl = ServerWritableStreamImpl;
    var ServerDuplexStreamImpl = class extends stream_1.Duplex {
      static {
        __name(this, "ServerDuplexStreamImpl");
      }
      constructor(path11, call, metadata) {
        super({ objectMode: true });
        this.path = path11;
        this.call = call;
        this.metadata = metadata;
        this.pendingStatus = {
          code: constants_1.Status.OK,
          details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata();
        this.on("error", (err) => {
          this.pendingStatus = serverErrorToStatus(err);
          this.end();
        });
      }
      getPeer() {
        return this.call.getPeer();
      }
      sendMetadata(responseMetadata) {
        this.call.sendMetadata(responseMetadata);
      }
      getDeadline() {
        return this.call.getDeadline();
      }
      getPath() {
        return this.path;
      }
      getHost() {
        return this.call.getHost();
      }
      getAuthContext() {
        return this.call.getAuthContext();
      }
      getMetricsRecorder() {
        return this.call.getMetricsRecorder();
      }
      _read(size) {
        this.call.startRead();
      }
      _write(chunk, encoding, callback) {
        this.call.sendMessage(chunk, callback);
      }
      _final(callback) {
        var _a;
        callback(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata }));
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      end(metadata) {
        if (metadata) {
          this.trailingMetadata = metadata;
        }
        return super.end();
      }
    };
    exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl;
  }
});

// node_modules/@grpc/grpc-js/build/src/server-credentials.js
var require_server_credentials = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server-credentials.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ServerCredentials = void 0;
    exports.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials;
    exports.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors;
    var tls_helpers_1 = require_tls_helpers();
    var ServerCredentials = class {
      static {
        __name(this, "ServerCredentials");
      }
      constructor(serverConstructorOptions, contextOptions) {
        this.serverConstructorOptions = serverConstructorOptions;
        this.watchers = /* @__PURE__ */ new Set();
        this.latestContextOptions = null;
        this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null;
      }
      _addWatcher(watcher) {
        this.watchers.add(watcher);
      }
      _removeWatcher(watcher) {
        this.watchers.delete(watcher);
      }
      getWatcherCount() {
        return this.watchers.size;
      }
      updateSecureContextOptions(options) {
        this.latestContextOptions = options;
        for (const watcher of this.watchers) {
          watcher(this.latestContextOptions);
        }
      }
      _isSecure() {
        return this.serverConstructorOptions !== null;
      }
      _getSecureContextOptions() {
        return this.latestContextOptions;
      }
      _getConstructorOptions() {
        return this.serverConstructorOptions;
      }
      _getInterceptors() {
        return [];
      }
      static createInsecure() {
        return new InsecureServerCredentials();
      }
      static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) {
        var _a;
        if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) {
          throw new TypeError("rootCerts must be null or a Buffer");
        }
        if (!Array.isArray(keyCertPairs)) {
          throw new TypeError("keyCertPairs must be an array");
        }
        if (typeof checkClientCertificate !== "boolean") {
          throw new TypeError("checkClientCertificate must be a boolean");
        }
        const cert = [];
        const key = [];
        for (let i = 0; i < keyCertPairs.length; i++) {
          const pair = keyCertPairs[i];
          if (pair === null || typeof pair !== "object") {
            throw new TypeError(`keyCertPair[${i}] must be an object`);
          }
          if (!Buffer.isBuffer(pair.private_key)) {
            throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`);
          }
          if (!Buffer.isBuffer(pair.cert_chain)) {
            throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`);
          }
          cert.push(pair.cert_chain);
          key.push(pair.private_key);
        }
        return new SecureServerCredentials({
          requestCert: checkClientCertificate,
          ciphers: tls_helpers_1.CIPHER_SUITES
        }, {
          ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : void 0,
          cert,
          key
        });
      }
    };
    exports.ServerCredentials = ServerCredentials;
    var InsecureServerCredentials = class _InsecureServerCredentials extends ServerCredentials {
      static {
        __name(this, "InsecureServerCredentials");
      }
      constructor() {
        super(null);
      }
      _getSettings() {
        return null;
      }
      _equals(other) {
        return other instanceof _InsecureServerCredentials;
      }
    };
    var SecureServerCredentials = class _SecureServerCredentials extends ServerCredentials {
      static {
        __name(this, "SecureServerCredentials");
      }
      constructor(constructorOptions, contextOptions) {
        super(constructorOptions, contextOptions);
        this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions);
      }
      /**
       * Checks equality by checking the options that are actually set by
       * createSsl.
       * @param other
       * @returns
       */
      _equals(other) {
        if (this === other) {
          return true;
        }
        if (!(other instanceof _SecureServerCredentials)) {
          return false;
        }
        if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) {
          if (!this.options.ca.equals(other.options.ca)) {
            return false;
          }
        } else {
          if (this.options.ca !== other.options.ca) {
            return false;
          }
        }
        if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) {
          if (this.options.cert.length !== other.options.cert.length) {
            return false;
          }
          for (let i = 0; i < this.options.cert.length; i++) {
            const thisCert = this.options.cert[i];
            const otherCert = other.options.cert[i];
            if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) {
              if (!thisCert.equals(otherCert)) {
                return false;
              }
            } else {
              if (thisCert !== otherCert) {
                return false;
              }
            }
          }
        } else {
          if (this.options.cert !== other.options.cert) {
            return false;
          }
        }
        if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) {
          if (this.options.key.length !== other.options.key.length) {
            return false;
          }
          for (let i = 0; i < this.options.key.length; i++) {
            const thisKey = this.options.key[i];
            const otherKey = other.options.key[i];
            if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) {
              if (!thisKey.equals(otherKey)) {
                return false;
              }
            } else {
              if (thisKey !== otherKey) {
                return false;
              }
            }
          }
        } else {
          if (this.options.key !== other.options.key) {
            return false;
          }
        }
        if (this.options.requestCert !== other.options.requestCert) {
          return false;
        }
        return true;
      }
    };
    var CertificateProviderServerCredentials = class _CertificateProviderServerCredentials extends ServerCredentials {
      static {
        __name(this, "CertificateProviderServerCredentials");
      }
      constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) {
        super({
          requestCert: caCertificateProvider !== null,
          rejectUnauthorized: requireClientCertificate,
          ciphers: tls_helpers_1.CIPHER_SUITES
        });
        this.identityCertificateProvider = identityCertificateProvider;
        this.caCertificateProvider = caCertificateProvider;
        this.requireClientCertificate = requireClientCertificate;
        this.latestCaUpdate = null;
        this.latestIdentityUpdate = null;
        this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this);
        this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this);
      }
      _addWatcher(watcher) {
        var _a;
        if (this.getWatcherCount() === 0) {
          (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.addCaCertificateListener(this.caCertificateUpdateListener);
          this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        super._addWatcher(watcher);
      }
      _removeWatcher(watcher) {
        var _a;
        super._removeWatcher(watcher);
        if (this.getWatcherCount() === 0) {
          (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeCaCertificateListener(this.caCertificateUpdateListener);
          this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
      }
      _equals(other) {
        if (this === other) {
          return true;
        }
        if (!(other instanceof _CertificateProviderServerCredentials)) {
          return false;
        }
        return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && this.requireClientCertificate === other.requireClientCertificate;
      }
      calculateSecureContextOptions() {
        var _a;
        if (this.latestIdentityUpdate === null) {
          return null;
        }
        if (this.caCertificateProvider !== null && this.latestCaUpdate === null) {
          return null;
        }
        return {
          ca: (_a = this.latestCaUpdate) === null || _a === void 0 ? void 0 : _a.caCertificate,
          cert: [this.latestIdentityUpdate.certificate],
          key: [this.latestIdentityUpdate.privateKey]
        };
      }
      finalizeUpdate() {
        const secureContextOptions = this.calculateSecureContextOptions();
        this.updateSecureContextOptions(secureContextOptions);
      }
      handleCaCertificateUpdate(update) {
        this.latestCaUpdate = update;
        this.finalizeUpdate();
      }
      handleIdentityCertitificateUpdate(update) {
        this.latestIdentityUpdate = update;
        this.finalizeUpdate();
      }
    };
    function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) {
      return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate);
    }
    __name(createCertificateProviderServerCredentials, "createCertificateProviderServerCredentials");
    var InterceptorServerCredentials = class _InterceptorServerCredentials extends ServerCredentials {
      static {
        __name(this, "InterceptorServerCredentials");
      }
      constructor(childCredentials, interceptors) {
        super({});
        this.childCredentials = childCredentials;
        this.interceptors = interceptors;
      }
      _isSecure() {
        return this.childCredentials._isSecure();
      }
      _equals(other) {
        if (!(other instanceof _InterceptorServerCredentials)) {
          return false;
        }
        if (!this.childCredentials._equals(other.childCredentials)) {
          return false;
        }
        if (this.interceptors.length !== other.interceptors.length) {
          return false;
        }
        for (let i = 0; i < this.interceptors.length; i++) {
          if (this.interceptors[i] !== other.interceptors[i]) {
            return false;
          }
        }
        return true;
      }
      _getInterceptors() {
        return this.interceptors;
      }
      _addWatcher(watcher) {
        this.childCredentials._addWatcher(watcher);
      }
      _removeWatcher(watcher) {
        this.childCredentials._removeWatcher(watcher);
      }
      _getConstructorOptions() {
        return this.childCredentials._getConstructorOptions();
      }
      _getSecureContextOptions() {
        return this.childCredentials._getSecureContextOptions();
      }
    };
    function createServerCredentialsWithInterceptors(credentials, interceptors) {
      return new InterceptorServerCredentials(credentials, interceptors);
    }
    __name(createServerCredentialsWithInterceptors, "createServerCredentialsWithInterceptors");
  }
});

// node_modules/@grpc/grpc-js/build/src/duration.js
var require_duration = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/duration.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.durationMessageToDuration = durationMessageToDuration;
    exports.msToDuration = msToDuration;
    exports.durationToMs = durationToMs;
    exports.isDuration = isDuration;
    exports.isDurationMessage = isDurationMessage;
    exports.parseDuration = parseDuration;
    exports.durationToString = durationToString;
    function durationMessageToDuration(message) {
      return {
        seconds: Number.parseInt(message.seconds),
        nanos: message.nanos
      };
    }
    __name(durationMessageToDuration, "durationMessageToDuration");
    function msToDuration(millis) {
      return {
        seconds: millis / 1e3 | 0,
        nanos: millis % 1e3 * 1e6 | 0
      };
    }
    __name(msToDuration, "msToDuration");
    function durationToMs(duration) {
      return duration.seconds * 1e3 + duration.nanos / 1e6 | 0;
    }
    __name(durationToMs, "durationToMs");
    function isDuration(value) {
      return typeof value.seconds === "number" && typeof value.nanos === "number";
    }
    __name(isDuration, "isDuration");
    function isDurationMessage(value) {
      return typeof value.seconds === "string" && typeof value.nanos === "number";
    }
    __name(isDurationMessage, "isDurationMessage");
    var durationRegex = /^(\d+)(?:\.(\d+))?s$/;
    function parseDuration(value) {
      const match = value.match(durationRegex);
      if (!match) {
        return null;
      }
      return {
        seconds: Number.parseInt(match[1], 10),
        nanos: match[2] ? Number.parseInt(match[2].padEnd(9, "0"), 10) : 0
      };
    }
    __name(parseDuration, "parseDuration");
    function durationToString(duration) {
      if (duration.nanos === 0) {
        return `${duration.seconds}s`;
      }
      let scaleFactor;
      if (duration.nanos % 1e6 === 0) {
        scaleFactor = 1e6;
      } else if (duration.nanos % 1e3 === 0) {
        scaleFactor = 1e3;
      } else {
        scaleFactor = 1;
      }
      return `${duration.seconds}.${duration.nanos / scaleFactor}s`;
    }
    __name(durationToString, "durationToString");
  }
});

// node_modules/@grpc/grpc-js/build/src/orca.js
var require_orca = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/orca.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OrcaOobMetricsSubchannelWrapper = exports.GRPC_METRICS_HEADER = exports.ServerMetricRecorder = exports.PerRequestMetricRecorder = void 0;
    exports.createOrcaClient = createOrcaClient;
    exports.createMetricsReader = createMetricsReader;
    var make_client_1 = require_make_client();
    var duration_1 = require_duration();
    var channel_credentials_1 = require_channel_credentials();
    var subchannel_interface_1 = require_subchannel_interface();
    var constants_1 = require_constants2();
    var backoff_timeout_1 = require_backoff_timeout();
    var connectivity_state_1 = require_connectivity_state();
    var loadedOrcaProto = null;
    function loadOrcaProto() {
      if (loadedOrcaProto) {
        return loadedOrcaProto;
      }
      const loaderLoadSync = require_src5().loadSync;
      const loadedProto = loaderLoadSync("xds/service/orca/v3/orca.proto", {
        keepCase: true,
        longs: String,
        enums: String,
        defaults: true,
        oneofs: true,
        includeDirs: [
          `${__qwen_dirname}/../../proto/xds`,
          `${__qwen_dirname}/../../proto/protoc-gen-validate`
        ]
      });
      return (0, make_client_1.loadPackageDefinition)(loadedProto);
    }
    __name(loadOrcaProto, "loadOrcaProto");
    var PerRequestMetricRecorder = class {
      static {
        __name(this, "PerRequestMetricRecorder");
      }
      constructor() {
        this.message = {};
      }
      /**
       * Records a request cost metric measurement for the call.
       * @param name
       * @param value
       */
      recordRequestCostMetric(name, value) {
        if (!this.message.request_cost) {
          this.message.request_cost = {};
        }
        this.message.request_cost[name] = value;
      }
      /**
       * Records a request cost metric measurement for the call.
       * @param name
       * @param value
       */
      recordUtilizationMetric(name, value) {
        if (!this.message.utilization) {
          this.message.utilization = {};
        }
        this.message.utilization[name] = value;
      }
      /**
       * Records an opaque named metric measurement for the call.
       * @param name
       * @param value
       */
      recordNamedMetric(name, value) {
        if (!this.message.named_metrics) {
          this.message.named_metrics = {};
        }
        this.message.named_metrics[name] = value;
      }
      /**
       * Records the CPU utilization metric measurement for the call.
       * @param value
       */
      recordCPUUtilizationMetric(value) {
        this.message.cpu_utilization = value;
      }
      /**
       * Records the memory utilization metric measurement for the call.
       * @param value
       */
      recordMemoryUtilizationMetric(value) {
        this.message.mem_utilization = value;
      }
      /**
       * Records the memory utilization metric measurement for the call.
       * @param value
       */
      recordApplicationUtilizationMetric(value) {
        this.message.application_utilization = value;
      }
      /**
       * Records the queries per second measurement.
       * @param value
       */
      recordQpsMetric(value) {
        this.message.rps_fractional = value;
      }
      /**
       * Records the errors per second measurement.
       * @param value
       */
      recordEpsMetric(value) {
        this.message.eps = value;
      }
      serialize() {
        const orcaProto = loadOrcaProto();
        return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message);
      }
    };
    exports.PerRequestMetricRecorder = PerRequestMetricRecorder;
    var DEFAULT_REPORT_INTERVAL_MS = 3e4;
    var ServerMetricRecorder = class {
      static {
        __name(this, "ServerMetricRecorder");
      }
      constructor() {
        this.message = {};
        this.serviceImplementation = {
          StreamCoreMetrics: /* @__PURE__ */ __name((call) => {
            const reportInterval = call.request.report_interval ? (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : DEFAULT_REPORT_INTERVAL_MS;
            const reportTimer = setInterval(() => {
              call.write(this.message);
            }, reportInterval);
            call.on("cancelled", () => {
              clearInterval(reportTimer);
            });
          }, "StreamCoreMetrics")
        };
      }
      putUtilizationMetric(name, value) {
        if (!this.message.utilization) {
          this.message.utilization = {};
        }
        this.message.utilization[name] = value;
      }
      setAllUtilizationMetrics(metrics2) {
        this.message.utilization = Object.assign({}, metrics2);
      }
      deleteUtilizationMetric(name) {
        var _a;
        (_a = this.message.utilization) === null || _a === void 0 ? true : delete _a[name];
      }
      setCpuUtilizationMetric(value) {
        this.message.cpu_utilization = value;
      }
      deleteCpuUtilizationMetric() {
        delete this.message.cpu_utilization;
      }
      setApplicationUtilizationMetric(value) {
        this.message.application_utilization = value;
      }
      deleteApplicationUtilizationMetric() {
        delete this.message.application_utilization;
      }
      setQpsMetric(value) {
        this.message.rps_fractional = value;
      }
      deleteQpsMetric() {
        delete this.message.rps_fractional;
      }
      setEpsMetric(value) {
        this.message.eps = value;
      }
      deleteEpsMetric() {
        delete this.message.eps;
      }
      addToServer(server) {
        const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service;
        server.addService(serviceDefinition, this.serviceImplementation);
      }
    };
    exports.ServerMetricRecorder = ServerMetricRecorder;
    function createOrcaClient(channel) {
      const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService;
      return new ClientClass("unused", channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel });
    }
    __name(createOrcaClient, "createOrcaClient");
    exports.GRPC_METRICS_HEADER = "endpoint-load-metrics-bin";
    var PARSED_LOAD_REPORT_KEY = "grpc_orca_load_report";
    function createMetricsReader(listener, previousOnCallEnded) {
      return (code, details, metadata) => {
        let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY);
        if (parsedLoadReport) {
          listener(parsedLoadReport);
        } else {
          const serializedLoadReport = metadata.get(exports.GRPC_METRICS_HEADER);
          if (serializedLoadReport.length > 0) {
            const orcaProto = loadOrcaProto();
            parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]);
            listener(parsedLoadReport);
            metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport);
          }
        }
        if (previousOnCallEnded) {
          previousOnCallEnded(code, details, metadata);
        }
      };
    }
    __name(createMetricsReader, "createMetricsReader");
    var DATA_PRODUCER_KEY = "orca_oob_metrics";
    var OobMetricsDataWatcher = class {
      static {
        __name(this, "OobMetricsDataWatcher");
      }
      constructor(metricsListener, intervalMs) {
        this.metricsListener = metricsListener;
        this.intervalMs = intervalMs;
        this.dataProducer = null;
      }
      setSubchannel(subchannel) {
        const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer);
        this.dataProducer = producer;
        producer.addDataWatcher(this);
      }
      destroy() {
        var _a;
        (_a = this.dataProducer) === null || _a === void 0 ? void 0 : _a.removeDataWatcher(this);
      }
      getInterval() {
        return this.intervalMs;
      }
      onMetricsUpdate(metrics2) {
        this.metricsListener(metrics2);
      }
    };
    var OobMetricsDataProducer = class {
      static {
        __name(this, "OobMetricsDataProducer");
      }
      constructor(subchannel) {
        this.subchannel = subchannel;
        this.dataWatchers = /* @__PURE__ */ new Set();
        this.orcaSupported = true;
        this.metricsCall = null;
        this.currentInterval = Infinity;
        this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription());
        this.subchannelStateListener = () => this.updateMetricsSubscription();
        const channel = subchannel.getChannel();
        this.client = createOrcaClient(channel);
        subchannel.addConnectivityStateListener(this.subchannelStateListener);
      }
      addDataWatcher(dataWatcher) {
        this.dataWatchers.add(dataWatcher);
        this.updateMetricsSubscription();
      }
      removeDataWatcher(dataWatcher) {
        var _a;
        this.dataWatchers.delete(dataWatcher);
        if (this.dataWatchers.size === 0) {
          this.subchannel.removeDataProducer(DATA_PRODUCER_KEY);
          (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel();
          this.metricsCall = null;
          this.client.close();
          this.subchannel.removeConnectivityStateListener(this.subchannelStateListener);
        } else {
          this.updateMetricsSubscription();
        }
      }
      updateMetricsSubscription() {
        var _a;
        if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) {
          return;
        }
        const newInterval = Math.min(...Array.from(this.dataWatchers).map((watcher) => watcher.getInterval()));
        if (!this.metricsCall || newInterval !== this.currentInterval) {
          (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel();
          this.currentInterval = newInterval;
          const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) });
          this.metricsCall = metricsCall;
          metricsCall.on("data", (report) => {
            this.dataWatchers.forEach((watcher) => {
              watcher.onMetricsUpdate(report);
            });
          });
          metricsCall.on("error", (error) => {
            this.metricsCall = null;
            if (error.code === constants_1.Status.UNIMPLEMENTED) {
              this.orcaSupported = false;
              return;
            }
            if (error.code === constants_1.Status.CANCELLED) {
              return;
            }
            this.backoffTimer.runOnce();
          });
        }
      }
    };
    var OrcaOobMetricsSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper {
      static {
        __name(this, "OrcaOobMetricsSubchannelWrapper");
      }
      constructor(child, metricsListener, intervalMs) {
        super(child);
        this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs));
      }
      getWrappedSubchannel() {
        return this.child;
      }
    };
    exports.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper;
    function createOobMetricsDataProducer(subchannel) {
      return new OobMetricsDataProducer(subchannel);
    }
    __name(createOobMetricsDataProducer, "createOobMetricsDataProducer");
  }
});

// node_modules/@grpc/grpc-js/build/src/server-interceptors.js
var require_server_interceptors = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server-interceptors.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseServerInterceptingCall = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = void 0;
    exports.isInterceptingServerListener = isInterceptingServerListener;
    exports.getServerInterceptingCall = getServerInterceptingCall;
    var metadata_1 = require_metadata();
    var constants_1 = require_constants2();
    var http2 = __require("http2");
    var error_1 = require_error();
    var zlib2 = __require("zlib");
    var stream_decoder_1 = require_stream_decoder();
    var logging = require_logging();
    var tls_1 = __require("tls");
    var orca_1 = require_orca();
    var TRACER_NAME = "server_call";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var ServerListenerBuilder = class {
      static {
        __name(this, "ServerListenerBuilder");
      }
      constructor() {
        this.metadata = void 0;
        this.message = void 0;
        this.halfClose = void 0;
        this.cancel = void 0;
      }
      withOnReceiveMetadata(onReceiveMetadata) {
        this.metadata = onReceiveMetadata;
        return this;
      }
      withOnReceiveMessage(onReceiveMessage) {
        this.message = onReceiveMessage;
        return this;
      }
      withOnReceiveHalfClose(onReceiveHalfClose) {
        this.halfClose = onReceiveHalfClose;
        return this;
      }
      withOnCancel(onCancel) {
        this.cancel = onCancel;
        return this;
      }
      build() {
        return {
          onReceiveMetadata: this.metadata,
          onReceiveMessage: this.message,
          onReceiveHalfClose: this.halfClose,
          onCancel: this.cancel
        };
      }
    };
    exports.ServerListenerBuilder = ServerListenerBuilder;
    function isInterceptingServerListener(listener) {
      return listener.onReceiveMetadata !== void 0 && listener.onReceiveMetadata.length === 1;
    }
    __name(isInterceptingServerListener, "isInterceptingServerListener");
    var InterceptingServerListenerImpl = class {
      static {
        __name(this, "InterceptingServerListenerImpl");
      }
      constructor(listener, nextListener) {
        this.listener = listener;
        this.nextListener = nextListener;
        this.cancelled = false;
        this.processingMetadata = false;
        this.hasPendingMessage = false;
        this.pendingMessage = null;
        this.processingMessage = false;
        this.hasPendingHalfClose = false;
      }
      processPendingMessage() {
        if (this.hasPendingMessage) {
          this.nextListener.onReceiveMessage(this.pendingMessage);
          this.pendingMessage = null;
          this.hasPendingMessage = false;
        }
      }
      processPendingHalfClose() {
        if (this.hasPendingHalfClose) {
          this.nextListener.onReceiveHalfClose();
          this.hasPendingHalfClose = false;
        }
      }
      onReceiveMetadata(metadata) {
        if (this.cancelled) {
          return;
        }
        this.processingMetadata = true;
        this.listener.onReceiveMetadata(metadata, (interceptedMetadata) => {
          this.processingMetadata = false;
          if (this.cancelled) {
            return;
          }
          this.nextListener.onReceiveMetadata(interceptedMetadata);
          this.processPendingMessage();
          this.processPendingHalfClose();
        });
      }
      onReceiveMessage(message) {
        if (this.cancelled) {
          return;
        }
        this.processingMessage = true;
        this.listener.onReceiveMessage(message, (msg) => {
          this.processingMessage = false;
          if (this.cancelled) {
            return;
          }
          if (this.processingMetadata) {
            this.pendingMessage = msg;
            this.hasPendingMessage = true;
          } else {
            this.nextListener.onReceiveMessage(msg);
            this.processPendingHalfClose();
          }
        });
      }
      onReceiveHalfClose() {
        if (this.cancelled) {
          return;
        }
        this.listener.onReceiveHalfClose(() => {
          if (this.cancelled) {
            return;
          }
          if (this.processingMetadata || this.processingMessage) {
            this.hasPendingHalfClose = true;
          } else {
            this.nextListener.onReceiveHalfClose();
          }
        });
      }
      onCancel() {
        this.cancelled = true;
        this.listener.onCancel();
        this.nextListener.onCancel();
      }
    };
    var ResponderBuilder = class {
      static {
        __name(this, "ResponderBuilder");
      }
      constructor() {
        this.start = void 0;
        this.metadata = void 0;
        this.message = void 0;
        this.status = void 0;
      }
      withStart(start) {
        this.start = start;
        return this;
      }
      withSendMetadata(sendMetadata) {
        this.metadata = sendMetadata;
        return this;
      }
      withSendMessage(sendMessage) {
        this.message = sendMessage;
        return this;
      }
      withSendStatus(sendStatus) {
        this.status = sendStatus;
        return this;
      }
      build() {
        return {
          start: this.start,
          sendMetadata: this.metadata,
          sendMessage: this.message,
          sendStatus: this.status
        };
      }
    };
    exports.ResponderBuilder = ResponderBuilder;
    var defaultServerListener = {
      onReceiveMetadata: /* @__PURE__ */ __name((metadata, next) => {
        next(metadata);
      }, "onReceiveMetadata"),
      onReceiveMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "onReceiveMessage"),
      onReceiveHalfClose: /* @__PURE__ */ __name((next) => {
        next();
      }, "onReceiveHalfClose"),
      onCancel: /* @__PURE__ */ __name(() => {
      }, "onCancel")
    };
    var defaultResponder = {
      start: /* @__PURE__ */ __name((next) => {
        next();
      }, "start"),
      sendMetadata: /* @__PURE__ */ __name((metadata, next) => {
        next(metadata);
      }, "sendMetadata"),
      sendMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "sendMessage"),
      sendStatus: /* @__PURE__ */ __name((status, next) => {
        next(status);
      }, "sendStatus")
    };
    var ServerInterceptingCall = class {
      static {
        __name(this, "ServerInterceptingCall");
      }
      constructor(nextCall, responder) {
        var _a, _b, _c, _d;
        this.nextCall = nextCall;
        this.processingMetadata = false;
        this.sentMetadata = false;
        this.processingMessage = false;
        this.pendingMessage = null;
        this.pendingMessageCallback = null;
        this.pendingStatus = null;
        this.responder = {
          start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start,
          sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata,
          sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage,
          sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus
        };
      }
      processPendingMessage() {
        if (this.pendingMessageCallback) {
          this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback);
          this.pendingMessage = null;
          this.pendingMessageCallback = null;
        }
      }
      processPendingStatus() {
        if (this.pendingStatus) {
          this.nextCall.sendStatus(this.pendingStatus);
          this.pendingStatus = null;
        }
      }
      start(listener) {
        this.responder.start((interceptedListener) => {
          var _a, _b, _c, _d;
          const fullInterceptedListener = {
            onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata,
            onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage,
            onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose,
            onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel
          };
          const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener);
          this.nextCall.start(finalInterceptingListener);
        });
      }
      sendMetadata(metadata) {
        this.processingMetadata = true;
        this.sentMetadata = true;
        this.responder.sendMetadata(metadata, (interceptedMetadata) => {
          this.processingMetadata = false;
          this.nextCall.sendMetadata(interceptedMetadata);
          this.processPendingMessage();
          this.processPendingStatus();
        });
      }
      sendMessage(message, callback) {
        this.processingMessage = true;
        if (!this.sentMetadata) {
          this.sendMetadata(new metadata_1.Metadata());
        }
        this.responder.sendMessage(message, (interceptedMessage) => {
          this.processingMessage = false;
          if (this.processingMetadata) {
            this.pendingMessage = interceptedMessage;
            this.pendingMessageCallback = callback;
          } else {
            this.nextCall.sendMessage(interceptedMessage, callback);
          }
        });
      }
      sendStatus(status) {
        this.responder.sendStatus(status, (interceptedStatus) => {
          if (this.processingMetadata || this.processingMessage) {
            this.pendingStatus = interceptedStatus;
          } else {
            this.nextCall.sendStatus(interceptedStatus);
          }
        });
      }
      startRead() {
        this.nextCall.startRead();
      }
      getPeer() {
        return this.nextCall.getPeer();
      }
      getDeadline() {
        return this.nextCall.getDeadline();
      }
      getHost() {
        return this.nextCall.getHost();
      }
      getAuthContext() {
        return this.nextCall.getAuthContext();
      }
      getConnectionInfo() {
        return this.nextCall.getConnectionInfo();
      }
      getMetricsRecorder() {
        return this.nextCall.getMetricsRecorder();
      }
    };
    exports.ServerInterceptingCall = ServerInterceptingCall;
    var GRPC_ACCEPT_ENCODING_HEADER = "grpc-accept-encoding";
    var GRPC_ENCODING_HEADER = "grpc-encoding";
    var GRPC_MESSAGE_HEADER = "grpc-message";
    var GRPC_STATUS_HEADER = "grpc-status";
    var GRPC_TIMEOUT_HEADER = "grpc-timeout";
    var DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/;
    var deadlineUnitsToMs = {
      H: 36e5,
      M: 6e4,
      S: 1e3,
      m: 1,
      u: 1e-3,
      n: 1e-6
    };
    var defaultCompressionHeaders = {
      // TODO(cjihrig): Remove these encoding headers from the default response
      // once compression is integrated.
      [GRPC_ACCEPT_ENCODING_HEADER]: "identity,deflate,gzip",
      [GRPC_ENCODING_HEADER]: "identity"
    };
    var defaultResponseHeaders = {
      [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK,
      [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto"
    };
    var defaultResponseOptions = {
      waitForTrailers: true
    };
    var BaseServerInterceptingCall = class {
      static {
        __name(this, "BaseServerInterceptingCall");
      }
      constructor(stream, headers, callEventTracker, handler, options) {
        var _a, _b;
        this.stream = stream;
        this.callEventTracker = callEventTracker;
        this.handler = handler;
        this.listener = null;
        this.deadlineTimer = null;
        this.deadline = Infinity;
        this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH;
        this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.cancelled = false;
        this.metadataSent = false;
        this.wantTrailers = false;
        this.cancelNotified = false;
        this.incomingEncoding = "identity";
        this.readQueue = [];
        this.isReadPending = false;
        this.receivedHalfClose = false;
        this.streamEnded = false;
        this.metricsRecorder = new orca_1.PerRequestMetricRecorder();
        this.stream.once("close", () => {
          var _a2;
          trace2("Request to method " + ((_a2 = this.handler) === null || _a2 === void 0 ? void 0 : _a2.path) + " stream closed with rstCode " + this.stream.rstCode);
          if (this.callEventTracker && !this.streamEnded) {
            this.streamEnded = true;
            this.callEventTracker.onStreamEnd(false);
            this.callEventTracker.onCallEnd({
              code: constants_1.Status.CANCELLED,
              details: "Stream closed before sending status",
              metadata: null
            });
          }
          this.notifyOnCancel();
        });
        this.stream.on("data", (data) => {
          this.handleDataFrame(data);
        });
        this.stream.pause();
        this.stream.on("end", () => {
          this.handleEndEvent();
        });
        if ("grpc.max_send_message_length" in options) {
          this.maxSendMessageSize = options["grpc.max_send_message_length"];
        }
        if ("grpc.max_receive_message_length" in options) {
          this.maxReceiveMessageSize = options["grpc.max_receive_message_length"];
        }
        this.host = (_a = headers[":authority"]) !== null && _a !== void 0 ? _a : headers.host;
        this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize);
        const metadata = metadata_1.Metadata.fromHttp2Headers(headers);
        if (logging.isTracerEnabled(TRACER_NAME)) {
          trace2("Request to " + this.handler.path + " received headers " + JSON.stringify(metadata.toJSON()));
        }
        const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER);
        if (timeoutHeader.length > 0) {
          this.handleTimeoutHeader(timeoutHeader[0]);
        }
        const encodingHeader = metadata.get(GRPC_ENCODING_HEADER);
        if (encodingHeader.length > 0) {
          this.incomingEncoding = encodingHeader[0];
        }
        metadata.remove(GRPC_TIMEOUT_HEADER);
        metadata.remove(GRPC_ENCODING_HEADER);
        metadata.remove(GRPC_ACCEPT_ENCODING_HEADER);
        metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING);
        metadata.remove(http2.constants.HTTP2_HEADER_TE);
        metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE);
        this.metadata = metadata;
        const socket = (_b = stream.session) === null || _b === void 0 ? void 0 : _b.socket;
        this.connectionInfo = {
          localAddress: socket === null || socket === void 0 ? void 0 : socket.localAddress,
          localPort: socket === null || socket === void 0 ? void 0 : socket.localPort,
          remoteAddress: socket === null || socket === void 0 ? void 0 : socket.remoteAddress,
          remotePort: socket === null || socket === void 0 ? void 0 : socket.remotePort
        };
        this.shouldSendMetrics = !!options["grpc.server_call_metric_recording"];
      }
      handleTimeoutHeader(timeoutHeader) {
        const match = timeoutHeader.toString().match(DEADLINE_REGEX);
        if (match === null) {
          const status = {
            code: constants_1.Status.INTERNAL,
            details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`,
            metadata: null
          };
          process.nextTick(() => {
            this.sendStatus(status);
          });
          return;
        }
        const timeout = +match[1] * deadlineUnitsToMs[match[2]] | 0;
        const now = /* @__PURE__ */ new Date();
        this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout);
        this.deadlineTimer = setTimeout(() => {
          const status = {
            code: constants_1.Status.DEADLINE_EXCEEDED,
            details: "Deadline exceeded",
            metadata: null
          };
          this.sendStatus(status);
        }, timeout);
      }
      checkCancelled() {
        if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) {
          this.notifyOnCancel();
          this.cancelled = true;
        }
        return this.cancelled;
      }
      notifyOnCancel() {
        if (this.cancelNotified) {
          return;
        }
        this.cancelNotified = true;
        this.cancelled = true;
        process.nextTick(() => {
          var _a;
          (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel();
        });
        if (this.deadlineTimer) {
          clearTimeout(this.deadlineTimer);
        }
        this.stream.resume();
      }
      /**
       * A server handler can start sending messages without explicitly sending
       * metadata. In that case, we need to send headers before sending any
       * messages. This function does that if necessary.
       */
      maybeSendMetadata() {
        if (!this.metadataSent) {
          this.sendMetadata(new metadata_1.Metadata());
        }
      }
      /**
       * Serialize a message to a length-delimited byte string.
       * @param value
       * @returns
       */
      serializeMessage(value) {
        const messageBuffer = this.handler.serialize(value);
        const byteLength = messageBuffer.byteLength;
        const output = Buffer.allocUnsafe(byteLength + 5);
        output.writeUInt8(0, 0);
        output.writeUInt32BE(byteLength, 1);
        messageBuffer.copy(output, 5);
        return output;
      }
      decompressMessage(message, encoding) {
        const messageContents = message.subarray(5);
        if (encoding === "identity") {
          return messageContents;
        } else if (encoding === "deflate" || encoding === "gzip") {
          let decompresser;
          if (encoding === "deflate") {
            decompresser = zlib2.createInflate();
          } else {
            decompresser = zlib2.createGunzip();
          }
          return new Promise((resolve2, reject) => {
            let totalLength = 0;
            const messageParts = [];
            decompresser.on("error", (error) => {
              reject({
                code: constants_1.Status.INTERNAL,
                details: "Failed to decompress message"
              });
            });
            decompresser.on("data", (chunk) => {
              messageParts.push(chunk);
              totalLength += chunk.byteLength;
              if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) {
                decompresser.destroy();
                reject({
                  code: constants_1.Status.RESOURCE_EXHAUSTED,
                  details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`
                });
              }
            });
            decompresser.on("end", () => {
              resolve2(Buffer.concat(messageParts));
            });
            decompresser.write(messageContents);
            decompresser.end();
          });
        } else {
          return Promise.reject({
            code: constants_1.Status.UNIMPLEMENTED,
            details: `Received message compressed with unsupported encoding "${encoding}"`
          });
        }
      }
      async decompressAndMaybePush(queueEntry) {
        if (queueEntry.type !== "COMPRESSED") {
          throw new Error(`Invalid queue entry type: ${queueEntry.type}`);
        }
        const compressed = queueEntry.compressedMessage.readUInt8(0) === 1;
        const compressedMessageEncoding = compressed ? this.incomingEncoding : "identity";
        let decompressedMessage;
        try {
          decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding);
        } catch (err) {
          this.sendStatus(err);
          return;
        }
        try {
          queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage);
        } catch (err) {
          this.sendStatus({
            code: constants_1.Status.INTERNAL,
            details: `Error deserializing request: ${err.message}`
          });
          return;
        }
        queueEntry.type = "READABLE";
        this.maybePushNextMessage();
      }
      maybePushNextMessage() {
        if (this.listener && this.isReadPending && this.readQueue.length > 0 && this.readQueue[0].type !== "COMPRESSED") {
          this.isReadPending = false;
          const nextQueueEntry = this.readQueue.shift();
          if (nextQueueEntry.type === "READABLE") {
            this.listener.onReceiveMessage(nextQueueEntry.parsedMessage);
          } else {
            this.listener.onReceiveHalfClose();
          }
        }
      }
      handleDataFrame(data) {
        var _a;
        if (this.checkCancelled()) {
          return;
        }
        trace2("Request to " + this.handler.path + " received data frame of size " + data.length);
        let rawMessages;
        try {
          rawMessages = this.decoder.write(data);
        } catch (e) {
          this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message });
          return;
        }
        for (const messageBytes of rawMessages) {
          this.stream.pause();
          const queueEntry = {
            type: "COMPRESSED",
            compressedMessage: messageBytes,
            parsedMessage: null
          };
          this.readQueue.push(queueEntry);
          this.decompressAndMaybePush(queueEntry);
          (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived();
        }
      }
      handleEndEvent() {
        this.readQueue.push({
          type: "HALF_CLOSE",
          compressedMessage: null,
          parsedMessage: null
        });
        this.receivedHalfClose = true;
        this.maybePushNextMessage();
      }
      start(listener) {
        trace2("Request to " + this.handler.path + " start called");
        if (this.checkCancelled()) {
          return;
        }
        this.listener = listener;
        listener.onReceiveMetadata(this.metadata);
      }
      sendMetadata(metadata) {
        if (this.checkCancelled()) {
          return;
        }
        if (this.metadataSent) {
          return;
        }
        this.metadataSent = true;
        const custom = metadata ? metadata.toHttp2Headers() : null;
        const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom);
        this.stream.respond(headers, defaultResponseOptions);
      }
      sendMessage(message, callback) {
        if (this.checkCancelled()) {
          return;
        }
        let response;
        try {
          response = this.serializeMessage(message);
        } catch (e) {
          this.sendStatus({
            code: constants_1.Status.INTERNAL,
            details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`,
            metadata: null
          });
          return;
        }
        if (this.maxSendMessageSize !== -1 && response.length - 5 > this.maxSendMessageSize) {
          this.sendStatus({
            code: constants_1.Status.RESOURCE_EXHAUSTED,
            details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`,
            metadata: null
          });
          return;
        }
        this.maybeSendMetadata();
        trace2("Request to " + this.handler.path + " sent data frame of size " + response.length);
        this.stream.write(response, (error) => {
          var _a;
          if (error) {
            this.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`,
              metadata: null
            });
            return;
          }
          (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent();
          callback();
        });
      }
      sendStatus(status) {
        var _a, _b, _c;
        if (this.checkCancelled()) {
          return;
        }
        trace2("Request to method " + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + " ended with status code: " + constants_1.Status[status.code] + " details: " + status.details);
        const statusMetadata = (_c = (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.clone()) !== null && _c !== void 0 ? _c : new metadata_1.Metadata();
        if (this.shouldSendMetrics) {
          statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize());
        }
        if (this.metadataSent) {
          if (!this.wantTrailers) {
            this.wantTrailers = true;
            this.stream.once("wantTrailers", () => {
              if (this.callEventTracker && !this.streamEnded) {
                this.streamEnded = true;
                this.callEventTracker.onStreamEnd(true);
                this.callEventTracker.onCallEnd(status);
              }
              const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers());
              this.stream.sendTrailers(trailersToSend);
              this.notifyOnCancel();
            });
            this.stream.end();
          } else {
            this.notifyOnCancel();
          }
        } else {
          if (this.callEventTracker && !this.streamEnded) {
            this.streamEnded = true;
            this.callEventTracker.onStreamEnd(true);
            this.callEventTracker.onCallEnd(status);
          }
          const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers());
          this.stream.respond(trailersToSend, { endStream: true });
          this.notifyOnCancel();
        }
      }
      startRead() {
        trace2("Request to " + this.handler.path + " startRead called");
        if (this.checkCancelled()) {
          return;
        }
        this.isReadPending = true;
        if (this.readQueue.length === 0) {
          if (!this.receivedHalfClose) {
            this.stream.resume();
          }
        } else {
          this.maybePushNextMessage();
        }
      }
      getPeer() {
        var _a;
        const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket;
        if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) {
          if (socket.remotePort) {
            return `${socket.remoteAddress}:${socket.remotePort}`;
          } else {
            return socket.remoteAddress;
          }
        } else {
          return "unknown";
        }
      }
      getDeadline() {
        return this.deadline;
      }
      getHost() {
        return this.host;
      }
      getAuthContext() {
        var _a;
        if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) {
          const peerCertificate = this.stream.session.socket.getPeerCertificate();
          return {
            transportSecurityType: "ssl",
            sslPeerCertificate: peerCertificate.raw ? peerCertificate : void 0
          };
        } else {
          return {};
        }
      }
      getConnectionInfo() {
        return this.connectionInfo;
      }
      getMetricsRecorder() {
        return this.metricsRecorder;
      }
    };
    exports.BaseServerInterceptingCall = BaseServerInterceptingCall;
    function getServerInterceptingCall(interceptors, stream, headers, callEventTracker, handler, options) {
      const methodDefinition = {
        path: handler.path,
        requestStream: handler.type === "clientStream" || handler.type === "bidi",
        responseStream: handler.type === "serverStream" || handler.type === "bidi",
        requestDeserialize: handler.deserialize,
        responseSerialize: handler.serialize
      };
      const baseCall = new BaseServerInterceptingCall(stream, headers, callEventTracker, handler, options);
      return interceptors.reduce((call, interceptor) => {
        return interceptor(methodDefinition, call);
      }, baseCall);
    }
    __name(getServerInterceptingCall, "getServerInterceptingCall");
  }
});

// node_modules/@grpc/grpc-js/build/src/server.js
var require_server = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/server.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var __runInitializers = exports && exports.__runInitializers || function(thisArg, initializers, value) {
      var useValue = arguments.length > 2;
      for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
      }
      return useValue ? value : void 0;
    };
    var __esDecorate = exports && exports.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
      function accept(f) {
        if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
        return f;
      }
      __name(accept, "accept");
      var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
      var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
      var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
      var _, done = false;
      for (var i = decorators.length - 1; i >= 0; i--) {
        var context2 = {};
        for (var p in contextIn) context2[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context2.access[p] = contextIn.access[p];
        context2.addInitializer = function(f) {
          if (done) throw new TypeError("Cannot add initializers after decoration has completed");
          extraInitializers.push(accept(f || null));
        };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context2);
        if (kind === "accessor") {
          if (result === void 0) continue;
          if (result === null || typeof result !== "object") throw new TypeError("Object expected");
          if (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
        } else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
        }
      }
      if (target) Object.defineProperty(target, contextIn.name, descriptor);
      done = true;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Server = void 0;
    var http2 = __require("http2");
    var util = __require("util");
    var constants_1 = require_constants2();
    var server_call_1 = require_server_call();
    var server_credentials_1 = require_server_credentials();
    var resolver_1 = require_resolver();
    var logging = require_logging();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var channelz_1 = require_channelz();
    var server_interceptors_1 = require_server_interceptors();
    var UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31);
    var KEEPALIVE_MAX_TIME_MS = ~(1 << 31);
    var KEEPALIVE_TIMEOUT_MS = 2e4;
    var MAX_CONNECTION_IDLE_MS = ~(1 << 31);
    var { HTTP2_HEADER_PATH } = http2.constants;
    var TRACER_NAME = "server";
    var kMaxAge = Buffer.from("max_age");
    function serverCallTrace(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, "server_call", text);
    }
    __name(serverCallTrace, "serverCallTrace");
    function noop() {
    }
    __name(noop, "noop");
    function deprecate(message) {
      return function(target, context2) {
        return util.deprecate(target, message);
      };
    }
    __name(deprecate, "deprecate");
    function getUnimplementedStatusResponse(methodName) {
      return {
        code: constants_1.Status.UNIMPLEMENTED,
        details: `The server does not implement the method ${methodName}`
      };
    }
    __name(getUnimplementedStatusResponse, "getUnimplementedStatusResponse");
    function getDefaultHandler(handlerType, methodName) {
      const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName);
      switch (handlerType) {
        case "unary":
          return (call, callback) => {
            callback(unimplementedStatusResponse, null);
          };
        case "clientStream":
          return (call, callback) => {
            callback(unimplementedStatusResponse, null);
          };
        case "serverStream":
          return (call) => {
            call.emit("error", unimplementedStatusResponse);
          };
        case "bidi":
          return (call) => {
            call.emit("error", unimplementedStatusResponse);
          };
        default:
          throw new Error(`Invalid handlerType ${handlerType}`);
      }
    }
    __name(getDefaultHandler, "getDefaultHandler");
    var Server = (() => {
      var _a;
      let _instanceExtraInitializers = [];
      let _start_decorators;
      return _a = class Server {
        static {
          __name(this, "Server");
        }
        constructor(options) {
          var _b, _c, _d, _e, _f, _g;
          this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map());
          this.http2Servers = /* @__PURE__ */ new Map();
          this.sessionIdleTimeouts = /* @__PURE__ */ new Map();
          this.handlers = /* @__PURE__ */ new Map();
          this.sessions = /* @__PURE__ */ new Map();
          this.started = false;
          this.shutdown = false;
          this.serverAddressString = "null";
          this.channelzEnabled = true;
          this.options = options !== null && options !== void 0 ? options : {};
          if (this.options["grpc.enable_channelz"] === 0) {
            this.channelzEnabled = false;
            this.channelzTrace = new channelz_1.ChannelzTraceStub();
            this.callTracker = new channelz_1.ChannelzCallTrackerStub();
            this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub();
            this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub();
          } else {
            this.channelzTrace = new channelz_1.ChannelzTrace();
            this.callTracker = new channelz_1.ChannelzCallTracker();
            this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker();
            this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker();
          }
          this.channelzRef = (0, channelz_1.registerChannelzServer)("server", () => this.getChannelzInfo(), this.channelzEnabled);
          this.channelzTrace.addTrace("CT_INFO", "Server created");
          this.maxConnectionAgeMs = (_b = this.options["grpc.max_connection_age_ms"]) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS;
          this.maxConnectionAgeGraceMs = (_c = this.options["grpc.max_connection_age_grace_ms"]) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS;
          this.keepaliveTimeMs = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS;
          this.keepaliveTimeoutMs = (_e = this.options["grpc.keepalive_timeout_ms"]) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS;
          this.sessionIdleTimeout = (_f = this.options["grpc.max_connection_idle_ms"]) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS;
          this.commonServerOptions = {
            maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER
          };
          if ("grpc-node.max_session_memory" in this.options) {
            this.commonServerOptions.maxSessionMemory = this.options["grpc-node.max_session_memory"];
          } else {
            this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER;
          }
          if ("grpc.max_concurrent_streams" in this.options) {
            this.commonServerOptions.settings = {
              maxConcurrentStreams: this.options["grpc.max_concurrent_streams"]
            };
          }
          this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : [];
          this.trace("Server constructed");
        }
        getChannelzInfo() {
          return {
            trace: this.channelzTrace,
            callTracker: this.callTracker,
            listenerChildren: this.listenerChildrenTracker.getChildLists(),
            sessionChildren: this.sessionChildrenTracker.getChildLists()
          };
        }
        getChannelzSessionInfo(session) {
          var _b, _c, _d;
          const sessionInfo = this.sessions.get(session);
          const sessionSocket = session.socket;
          const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null;
          const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null;
          let tlsInfo;
          if (session.encrypted) {
            const tlsSocket = sessionSocket;
            const cipherInfo = tlsSocket.getCipher();
            const certificate = tlsSocket.getCertificate();
            const peerCertificate = tlsSocket.getPeerCertificate();
            tlsInfo = {
              cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null,
              cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name,
              localCertificate: certificate && "raw" in certificate ? certificate.raw : null,
              remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null
            };
          } else {
            tlsInfo = null;
          }
          const socketInfo = {
            remoteAddress,
            localAddress,
            security: tlsInfo,
            remoteName: null,
            streamsStarted: sessionInfo.streamTracker.callsStarted,
            streamsSucceeded: sessionInfo.streamTracker.callsSucceeded,
            streamsFailed: sessionInfo.streamTracker.callsFailed,
            messagesSent: sessionInfo.messagesSent,
            messagesReceived: sessionInfo.messagesReceived,
            keepAlivesSent: sessionInfo.keepAlivesSent,
            lastLocalStreamCreatedTimestamp: null,
            lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp,
            lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp,
            lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp,
            localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null,
            remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null
          };
          return socketInfo;
        }
        trace(text) {
          logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + text);
        }
        keepaliveTrace(text) {
          logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + text);
        }
        addProtoService() {
          throw new Error("Not implemented. Use addService() instead");
        }
        addService(service, implementation) {
          if (service === null || typeof service !== "object" || implementation === null || typeof implementation !== "object") {
            throw new Error("addService() requires two objects as arguments");
          }
          const serviceKeys = Object.keys(service);
          if (serviceKeys.length === 0) {
            throw new Error("Cannot add an empty service to a server");
          }
          serviceKeys.forEach((name) => {
            const attrs = service[name];
            let methodType;
            if (attrs.requestStream) {
              if (attrs.responseStream) {
                methodType = "bidi";
              } else {
                methodType = "clientStream";
              }
            } else {
              if (attrs.responseStream) {
                methodType = "serverStream";
              } else {
                methodType = "unary";
              }
            }
            let implFn = implementation[name];
            let impl;
            if (implFn === void 0 && typeof attrs.originalName === "string") {
              implFn = implementation[attrs.originalName];
            }
            if (implFn !== void 0) {
              impl = implFn.bind(implementation);
            } else {
              impl = getDefaultHandler(methodType, name);
            }
            const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType);
            if (success === false) {
              throw new Error(`Method handler for ${attrs.path} already provided.`);
            }
          });
        }
        removeService(service) {
          if (service === null || typeof service !== "object") {
            throw new Error("removeService() requires object as argument");
          }
          const serviceKeys = Object.keys(service);
          serviceKeys.forEach((name) => {
            const attrs = service[name];
            this.unregister(attrs.path);
          });
        }
        bind(port, creds) {
          throw new Error("Not implemented. Use bindAsync() instead");
        }
        /**
         * This API is experimental, so API stability is not guaranteed across minor versions.
         * @param boundAddress
         * @returns
         */
        experimentalRegisterListenerToChannelz(boundAddress) {
          return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => {
            return {
              localAddress: boundAddress,
              remoteAddress: null,
              security: null,
              remoteName: null,
              streamsStarted: 0,
              streamsSucceeded: 0,
              streamsFailed: 0,
              messagesSent: 0,
              messagesReceived: 0,
              keepAlivesSent: 0,
              lastLocalStreamCreatedTimestamp: null,
              lastRemoteStreamCreatedTimestamp: null,
              lastMessageSentTimestamp: null,
              lastMessageReceivedTimestamp: null,
              localFlowControlWindow: null,
              remoteFlowControlWindow: null
            };
          }, this.channelzEnabled);
        }
        experimentalUnregisterListenerFromChannelz(channelzRef) {
          (0, channelz_1.unregisterChannelzRef)(channelzRef);
        }
        createHttp2Server(credentials) {
          let http2Server;
          if (credentials._isSecure()) {
            const constructorOptions = credentials._getConstructorOptions();
            const contextOptions = credentials._getSecureContextOptions();
            const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options["grpc-node.tls_enable_trace"] === 1 });
            let areCredentialsValid = contextOptions !== null;
            this.trace("Initial credentials valid: " + areCredentialsValid);
            http2Server = http2.createSecureServer(secureServerOptions);
            http2Server.prependListener("connection", (socket) => {
              if (!areCredentialsValid) {
                this.trace("Dropped connection from " + JSON.stringify(socket.address()) + " due to unloaded credentials");
                socket.destroy();
              }
            });
            http2Server.on("secureConnection", (socket) => {
              socket.on("error", (e) => {
                this.trace("An incoming TLS connection closed with error: " + e.message);
              });
            });
            const credsWatcher = /* @__PURE__ */ __name((options) => {
              if (options) {
                const secureServer = http2Server;
                try {
                  secureServer.setSecureContext(options);
                } catch (e) {
                  logging.log(constants_1.LogVerbosity.ERROR, "Failed to set secure context with error " + e.message);
                  options = null;
                }
              }
              areCredentialsValid = options !== null;
              this.trace("Post-update credentials valid: " + areCredentialsValid);
            }, "credsWatcher");
            credentials._addWatcher(credsWatcher);
            http2Server.on("close", () => {
              credentials._removeWatcher(credsWatcher);
            });
          } else {
            http2Server = http2.createServer(this.commonServerOptions);
          }
          http2Server.setTimeout(0, noop);
          this._setupHandlers(http2Server, credentials._getInterceptors());
          return http2Server;
        }
        bindOneAddress(address, boundPortObject) {
          this.trace("Attempting to bind " + (0, subchannel_address_1.subchannelAddressToString)(address));
          const http2Server = this.createHttp2Server(boundPortObject.credentials);
          return new Promise((resolve2, reject) => {
            const onError = /* @__PURE__ */ __name((err) => {
              this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(address) + " with error " + err.message);
              resolve2({
                port: "port" in address ? address.port : 1,
                error: err.message
              });
            }, "onError");
            http2Server.once("error", onError);
            http2Server.listen(address, () => {
              const boundAddress = http2Server.address();
              let boundSubchannelAddress;
              if (typeof boundAddress === "string") {
                boundSubchannelAddress = {
                  path: boundAddress
                };
              } else {
                boundSubchannelAddress = {
                  host: boundAddress.address,
                  port: boundAddress.port
                };
              }
              const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress);
              this.listenerChildrenTracker.refChild(channelzRef);
              this.http2Servers.set(http2Server, {
                channelzRef,
                sessions: /* @__PURE__ */ new Set(),
                ownsChannelzRef: true
              });
              boundPortObject.listeningServers.add(http2Server);
              this.trace("Successfully bound " + (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress));
              resolve2({
                port: "port" in boundSubchannelAddress ? boundSubchannelAddress.port : 1
              });
              http2Server.removeListener("error", onError);
            });
          });
        }
        async bindManyPorts(addressList, boundPortObject) {
          if (addressList.length === 0) {
            return {
              count: 0,
              port: 0,
              errors: []
            };
          }
          if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) {
            const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject);
            if (firstAddressResult.error) {
              const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject);
              return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] });
            } else {
              const restAddresses = addressList.slice(1).map((address) => (0, subchannel_address_1.isTcpSubchannelAddress)(address) ? { host: address.host, port: firstAddressResult.port } : address);
              const restAddressResult = await Promise.all(restAddresses.map((address) => this.bindOneAddress(address, boundPortObject)));
              const allResults = [firstAddressResult, ...restAddressResult];
              return {
                count: allResults.filter((result) => result.error === void 0).length,
                port: firstAddressResult.port,
                errors: allResults.filter((result) => result.error).map((result) => result.error)
              };
            }
          } else {
            const allResults = await Promise.all(addressList.map((address) => this.bindOneAddress(address, boundPortObject)));
            return {
              count: allResults.filter((result) => result.error === void 0).length,
              port: allResults[0].port,
              errors: allResults.filter((result) => result.error).map((result) => result.error)
            };
          }
        }
        async bindAddressList(addressList, boundPortObject) {
          const bindResult = await this.bindManyPorts(addressList, boundPortObject);
          if (bindResult.count > 0) {
            if (bindResult.count < addressList.length) {
              logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`);
            }
            return bindResult.port;
          } else {
            const errorString = `No address added out of total ${addressList.length} resolved`;
            logging.log(constants_1.LogVerbosity.ERROR, errorString);
            throw new Error(`${errorString} errors: [${bindResult.errors.join(",")}]`);
          }
        }
        resolvePort(port) {
          return new Promise((resolve2, reject) => {
            let seenResolution = false;
            const resolverListener = /* @__PURE__ */ __name((endpointList, attributes, serviceConfig, resolutionNote) => {
              if (seenResolution) {
                return true;
              }
              seenResolution = true;
              if (!endpointList.ok) {
                reject(new Error(endpointList.error.details));
                return true;
              }
              const addressList = [].concat(...endpointList.value.map((endpoint) => endpoint.addresses));
              if (addressList.length === 0) {
                reject(new Error(`No addresses resolved for port ${port}`));
                return true;
              }
              resolve2(addressList);
              return true;
            }, "resolverListener");
            const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options);
            resolver.updateResolution();
          });
        }
        async bindPort(port, boundPortObject) {
          const addressList = await this.resolvePort(port);
          if (boundPortObject.cancelled) {
            this.completeUnbind(boundPortObject);
            throw new Error("bindAsync operation cancelled by unbind call");
          }
          const portNumber = await this.bindAddressList(addressList, boundPortObject);
          if (boundPortObject.cancelled) {
            this.completeUnbind(boundPortObject);
            throw new Error("bindAsync operation cancelled by unbind call");
          }
          return portNumber;
        }
        normalizePort(port) {
          const initialPortUri = (0, uri_parser_1.parseUri)(port);
          if (initialPortUri === null) {
            throw new Error(`Could not parse port "${port}"`);
          }
          const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri);
          if (portUri === null) {
            throw new Error(`Could not get a default scheme for port "${port}"`);
          }
          return portUri;
        }
        bindAsync(port, creds, callback) {
          if (this.shutdown) {
            throw new Error("bindAsync called after shutdown");
          }
          if (typeof port !== "string") {
            throw new TypeError("port must be a string");
          }
          if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) {
            throw new TypeError("creds must be a ServerCredentials object");
          }
          if (typeof callback !== "function") {
            throw new TypeError("callback must be a function");
          }
          this.trace("bindAsync port=" + port);
          const portUri = this.normalizePort(port);
          const deferredCallback = /* @__PURE__ */ __name((error, port2) => {
            process.nextTick(() => callback(error, port2));
          }, "deferredCallback");
          let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri));
          if (boundPortObject) {
            if (!creds._equals(boundPortObject.credentials)) {
              deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0);
              return;
            }
            boundPortObject.cancelled = false;
            if (boundPortObject.completionPromise) {
              boundPortObject.completionPromise.then((portNum) => callback(null, portNum), (error) => callback(error, 0));
            } else {
              deferredCallback(null, boundPortObject.portNumber);
            }
            return;
          }
          boundPortObject = {
            mapKey: (0, uri_parser_1.uriToString)(portUri),
            originalUri: portUri,
            completionPromise: null,
            cancelled: false,
            portNumber: 0,
            credentials: creds,
            listeningServers: /* @__PURE__ */ new Set()
          };
          const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path);
          const completionPromise = this.bindPort(portUri, boundPortObject);
          boundPortObject.completionPromise = completionPromise;
          if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) {
            completionPromise.then((portNum) => {
              const finalUri = {
                scheme: portUri.scheme,
                authority: portUri.authority,
                path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum })
              };
              boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri);
              boundPortObject.completionPromise = null;
              boundPortObject.portNumber = portNum;
              this.boundPorts.set(boundPortObject.mapKey, boundPortObject);
              callback(null, portNum);
            }, (error) => {
              callback(error, 0);
            });
          } else {
            this.boundPorts.set(boundPortObject.mapKey, boundPortObject);
            completionPromise.then((portNum) => {
              boundPortObject.completionPromise = null;
              boundPortObject.portNumber = portNum;
              callback(null, portNum);
            }, (error) => {
              callback(error, 0);
            });
          }
        }
        registerInjectorToChannelz() {
          return (0, channelz_1.registerChannelzSocket)("injector", () => {
            return {
              localAddress: null,
              remoteAddress: null,
              security: null,
              remoteName: null,
              streamsStarted: 0,
              streamsSucceeded: 0,
              streamsFailed: 0,
              messagesSent: 0,
              messagesReceived: 0,
              keepAlivesSent: 0,
              lastLocalStreamCreatedTimestamp: null,
              lastRemoteStreamCreatedTimestamp: null,
              lastMessageSentTimestamp: null,
              lastMessageReceivedTimestamp: null,
              localFlowControlWindow: null,
              remoteFlowControlWindow: null
            };
          }, this.channelzEnabled);
        }
        /**
         * This API is experimental, so API stability is not guaranteed across minor versions.
         * @param credentials
         * @param channelzRef
         * @returns
         */
        experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) {
          if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) {
            throw new TypeError("creds must be a ServerCredentials object");
          }
          if (this.channelzEnabled) {
            this.listenerChildrenTracker.refChild(channelzRef);
          }
          const server = this.createHttp2Server(credentials);
          const sessionsSet = /* @__PURE__ */ new Set();
          this.http2Servers.set(server, {
            channelzRef,
            sessions: sessionsSet,
            ownsChannelzRef
          });
          return {
            injectConnection: /* @__PURE__ */ __name((connection) => {
              server.emit("connection", connection);
            }, "injectConnection"),
            drain: /* @__PURE__ */ __name((graceTimeMs) => {
              var _b, _c;
              for (const session of sessionsSet) {
                this.closeSession(session);
              }
              (_c = (_b = setTimeout(() => {
                for (const session of sessionsSet) {
                  session.destroy(http2.constants.NGHTTP2_CANCEL);
                }
              }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b);
            }, "drain"),
            destroy: /* @__PURE__ */ __name(() => {
              this.closeServer(server);
              for (const session of sessionsSet) {
                this.closeSession(session);
              }
            }, "destroy")
          };
        }
        createConnectionInjector(credentials) {
          if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) {
            throw new TypeError("creds must be a ServerCredentials object");
          }
          const channelzRef = this.registerInjectorToChannelz();
          return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true);
        }
        closeServer(server, callback) {
          this.trace("Closing server with address " + JSON.stringify(server.address()));
          const serverInfo = this.http2Servers.get(server);
          server.close(() => {
            if (serverInfo && serverInfo.ownsChannelzRef) {
              this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef);
              (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef);
            }
            this.http2Servers.delete(server);
            callback === null || callback === void 0 ? void 0 : callback();
          });
        }
        closeSession(session, callback) {
          var _b;
          this.trace("Closing session initiated by " + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress));
          const sessionInfo = this.sessions.get(session);
          const closeCallback = /* @__PURE__ */ __name(() => {
            if (sessionInfo) {
              this.sessionChildrenTracker.unrefChild(sessionInfo.ref);
              (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref);
            }
            callback === null || callback === void 0 ? void 0 : callback();
          }, "closeCallback");
          if (session.closed) {
            queueMicrotask(closeCallback);
          } else {
            session.close(closeCallback);
          }
        }
        completeUnbind(boundPortObject) {
          for (const server of boundPortObject.listeningServers) {
            const serverInfo = this.http2Servers.get(server);
            this.closeServer(server, () => {
              boundPortObject.listeningServers.delete(server);
            });
            if (serverInfo) {
              for (const session of serverInfo.sessions) {
                this.closeSession(session);
              }
            }
          }
          this.boundPorts.delete(boundPortObject.mapKey);
        }
        /**
         * Unbind a previously bound port, or cancel an in-progress bindAsync
         * operation. If port 0 was bound, only the actual bound port can be
         * unbound. For example, if bindAsync was called with "localhost:0" and the
         * bound port result was 54321, it can be unbound as "localhost:54321".
         * @param port
         */
        unbind(port) {
          this.trace("unbind port=" + port);
          const portUri = this.normalizePort(port);
          const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path);
          if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) {
            throw new Error("Cannot unbind port 0");
          }
          const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri));
          if (boundPortObject) {
            this.trace("unbinding " + boundPortObject.mapKey + " originally bound as " + (0, uri_parser_1.uriToString)(boundPortObject.originalUri));
            if (boundPortObject.completionPromise) {
              boundPortObject.cancelled = true;
            } else {
              this.completeUnbind(boundPortObject);
            }
          }
        }
        /**
         * Gracefully close all connections associated with a previously bound port.
         * After the grace time, forcefully close all remaining open connections.
         *
         * If port 0 was bound, only the actual bound port can be
         * drained. For example, if bindAsync was called with "localhost:0" and the
         * bound port result was 54321, it can be drained as "localhost:54321".
         * @param port
         * @param graceTimeMs
         * @returns
         */
        drain(port, graceTimeMs) {
          var _b, _c;
          this.trace("drain port=" + port + " graceTimeMs=" + graceTimeMs);
          const portUri = this.normalizePort(port);
          const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path);
          if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) {
            throw new Error("Cannot drain port 0");
          }
          const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri));
          if (!boundPortObject) {
            return;
          }
          const allSessions = /* @__PURE__ */ new Set();
          for (const http2Server of boundPortObject.listeningServers) {
            const serverEntry = this.http2Servers.get(http2Server);
            if (serverEntry) {
              for (const session of serverEntry.sessions) {
                allSessions.add(session);
                this.closeSession(session, () => {
                  allSessions.delete(session);
                });
              }
            }
          }
          (_c = (_b = setTimeout(() => {
            for (const session of allSessions) {
              session.destroy(http2.constants.NGHTTP2_CANCEL);
            }
          }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b);
        }
        forceShutdown() {
          for (const boundPortObject of this.boundPorts.values()) {
            boundPortObject.cancelled = true;
          }
          this.boundPorts.clear();
          for (const server of this.http2Servers.keys()) {
            this.closeServer(server);
          }
          this.sessions.forEach((channelzInfo, session) => {
            this.closeSession(session);
            session.destroy(http2.constants.NGHTTP2_CANCEL);
          });
          this.sessions.clear();
          (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
          this.shutdown = true;
        }
        register(name, handler, serialize, deserialize, type) {
          if (this.handlers.has(name)) {
            return false;
          }
          this.handlers.set(name, {
            func: handler,
            serialize,
            deserialize,
            type,
            path: name
          });
          return true;
        }
        unregister(name) {
          return this.handlers.delete(name);
        }
        /**
         * @deprecated No longer needed as of version 1.10.x
         */
        start() {
          if (this.http2Servers.size === 0 || [...this.http2Servers.keys()].every((server) => !server.listening)) {
            throw new Error("server must be bound in order to start");
          }
          if (this.started === true) {
            throw new Error("server is already started");
          }
          this.started = true;
        }
        tryShutdown(callback) {
          var _b;
          const wrappedCallback = /* @__PURE__ */ __name((error) => {
            (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
            callback(error);
          }, "wrappedCallback");
          let pendingChecks = 0;
          function maybeCallback() {
            pendingChecks--;
            if (pendingChecks === 0) {
              wrappedCallback();
            }
          }
          __name(maybeCallback, "maybeCallback");
          this.shutdown = true;
          for (const [serverKey, server] of this.http2Servers.entries()) {
            pendingChecks++;
            const serverString = server.channelzRef.name;
            this.trace("Waiting for server " + serverString + " to close");
            this.closeServer(serverKey, () => {
              this.trace("Server " + serverString + " finished closing");
              maybeCallback();
            });
            for (const session of server.sessions.keys()) {
              pendingChecks++;
              const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress;
              this.trace("Waiting for session " + sessionString + " to close");
              this.closeSession(session, () => {
                this.trace("Session " + sessionString + " finished closing");
                maybeCallback();
              });
            }
          }
          if (pendingChecks === 0) {
            wrappedCallback();
          }
        }
        addHttp2Port() {
          throw new Error("Not yet implemented");
        }
        /**
         * Get the channelz reference object for this server. The returned value is
         * garbage if channelz is disabled for this server.
         * @returns
         */
        getChannelzRef() {
          return this.channelzRef;
        }
        _verifyContentType(stream, headers) {
          const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE];
          if (typeof contentType !== "string" || !contentType.startsWith("application/grpc")) {
            stream.respond({
              [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE
            }, { endStream: true });
            return false;
          }
          return true;
        }
        _retrieveHandler(path11) {
          serverCallTrace("Received call to method " + path11 + " at address " + this.serverAddressString);
          const handler = this.handlers.get(path11);
          if (handler === void 0) {
            serverCallTrace("No handler registered for method " + path11 + ". Sending UNIMPLEMENTED status.");
            return null;
          }
          return handler;
        }
        _respondWithError(err, stream, channelzSessionInfo = null) {
          var _b, _c;
          const trailersToSend = Object.assign({ "grpc-status": (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, "grpc-message": err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers());
          stream.respond(trailersToSend, { endStream: true });
          this.callTracker.addCallFailed();
          channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
        }
        _channelzHandler(extraInterceptors, stream, headers) {
          stream.once("error", (err) => {
          });
          this.onStreamOpened(stream);
          const channelzSessionInfo = this.sessions.get(stream.session);
          this.callTracker.addCallStarted();
          channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted();
          if (!this._verifyContentType(stream, headers)) {
            this.callTracker.addCallFailed();
            channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
            return;
          }
          const path11 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path11);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path11), stream, channelzSessionInfo);
            return;
          }
          const callEventTracker = {
            addMessageSent: /* @__PURE__ */ __name(() => {
              if (channelzSessionInfo) {
                channelzSessionInfo.messagesSent += 1;
                channelzSessionInfo.lastMessageSentTimestamp = /* @__PURE__ */ new Date();
              }
            }, "addMessageSent"),
            addMessageReceived: /* @__PURE__ */ __name(() => {
              if (channelzSessionInfo) {
                channelzSessionInfo.messagesReceived += 1;
                channelzSessionInfo.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date();
              }
            }, "addMessageReceived"),
            onCallEnd: /* @__PURE__ */ __name((status) => {
              if (status.code === constants_1.Status.OK) {
                this.callTracker.addCallSucceeded();
              } else {
                this.callTracker.addCallFailed();
              }
            }, "onCallEnd"),
            onStreamEnd: /* @__PURE__ */ __name((success) => {
              if (channelzSessionInfo) {
                if (success) {
                  channelzSessionInfo.streamTracker.addCallSucceeded();
                } else {
                  channelzSessionInfo.streamTracker.addCallFailed();
                }
              }
            }, "onStreamEnd")
          };
          const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, callEventTracker, handler, this.options);
          if (!this._runHandlerForCall(call, handler)) {
            this.callTracker.addCallFailed();
            channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
            call.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Unknown handler type: ${handler.type}`
            });
          }
        }
        _streamHandler(extraInterceptors, stream, headers) {
          stream.once("error", (err) => {
          });
          this.onStreamOpened(stream);
          if (this._verifyContentType(stream, headers) !== true) {
            return;
          }
          const path11 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path11);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path11), stream, null);
            return;
          }
          const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, null, handler, this.options);
          if (!this._runHandlerForCall(call, handler)) {
            call.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Unknown handler type: ${handler.type}`
            });
          }
        }
        _runHandlerForCall(call, handler) {
          const { type } = handler;
          if (type === "unary") {
            handleUnary(call, handler);
          } else if (type === "clientStream") {
            handleClientStreaming(call, handler);
          } else if (type === "serverStream") {
            handleServerStreaming(call, handler);
          } else if (type === "bidi") {
            handleBidiStreaming(call, handler);
          } else {
            return false;
          }
          return true;
        }
        _setupHandlers(http2Server, extraInterceptors) {
          if (http2Server === null) {
            return;
          }
          const serverAddress = http2Server.address();
          let serverAddressString = "null";
          if (serverAddress) {
            if (typeof serverAddress === "string") {
              serverAddressString = serverAddress;
            } else {
              serverAddressString = serverAddress.address + ":" + serverAddress.port;
            }
          }
          this.serverAddressString = serverAddressString;
          const handler = this.channelzEnabled ? this._channelzHandler : this._streamHandler;
          const sessionHandler = this.channelzEnabled ? this._channelzSessionHandler(http2Server) : this._sessionHandler(http2Server);
          http2Server.on("stream", handler.bind(this, extraInterceptors));
          http2Server.on("session", sessionHandler);
        }
        _sessionHandler(http2Server) {
          return (session) => {
            var _b, _c;
            (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session);
            let connectionAgeTimer = null;
            let connectionAgeGraceTimer = null;
            let keepaliveTimer = null;
            let sessionClosedByServer = false;
            const idleTimeoutObj = this.enableIdleTimeout(session);
            if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) {
              const jitterMagnitude = this.maxConnectionAgeMs / 10;
              const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude;
              connectionAgeTimer = setTimeout(() => {
                var _b2, _c2;
                sessionClosedByServer = true;
                this.trace("Connection dropped by max connection age: " + ((_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress));
                try {
                  session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge);
                } catch (e) {
                  session.destroy();
                  return;
                }
                session.close();
                if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) {
                  connectionAgeGraceTimer = setTimeout(() => {
                    session.destroy();
                  }, this.maxConnectionAgeGraceMs);
                  (_c2 = connectionAgeGraceTimer.unref) === null || _c2 === void 0 ? void 0 : _c2.call(connectionAgeGraceTimer);
                }
              }, this.maxConnectionAgeMs + jitter);
              (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer);
            }
            const clearKeepaliveTimeout = /* @__PURE__ */ __name(() => {
              if (keepaliveTimer) {
                clearTimeout(keepaliveTimer);
                keepaliveTimer = null;
              }
            }, "clearKeepaliveTimeout");
            const canSendPing = /* @__PURE__ */ __name(() => {
              return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0;
            }, "canSendPing");
            let sendPing;
            const maybeStartKeepalivePingTimer = /* @__PURE__ */ __name(() => {
              var _b2;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
              keepaliveTimer = setTimeout(() => {
                clearKeepaliveTimeout();
                sendPing();
              }, this.keepaliveTimeMs);
              (_b2 = keepaliveTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimer);
            }, "maybeStartKeepalivePingTimer");
            sendPing = /* @__PURE__ */ __name(() => {
              var _b2;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
              let pingSendError = "";
              try {
                const pingSentSuccessfully = session.ping((err, duration, payload) => {
                  clearKeepaliveTimeout();
                  if (err) {
                    this.keepaliveTrace("Ping failed with error: " + err.message);
                    sessionClosedByServer = true;
                    session.destroy();
                  } else {
                    this.keepaliveTrace("Received ping response");
                    maybeStartKeepalivePingTimer();
                  }
                });
                if (!pingSentSuccessfully) {
                  pingSendError = "Ping returned false";
                }
              } catch (e) {
                pingSendError = (e instanceof Error ? e.message : "") || "Unknown error";
              }
              if (pingSendError) {
                this.keepaliveTrace("Ping send failed: " + pingSendError);
                this.trace("Connection dropped due to ping send error: " + pingSendError);
                sessionClosedByServer = true;
                session.destroy();
                return;
              }
              keepaliveTimer = setTimeout(() => {
                clearKeepaliveTimeout();
                this.keepaliveTrace("Ping timeout passed without response");
                this.trace("Connection dropped by keepalive timeout");
                sessionClosedByServer = true;
                session.destroy();
              }, this.keepaliveTimeoutMs);
              (_b2 = keepaliveTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimer);
            }, "sendPing");
            maybeStartKeepalivePingTimer();
            session.on("close", () => {
              var _b2, _c2;
              if (!sessionClosedByServer) {
                this.trace(`Connection dropped by client ${(_b2 = session.socket) === null || _b2 === void 0 ? void 0 : _b2.remoteAddress}`);
              }
              if (connectionAgeTimer) {
                clearTimeout(connectionAgeTimer);
              }
              if (connectionAgeGraceTimer) {
                clearTimeout(connectionAgeGraceTimer);
              }
              clearKeepaliveTimeout();
              if (idleTimeoutObj !== null) {
                clearTimeout(idleTimeoutObj.timeout);
                this.sessionIdleTimeouts.delete(session);
              }
              (_c2 = this.http2Servers.get(http2Server)) === null || _c2 === void 0 ? void 0 : _c2.sessions.delete(session);
            });
          };
        }
        _channelzSessionHandler(http2Server) {
          return (session) => {
            var _b, _c, _d, _e;
            const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : "unknown", this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled);
            const channelzSessionInfo = {
              ref: channelzRef,
              streamTracker: new channelz_1.ChannelzCallTracker(),
              messagesSent: 0,
              messagesReceived: 0,
              keepAlivesSent: 0,
              lastMessageSentTimestamp: null,
              lastMessageReceivedTimestamp: null
            };
            (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session);
            this.sessions.set(session, channelzSessionInfo);
            const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`;
            this.channelzTrace.addTrace("CT_INFO", "Connection established by client " + clientAddress);
            this.trace("Connection established by client " + clientAddress);
            this.sessionChildrenTracker.refChild(channelzRef);
            let connectionAgeTimer = null;
            let connectionAgeGraceTimer = null;
            let keepaliveTimeout = null;
            let sessionClosedByServer = false;
            const idleTimeoutObj = this.enableIdleTimeout(session);
            if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) {
              const jitterMagnitude = this.maxConnectionAgeMs / 10;
              const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude;
              connectionAgeTimer = setTimeout(() => {
                var _b2;
                sessionClosedByServer = true;
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped by max connection age from " + clientAddress);
                try {
                  session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge);
                } catch (e) {
                  session.destroy();
                  return;
                }
                session.close();
                if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) {
                  connectionAgeGraceTimer = setTimeout(() => {
                    session.destroy();
                  }, this.maxConnectionAgeGraceMs);
                  (_b2 = connectionAgeGraceTimer.unref) === null || _b2 === void 0 ? void 0 : _b2.call(connectionAgeGraceTimer);
                }
              }, this.maxConnectionAgeMs + jitter);
              (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer);
            }
            const clearKeepaliveTimeout = /* @__PURE__ */ __name(() => {
              if (keepaliveTimeout) {
                clearTimeout(keepaliveTimeout);
                keepaliveTimeout = null;
              }
            }, "clearKeepaliveTimeout");
            const canSendPing = /* @__PURE__ */ __name(() => {
              return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0;
            }, "canSendPing");
            let sendPing;
            const maybeStartKeepalivePingTimer = /* @__PURE__ */ __name(() => {
              var _b2;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
              keepaliveTimeout = setTimeout(() => {
                clearKeepaliveTimeout();
                sendPing();
              }, this.keepaliveTimeMs);
              (_b2 = keepaliveTimeout.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimeout);
            }, "maybeStartKeepalivePingTimer");
            sendPing = /* @__PURE__ */ __name(() => {
              var _b2;
              if (!canSendPing()) {
                return;
              }
              this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
              let pingSendError = "";
              try {
                const pingSentSuccessfully = session.ping((err, duration, payload) => {
                  clearKeepaliveTimeout();
                  if (err) {
                    this.keepaliveTrace("Ping failed with error: " + err.message);
                    this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to error of a ping frame " + err.message + " return in " + duration);
                    sessionClosedByServer = true;
                    session.destroy();
                  } else {
                    this.keepaliveTrace("Received ping response");
                    maybeStartKeepalivePingTimer();
                  }
                });
                if (!pingSentSuccessfully) {
                  pingSendError = "Ping returned false";
                }
              } catch (e) {
                pingSendError = (e instanceof Error ? e.message : "") || "Unknown error";
              }
              if (pingSendError) {
                this.keepaliveTrace("Ping send failed: " + pingSendError);
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to ping send error: " + pingSendError);
                sessionClosedByServer = true;
                session.destroy();
                return;
              }
              channelzSessionInfo.keepAlivesSent += 1;
              keepaliveTimeout = setTimeout(() => {
                clearKeepaliveTimeout();
                this.keepaliveTrace("Ping timeout passed without response");
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped by keepalive timeout from " + clientAddress);
                sessionClosedByServer = true;
                session.destroy();
              }, this.keepaliveTimeoutMs);
              (_b2 = keepaliveTimeout.unref) === null || _b2 === void 0 ? void 0 : _b2.call(keepaliveTimeout);
            }, "sendPing");
            maybeStartKeepalivePingTimer();
            session.on("close", () => {
              var _b2;
              if (!sessionClosedByServer) {
                this.channelzTrace.addTrace("CT_INFO", "Connection dropped by client " + clientAddress);
              }
              this.sessionChildrenTracker.unrefChild(channelzRef);
              (0, channelz_1.unregisterChannelzRef)(channelzRef);
              if (connectionAgeTimer) {
                clearTimeout(connectionAgeTimer);
              }
              if (connectionAgeGraceTimer) {
                clearTimeout(connectionAgeGraceTimer);
              }
              clearKeepaliveTimeout();
              if (idleTimeoutObj !== null) {
                clearTimeout(idleTimeoutObj.timeout);
                this.sessionIdleTimeouts.delete(session);
              }
              (_b2 = this.http2Servers.get(http2Server)) === null || _b2 === void 0 ? void 0 : _b2.sessions.delete(session);
              this.sessions.delete(session);
            });
          };
        }
        enableIdleTimeout(session) {
          var _b, _c;
          if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) {
            return null;
          }
          const idleTimeoutObj = {
            activeStreams: 0,
            lastIdle: Date.now(),
            onClose: this.onStreamClose.bind(this, session),
            timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session)
          };
          (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b);
          this.sessionIdleTimeouts.set(session, idleTimeoutObj);
          const { socket } = session;
          this.trace("Enable idle timeout for " + socket.remoteAddress + ":" + socket.remotePort);
          return idleTimeoutObj;
        }
        onIdleTimeout(ctx, session) {
          const { socket } = session;
          const sessionInfo = ctx.sessionIdleTimeouts.get(session);
          if (sessionInfo !== void 0 && sessionInfo.activeStreams === 0) {
            if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) {
              ctx.trace("Session idle timeout triggered for " + (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + ":" + (socket === null || socket === void 0 ? void 0 : socket.remotePort) + " last idle at " + sessionInfo.lastIdle);
              ctx.closeSession(session);
            } else {
              sessionInfo.timeout.refresh();
            }
          }
        }
        onStreamOpened(stream) {
          const session = stream.session;
          const idleTimeoutObj = this.sessionIdleTimeouts.get(session);
          if (idleTimeoutObj) {
            idleTimeoutObj.activeStreams += 1;
            stream.once("close", idleTimeoutObj.onClose);
          }
        }
        onStreamClose(session) {
          var _b, _c;
          const idleTimeoutObj = this.sessionIdleTimeouts.get(session);
          if (idleTimeoutObj) {
            idleTimeoutObj.activeStreams -= 1;
            if (idleTimeoutObj.activeStreams === 0) {
              idleTimeoutObj.lastIdle = Date.now();
              idleTimeoutObj.timeout.refresh();
              this.trace("Session onStreamClose" + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + ":" + ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + " at " + idleTimeoutObj.lastIdle);
            }
          }
        }
      }, (() => {
        const _metadata = typeof Symbol === "function" && Symbol.metadata ? /* @__PURE__ */ Object.create(null) : void 0;
        _start_decorators = [deprecate("Calling start() is no longer necessary. It can be safely omitted.")];
        __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "start" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.start, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
        if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      })(), _a;
    })();
    exports.Server = Server;
    async function handleUnary(call, handler) {
      let stream;
      function respond(err, value, trailer, flags) {
        if (err) {
          call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer));
          return;
        }
        call.sendMessage(value, () => {
          call.sendStatus({
            code: constants_1.Status.OK,
            details: "OK",
            metadata: trailer !== null && trailer !== void 0 ? trailer : null
          });
        });
      }
      __name(respond, "respond");
      let requestMetadata;
      let requestMessage = null;
      call.start({
        onReceiveMetadata(metadata) {
          requestMetadata = metadata;
          call.startRead();
        },
        onReceiveMessage(message) {
          if (requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received a second request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          requestMessage = message;
          call.startRead();
        },
        onReceiveHalfClose() {
          if (!requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received no request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage);
          try {
            handler.func(stream, respond);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onCancel() {
          if (stream) {
            stream.cancelled = true;
            stream.emit("cancelled", "cancelled");
          }
        }
      });
    }
    __name(handleUnary, "handleUnary");
    function handleClientStreaming(call, handler) {
      let stream;
      function respond(err, value, trailer, flags) {
        if (err) {
          call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer));
          return;
        }
        call.sendMessage(value, () => {
          call.sendStatus({
            code: constants_1.Status.OK,
            details: "OK",
            metadata: trailer !== null && trailer !== void 0 ? trailer : null
          });
        });
      }
      __name(respond, "respond");
      call.start({
        onReceiveMetadata(metadata) {
          stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata);
          try {
            handler.func(stream, respond);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onReceiveMessage(message) {
          stream.push(message);
        },
        onReceiveHalfClose() {
          stream.push(null);
        },
        onCancel() {
          if (stream) {
            stream.cancelled = true;
            stream.emit("cancelled", "cancelled");
            stream.destroy();
          }
        }
      });
    }
    __name(handleClientStreaming, "handleClientStreaming");
    function handleServerStreaming(call, handler) {
      let stream;
      let requestMetadata;
      let requestMessage = null;
      call.start({
        onReceiveMetadata(metadata) {
          requestMetadata = metadata;
          call.startRead();
        },
        onReceiveMessage(message) {
          if (requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received a second request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          requestMessage = message;
          call.startRead();
        },
        onReceiveHalfClose() {
          if (!requestMessage) {
            call.sendStatus({
              code: constants_1.Status.UNIMPLEMENTED,
              details: `Received no request message for server streaming method ${handler.path}`,
              metadata: null
            });
            return;
          }
          stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage);
          try {
            handler.func(stream);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onCancel() {
          if (stream) {
            stream.cancelled = true;
            stream.emit("cancelled", "cancelled");
            stream.destroy();
          }
        }
      });
    }
    __name(handleServerStreaming, "handleServerStreaming");
    function handleBidiStreaming(call, handler) {
      let stream;
      call.start({
        onReceiveMetadata(metadata) {
          stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata);
          try {
            handler.func(stream);
          } catch (err) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err.message}`,
              metadata: null
            });
          }
        },
        onReceiveMessage(message) {
          stream.push(message);
        },
        onReceiveHalfClose() {
          stream.push(null);
        },
        onCancel() {
          if (stream) {
            stream.cancelled = true;
            stream.emit("cancelled", "cancelled");
            stream.destroy();
          }
        }
      });
    }
    __name(handleBidiStreaming, "handleBidiStreaming");
  }
});

// node_modules/@grpc/grpc-js/build/src/status-builder.js
var require_status_builder = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/status-builder.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StatusBuilder = void 0;
    var StatusBuilder = class {
      static {
        __name(this, "StatusBuilder");
      }
      constructor() {
        this.code = null;
        this.details = null;
        this.metadata = null;
      }
      /**
       * Adds a status code to the builder.
       */
      withCode(code) {
        this.code = code;
        return this;
      }
      /**
       * Adds details to the builder.
       */
      withDetails(details) {
        this.details = details;
        return this;
      }
      /**
       * Adds metadata to the builder.
       */
      withMetadata(metadata) {
        this.metadata = metadata;
        return this;
      }
      /**
       * Builds the status object.
       */
      build() {
        const status = {};
        if (this.code !== null) {
          status.code = this.code;
        }
        if (this.details !== null) {
          status.details = this.details;
        }
        if (this.metadata !== null) {
          status.metadata = this.metadata;
        }
        return status;
      }
    };
    exports.StatusBuilder = StatusBuilder;
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js
var require_load_balancer_pick_first = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LeafLoadBalancer = exports.PickFirstLoadBalancer = exports.PickFirstLoadBalancingConfig = void 0;
    exports.shuffled = shuffled;
    exports.setup = setup;
    var load_balancer_1 = require_load_balancer();
    var connectivity_state_1 = require_connectivity_state();
    var picker_1 = require_picker();
    var subchannel_address_1 = require_subchannel_address();
    var logging = require_logging();
    var constants_1 = require_constants2();
    var subchannel_address_2 = require_subchannel_address();
    var net_1 = __require("net");
    var call_interface_1 = require_call_interface();
    var TRACER_NAME = "pick_first";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var TYPE_NAME = "pick_first";
    var CONNECTION_DELAY_INTERVAL_MS = 250;
    var PickFirstLoadBalancingConfig = class _PickFirstLoadBalancingConfig {
      static {
        __name(this, "PickFirstLoadBalancingConfig");
      }
      constructor(shuffleAddressList) {
        this.shuffleAddressList = shuffleAddressList;
      }
      getLoadBalancerName() {
        return TYPE_NAME;
      }
      toJsonObject() {
        return {
          [TYPE_NAME]: {
            shuffleAddressList: this.shuffleAddressList
          }
        };
      }
      getShuffleAddressList() {
        return this.shuffleAddressList;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static createFromJson(obj) {
        if ("shuffleAddressList" in obj && !(typeof obj.shuffleAddressList === "boolean")) {
          throw new Error("pick_first config field shuffleAddressList must be a boolean if provided");
        }
        return new _PickFirstLoadBalancingConfig(obj.shuffleAddressList === true);
      }
    };
    exports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig;
    var PickFirstPicker = class {
      static {
        __name(this, "PickFirstPicker");
      }
      constructor(subchannel) {
        this.subchannel = subchannel;
      }
      pick(pickArgs) {
        return {
          pickResultType: picker_1.PickResultType.COMPLETE,
          subchannel: this.subchannel,
          status: null,
          onCallStarted: null,
          onCallEnded: null
        };
      }
    };
    function shuffled(list) {
      const result = list.slice();
      for (let i = result.length - 1; i > 1; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = result[i];
        result[i] = result[j];
        result[j] = temp;
      }
      return result;
    }
    __name(shuffled, "shuffled");
    function interleaveAddressFamilies(addressList) {
      if (addressList.length === 0) {
        return [];
      }
      const result = [];
      const ipv6Addresses = [];
      const ipv4Addresses = [];
      const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host);
      for (const address of addressList) {
        if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) {
          ipv6Addresses.push(address);
        } else {
          ipv4Addresses.push(address);
        }
      }
      const firstList = ipv6First ? ipv6Addresses : ipv4Addresses;
      const secondList = ipv6First ? ipv4Addresses : ipv6Addresses;
      for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) {
        if (i < firstList.length) {
          result.push(firstList[i]);
        }
        if (i < secondList.length) {
          result.push(secondList[i]);
        }
      }
      return result;
    }
    __name(interleaveAddressFamilies, "interleaveAddressFamilies");
    var REPORT_HEALTH_STATUS_OPTION_NAME = "grpc-node.internal.pick-first.report_health_status";
    var PickFirstLoadBalancer = class {
      static {
        __name(this, "PickFirstLoadBalancer");
      }
      /**
       * Load balancer that attempts to connect to each backend in the address list
       * in order, and picks the first one that connects, using it for every
       * request.
       * @param channelControlHelper `ChannelControlHelper` instance provided by
       *     this load balancer's owner.
       */
      constructor(channelControlHelper) {
        this.channelControlHelper = channelControlHelper;
        this.children = [];
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.currentSubchannelIndex = 0;
        this.currentPick = null;
        this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage2) => {
          this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage2);
        };
        this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState();
        this.stickyTransientFailureMode = false;
        this.reportHealthStatus = false;
        this.lastError = null;
        this.latestAddressList = null;
        this.latestOptions = {};
        this.latestResolutionNote = "";
        this.connectionDelayTimeout = setTimeout(() => {
        }, 0);
        clearTimeout(this.connectionDelayTimeout);
      }
      allChildrenHaveReportedTF() {
        return this.children.every((child) => child.hasReportedTransientFailure);
      }
      resetChildrenReportedTF() {
        this.children.every((child) => child.hasReportedTransientFailure = false);
      }
      calculateAndReportNewState() {
        var _a;
        if (this.currentPick) {
          if (this.reportHealthStatus && !this.currentPick.isHealthy()) {
            const errorMessage2 = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;
            this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
              details: errorMessage2
            }), errorMessage2);
          } else {
            this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null);
          }
        } else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) {
          const errorMessage2 = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
            details: errorMessage2
          }), errorMessage2);
        } else if (this.children.length === 0) {
          this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
        } else {
          if (this.stickyTransientFailureMode) {
            const errorMessage2 = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;
            this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
              details: errorMessage2
            }), errorMessage2);
          } else {
            this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null);
          }
        }
      }
      requestReresolution() {
        this.channelControlHelper.requestReresolution();
      }
      maybeEnterStickyTransientFailureMode() {
        if (!this.allChildrenHaveReportedTF()) {
          return;
        }
        this.requestReresolution();
        this.resetChildrenReportedTF();
        if (this.stickyTransientFailureMode) {
          this.calculateAndReportNewState();
          return;
        }
        this.stickyTransientFailureMode = true;
        for (const { subchannel } of this.children) {
          subchannel.startConnecting();
        }
        this.calculateAndReportNewState();
      }
      removeCurrentPick() {
        if (this.currentPick !== null) {
          this.currentPick.removeConnectivityStateListener(this.subchannelStateListener);
          this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef());
          this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener);
          this.currentPick.unref();
          this.currentPick = null;
        }
      }
      onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage2) {
        var _a;
        if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) {
          if (newState !== connectivity_state_1.ConnectivityState.READY) {
            this.removeCurrentPick();
            this.calculateAndReportNewState();
          }
          return;
        }
        for (const [index, child] of this.children.entries()) {
          if (subchannel.realSubchannelEquals(child.subchannel)) {
            if (newState === connectivity_state_1.ConnectivityState.READY) {
              this.pickSubchannel(child.subchannel);
            }
            if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
              child.hasReportedTransientFailure = true;
              if (errorMessage2) {
                this.lastError = errorMessage2;
              }
              this.maybeEnterStickyTransientFailureMode();
              if (index === this.currentSubchannelIndex) {
                this.startNextSubchannelConnecting(index + 1);
              }
            }
            child.subchannel.startConnecting();
            return;
          }
        }
      }
      startNextSubchannelConnecting(startIndex) {
        clearTimeout(this.connectionDelayTimeout);
        for (const [index, child] of this.children.entries()) {
          if (index >= startIndex) {
            const subchannelState = child.subchannel.getConnectivityState();
            if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) {
              this.startConnecting(index);
              return;
            }
          }
        }
        this.maybeEnterStickyTransientFailureMode();
      }
      /**
       * Have a single subchannel in the `subchannels` list start connecting.
       * @param subchannelIndex The index into the `subchannels` list.
       */
      startConnecting(subchannelIndex) {
        var _a, _b;
        clearTimeout(this.connectionDelayTimeout);
        this.currentSubchannelIndex = subchannelIndex;
        if (this.children[subchannelIndex].subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) {
          trace2("Start connecting to subchannel with address " + this.children[subchannelIndex].subchannel.getAddress());
          process.nextTick(() => {
            var _a2;
            (_a2 = this.children[subchannelIndex]) === null || _a2 === void 0 ? void 0 : _a2.subchannel.startConnecting();
          });
        }
        this.connectionDelayTimeout = setTimeout(() => {
          this.startNextSubchannelConnecting(subchannelIndex + 1);
        }, CONNECTION_DELAY_INTERVAL_MS);
        (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
      }
      /**
       * Declare that the specified subchannel should be used to make requests.
       * This functions the same independent of whether subchannel is a member of
       * this.children and whether it is equal to this.currentPick.
       * Prerequisite: subchannel.getConnectivityState() === READY.
       * @param subchannel
       */
      pickSubchannel(subchannel) {
        trace2("Pick subchannel with address " + subchannel.getAddress());
        this.stickyTransientFailureMode = false;
        subchannel.ref();
        this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef());
        this.removeCurrentPick();
        this.resetSubchannelList();
        subchannel.addConnectivityStateListener(this.subchannelStateListener);
        subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener);
        this.currentPick = subchannel;
        clearTimeout(this.connectionDelayTimeout);
        this.calculateAndReportNewState();
      }
      updateState(newState, picker, errorMessage2) {
        trace2(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        this.currentState = newState;
        this.channelControlHelper.updateState(newState, picker, errorMessage2);
      }
      resetSubchannelList() {
        for (const child of this.children) {
          child.subchannel.removeConnectivityStateListener(this.subchannelStateListener);
          child.subchannel.unref();
          this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef());
        }
        this.currentSubchannelIndex = 0;
        this.children = [];
      }
      connectToAddressList(addressList, options) {
        trace2("connectToAddressList([" + addressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])");
        const newChildrenList = addressList.map((address) => ({
          subchannel: this.channelControlHelper.createSubchannel(address, options),
          hasReportedTransientFailure: false
        }));
        for (const { subchannel } of newChildrenList) {
          if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) {
            this.pickSubchannel(subchannel);
            return;
          }
        }
        for (const { subchannel } of newChildrenList) {
          subchannel.ref();
          this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef());
        }
        this.resetSubchannelList();
        this.children = newChildrenList;
        for (const { subchannel } of this.children) {
          subchannel.addConnectivityStateListener(this.subchannelStateListener);
        }
        for (const child of this.children) {
          if (child.subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
            child.hasReportedTransientFailure = true;
          }
        }
        this.startNextSubchannelConnecting(0);
        this.calculateAndReportNewState();
      }
      updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) {
        if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) {
          return false;
        }
        if (!maybeEndpointList.ok) {
          if (this.children.length === 0 && this.currentPick === null) {
            this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details);
          }
          return true;
        }
        let endpointList = maybeEndpointList.value;
        this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME];
        if (lbConfig.getShuffleAddressList()) {
          endpointList = shuffled(endpointList);
        }
        const rawAddressList = [].concat(...endpointList.map((endpoint) => endpoint.addresses));
        trace2("updateAddressList([" + rawAddressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])");
        const addressList = interleaveAddressFamilies(rawAddressList);
        this.latestAddressList = addressList;
        this.latestOptions = options;
        this.connectToAddressList(addressList, options);
        this.latestResolutionNote = resolutionNote;
        if (rawAddressList.length > 0) {
          return true;
        } else {
          this.lastError = "No addresses resolved";
          return false;
        }
      }
      exitIdle() {
        if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && this.latestAddressList) {
          this.connectToAddressList(this.latestAddressList, this.latestOptions);
        }
      }
      resetBackoff() {
      }
      destroy() {
        this.resetSubchannelList();
        this.removeCurrentPick();
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports.PickFirstLoadBalancer = PickFirstLoadBalancer;
    var LEAF_CONFIG = new PickFirstLoadBalancingConfig(false);
    var LeafLoadBalancer = class {
      static {
        __name(this, "LeafLoadBalancer");
      }
      constructor(endpoint, channelControlHelper, options, resolutionNote) {
        this.endpoint = endpoint;
        this.options = options;
        this.resolutionNote = resolutionNote;
        this.latestState = connectivity_state_1.ConnectivityState.IDLE;
        const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, {
          updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage2) => {
            this.latestState = connectivityState;
            this.latestPicker = picker;
            channelControlHelper.updateState(connectivityState, picker, errorMessage2);
          }, "updateState")
        });
        this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper);
        this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer);
      }
      startConnecting() {
        this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote);
      }
      /**
       * Update the endpoint associated with this LeafLoadBalancer to a new
       * endpoint. Does not trigger connection establishment if a connection
       * attempt is not already in progress.
       * @param newEndpoint
       */
      updateEndpoint(newEndpoint, newOptions) {
        this.options = newOptions;
        this.endpoint = newEndpoint;
        if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) {
          this.startConnecting();
        }
      }
      getConnectivityState() {
        return this.latestState;
      }
      getPicker() {
        return this.latestPicker;
      }
      getEndpoint() {
        return this.endpoint;
      }
      exitIdle() {
        this.pickFirstBalancer.exitIdle();
      }
      destroy() {
        this.pickFirstBalancer.destroy();
      }
    };
    exports.LeafLoadBalancer = LeafLoadBalancer;
    function setup() {
      (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig);
      (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/certificate-provider.js
var require_certificate_provider = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/certificate-provider.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FileWatcherCertificateProvider = void 0;
    var fs9 = __require("fs");
    var logging = require_logging();
    var constants_1 = require_constants2();
    var util_1 = __require("util");
    var TRACER_NAME = "certificate_provider";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var readFilePromise = (0, util_1.promisify)(fs9.readFile);
    var FileWatcherCertificateProvider = class {
      static {
        __name(this, "FileWatcherCertificateProvider");
      }
      constructor(config) {
        this.config = config;
        this.refreshTimer = null;
        this.fileResultPromise = null;
        this.latestCaUpdate = void 0;
        this.caListeners = /* @__PURE__ */ new Set();
        this.latestIdentityUpdate = void 0;
        this.identityListeners = /* @__PURE__ */ new Set();
        this.lastUpdateTime = null;
        if (config.certificateFile === void 0 !== (config.privateKeyFile === void 0)) {
          throw new Error("certificateFile and privateKeyFile must be set or unset together");
        }
        if (config.certificateFile === void 0 && config.caCertificateFile === void 0) {
          throw new Error("At least one of certificateFile and caCertificateFile must be set");
        }
        trace2("File watcher constructed with config " + JSON.stringify(config));
      }
      updateCertificates() {
        if (this.fileResultPromise) {
          return;
        }
        this.fileResultPromise = Promise.allSettled([
          this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(),
          this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(),
          this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject()
        ]);
        this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => {
          if (!this.refreshTimer) {
            return;
          }
          trace2("File watcher read certificates certificate " + certificateResult.status + ", privateKey " + privateKeyResult.status + ", CA certificate " + caCertificateResult.status);
          this.lastUpdateTime = /* @__PURE__ */ new Date();
          this.fileResultPromise = null;
          if (certificateResult.status === "fulfilled" && privateKeyResult.status === "fulfilled") {
            this.latestIdentityUpdate = {
              certificate: certificateResult.value,
              privateKey: privateKeyResult.value
            };
          } else {
            this.latestIdentityUpdate = null;
          }
          if (caCertificateResult.status === "fulfilled") {
            this.latestCaUpdate = {
              caCertificate: caCertificateResult.value
            };
          } else {
            this.latestCaUpdate = null;
          }
          for (const listener of this.identityListeners) {
            listener(this.latestIdentityUpdate);
          }
          for (const listener of this.caListeners) {
            listener(this.latestCaUpdate);
          }
        });
        trace2("File watcher initiated certificate update");
      }
      maybeStartWatchingFiles() {
        if (!this.refreshTimer) {
          const timeSinceLastUpdate = this.lastUpdateTime ? (/* @__PURE__ */ new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity;
          if (timeSinceLastUpdate > this.config.refreshIntervalMs) {
            this.updateCertificates();
          }
          if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) {
            this.latestCaUpdate = void 0;
            this.latestIdentityUpdate = void 0;
          }
          this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs);
          trace2("File watcher started watching");
        }
      }
      maybeStopWatchingFiles() {
        if (this.caListeners.size === 0 && this.identityListeners.size === 0) {
          this.fileResultPromise = null;
          if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
            this.refreshTimer = null;
          }
        }
      }
      addCaCertificateListener(listener) {
        this.caListeners.add(listener);
        this.maybeStartWatchingFiles();
        if (this.latestCaUpdate !== void 0) {
          process.nextTick(listener, this.latestCaUpdate);
        }
      }
      removeCaCertificateListener(listener) {
        this.caListeners.delete(listener);
        this.maybeStopWatchingFiles();
      }
      addIdentityCertificateListener(listener) {
        this.identityListeners.add(listener);
        this.maybeStartWatchingFiles();
        if (this.latestIdentityUpdate !== void 0) {
          process.nextTick(listener, this.latestIdentityUpdate);
        }
      }
      removeIdentityCertificateListener(listener) {
        this.identityListeners.delete(listener);
        this.maybeStopWatchingFiles();
      }
    };
    exports.FileWatcherCertificateProvider = FileWatcherCertificateProvider;
  }
});

// node_modules/@grpc/grpc-js/build/src/experimental.js
var require_experimental = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/experimental.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports.createCertificateProviderChannelCredentials = exports.FileWatcherCertificateProvider = exports.createCertificateProviderServerCredentials = exports.createServerCredentialsWithInterceptors = exports.BaseSubchannelWrapper = exports.registerAdminService = exports.FilterStackFactory = exports.BaseFilter = exports.statusOrFromError = exports.statusOrFromValue = exports.PickResultType = exports.QueuePicker = exports.UnavailablePicker = exports.ChildLoadBalancerHandler = exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.subchannelAddressToString = exports.LeafLoadBalancer = exports.isLoadBalancerNameRegistered = exports.parseLoadBalancingConfig = exports.selectLbConfigFromList = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = exports.BackoffTimeout = exports.parseDuration = exports.durationToMs = exports.splitHostPort = exports.uriToString = exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports.createResolver = exports.registerResolver = exports.log = exports.trace = void 0;
    var logging_1 = require_logging();
    Object.defineProperty(exports, "trace", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logging_1.trace;
    }, "get") });
    Object.defineProperty(exports, "log", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logging_1.log;
    }, "get") });
    var resolver_1 = require_resolver();
    Object.defineProperty(exports, "registerResolver", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return resolver_1.registerResolver;
    }, "get") });
    Object.defineProperty(exports, "createResolver", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return resolver_1.createResolver;
    }, "get") });
    Object.defineProperty(exports, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY;
    }, "get") });
    var uri_parser_1 = require_uri_parser();
    Object.defineProperty(exports, "uriToString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return uri_parser_1.uriToString;
    }, "get") });
    Object.defineProperty(exports, "splitHostPort", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return uri_parser_1.splitHostPort;
    }, "get") });
    var duration_1 = require_duration();
    Object.defineProperty(exports, "durationToMs", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return duration_1.durationToMs;
    }, "get") });
    Object.defineProperty(exports, "parseDuration", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return duration_1.parseDuration;
    }, "get") });
    var backoff_timeout_1 = require_backoff_timeout();
    Object.defineProperty(exports, "BackoffTimeout", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return backoff_timeout_1.BackoffTimeout;
    }, "get") });
    var load_balancer_1 = require_load_balancer();
    Object.defineProperty(exports, "createChildChannelControlHelper", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.createChildChannelControlHelper;
    }, "get") });
    Object.defineProperty(exports, "registerLoadBalancerType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.registerLoadBalancerType;
    }, "get") });
    Object.defineProperty(exports, "selectLbConfigFromList", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.selectLbConfigFromList;
    }, "get") });
    Object.defineProperty(exports, "parseLoadBalancingConfig", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.parseLoadBalancingConfig;
    }, "get") });
    Object.defineProperty(exports, "isLoadBalancerNameRegistered", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_1.isLoadBalancerNameRegistered;
    }, "get") });
    var load_balancer_pick_first_1 = require_load_balancer_pick_first();
    Object.defineProperty(exports, "LeafLoadBalancer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_pick_first_1.LeafLoadBalancer;
    }, "get") });
    var subchannel_address_1 = require_subchannel_address();
    Object.defineProperty(exports, "subchannelAddressToString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.subchannelAddressToString;
    }, "get") });
    Object.defineProperty(exports, "endpointToString", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.endpointToString;
    }, "get") });
    Object.defineProperty(exports, "endpointHasAddress", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.endpointHasAddress;
    }, "get") });
    Object.defineProperty(exports, "EndpointMap", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_address_1.EndpointMap;
    }, "get") });
    var load_balancer_child_handler_1 = require_load_balancer_child_handler();
    Object.defineProperty(exports, "ChildLoadBalancerHandler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return load_balancer_child_handler_1.ChildLoadBalancerHandler;
    }, "get") });
    var picker_1 = require_picker();
    Object.defineProperty(exports, "UnavailablePicker", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return picker_1.UnavailablePicker;
    }, "get") });
    Object.defineProperty(exports, "QueuePicker", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return picker_1.QueuePicker;
    }, "get") });
    Object.defineProperty(exports, "PickResultType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return picker_1.PickResultType;
    }, "get") });
    var call_interface_1 = require_call_interface();
    Object.defineProperty(exports, "statusOrFromValue", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return call_interface_1.statusOrFromValue;
    }, "get") });
    Object.defineProperty(exports, "statusOrFromError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return call_interface_1.statusOrFromError;
    }, "get") });
    var filter_1 = require_filter();
    Object.defineProperty(exports, "BaseFilter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return filter_1.BaseFilter;
    }, "get") });
    var filter_stack_1 = require_filter_stack();
    Object.defineProperty(exports, "FilterStackFactory", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return filter_stack_1.FilterStackFactory;
    }, "get") });
    var admin_1 = require_admin();
    Object.defineProperty(exports, "registerAdminService", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return admin_1.registerAdminService;
    }, "get") });
    var subchannel_interface_1 = require_subchannel_interface();
    Object.defineProperty(exports, "BaseSubchannelWrapper", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return subchannel_interface_1.BaseSubchannelWrapper;
    }, "get") });
    var server_credentials_1 = require_server_credentials();
    Object.defineProperty(exports, "createServerCredentialsWithInterceptors", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_credentials_1.createServerCredentialsWithInterceptors;
    }, "get") });
    Object.defineProperty(exports, "createCertificateProviderServerCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_credentials_1.createCertificateProviderServerCredentials;
    }, "get") });
    var certificate_provider_1 = require_certificate_provider();
    Object.defineProperty(exports, "FileWatcherCertificateProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return certificate_provider_1.FileWatcherCertificateProvider;
    }, "get") });
    var channel_credentials_1 = require_channel_credentials();
    Object.defineProperty(exports, "createCertificateProviderChannelCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channel_credentials_1.createCertificateProviderChannelCredentials;
    }, "get") });
    var internal_channel_1 = require_internal_channel();
    Object.defineProperty(exports, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX;
    }, "get") });
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver-uds.js
var require_resolver_uds = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver-uds.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.setup = setup;
    var resolver_1 = require_resolver();
    var call_interface_1 = require_call_interface();
    var UdsResolver = class {
      static {
        __name(this, "UdsResolver");
      }
      constructor(target, listener, channelOptions) {
        this.listener = listener;
        this.hasReturnedResult = false;
        this.endpoints = [];
        let path11;
        if (target.authority === "") {
          path11 = "/" + target.path;
        } else {
          path11 = target.path;
        }
        this.endpoints = [{ addresses: [{ path: path11 }] }];
      }
      updateResolution() {
        if (!this.hasReturnedResult) {
          this.hasReturnedResult = true;
          process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, "");
        }
      }
      destroy() {
        this.hasReturnedResult = false;
      }
      static getDefaultAuthority(target) {
        return "localhost";
      }
    };
    function setup() {
      (0, resolver_1.registerResolver)("unix", UdsResolver);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/resolver-ip.js
var require_resolver_ip = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/resolver-ip.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.setup = setup;
    var net_1 = __require("net");
    var call_interface_1 = require_call_interface();
    var constants_1 = require_constants2();
    var metadata_1 = require_metadata();
    var resolver_1 = require_resolver();
    var subchannel_address_1 = require_subchannel_address();
    var uri_parser_1 = require_uri_parser();
    var logging = require_logging();
    var TRACER_NAME = "ip_resolver";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var IPV4_SCHEME = "ipv4";
    var IPV6_SCHEME = "ipv6";
    var DEFAULT_PORT = 443;
    var IpResolver = class {
      static {
        __name(this, "IpResolver");
      }
      constructor(target, listener, channelOptions) {
        var _a;
        this.listener = listener;
        this.endpoints = [];
        this.error = null;
        this.hasReturnedResult = false;
        trace2("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target));
        const addresses = [];
        if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) {
          this.error = {
            code: constants_1.Status.UNAVAILABLE,
            details: `Unrecognized scheme ${target.scheme} in IP resolver`,
            metadata: new metadata_1.Metadata()
          };
          return;
        }
        const pathList = target.path.split(",");
        for (const path11 of pathList) {
          const hostPort = (0, uri_parser_1.splitHostPort)(path11);
          if (hostPort === null) {
            this.error = {
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse ${target.scheme} address ${path11}`,
              metadata: new metadata_1.Metadata()
            };
            return;
          }
          if (target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host) || target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host)) {
            this.error = {
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse ${target.scheme} address ${path11}`,
              metadata: new metadata_1.Metadata()
            };
            return;
          }
          addresses.push({
            host: hostPort.host,
            port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT
          });
        }
        this.endpoints = addresses.map((address) => ({ addresses: [address] }));
        trace2("Parsed " + target.scheme + " address list " + addresses.map(subchannel_address_1.subchannelAddressToString));
      }
      updateResolution() {
        if (!this.hasReturnedResult) {
          this.hasReturnedResult = true;
          process.nextTick(() => {
            if (this.error) {
              this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, "");
            } else {
              this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, "");
            }
          });
        }
      }
      destroy() {
        this.hasReturnedResult = false;
      }
      static getDefaultAuthority(target) {
        return target.path.split(",")[0];
      }
    };
    function setup() {
      (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver);
      (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js
var require_load_balancer_round_robin = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RoundRobinLoadBalancer = void 0;
    exports.setup = setup;
    var load_balancer_1 = require_load_balancer();
    var connectivity_state_1 = require_connectivity_state();
    var picker_1 = require_picker();
    var logging = require_logging();
    var constants_1 = require_constants2();
    var subchannel_address_1 = require_subchannel_address();
    var load_balancer_pick_first_1 = require_load_balancer_pick_first();
    var TRACER_NAME = "round_robin";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var TYPE_NAME = "round_robin";
    var RoundRobinLoadBalancingConfig = class _RoundRobinLoadBalancingConfig {
      static {
        __name(this, "RoundRobinLoadBalancingConfig");
      }
      getLoadBalancerName() {
        return TYPE_NAME;
      }
      constructor() {
      }
      toJsonObject() {
        return {
          [TYPE_NAME]: {}
        };
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static createFromJson(obj) {
        return new _RoundRobinLoadBalancingConfig();
      }
    };
    var RoundRobinPicker = class {
      static {
        __name(this, "RoundRobinPicker");
      }
      constructor(children, nextIndex = 0) {
        this.children = children;
        this.nextIndex = nextIndex;
      }
      pick(pickArgs) {
        const childPicker = this.children[this.nextIndex].picker;
        this.nextIndex = (this.nextIndex + 1) % this.children.length;
        return childPicker.pick(pickArgs);
      }
      /**
       * Check what the next subchannel returned would be. Used by the load
       * balancer implementation to preserve this part of the picker state if
       * possible when a subchannel connects or disconnects.
       */
      peekNextEndpoint() {
        return this.children[this.nextIndex].endpoint;
      }
    };
    function rotateArray(list, startIndex) {
      return [...list.slice(startIndex), ...list.slice(0, startIndex)];
    }
    __name(rotateArray, "rotateArray");
    var RoundRobinLoadBalancer = class {
      static {
        __name(this, "RoundRobinLoadBalancer");
      }
      constructor(channelControlHelper) {
        this.channelControlHelper = channelControlHelper;
        this.children = [];
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.currentReadyPicker = null;
        this.updatesPaused = false;
        this.lastError = null;
        this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, {
          updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage2) => {
            if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) {
              this.channelControlHelper.requestReresolution();
            }
            if (errorMessage2) {
              this.lastError = errorMessage2;
            }
            this.calculateAndUpdateState();
          }, "updateState")
        });
      }
      countChildrenWithState(state) {
        return this.children.filter((child) => child.getConnectivityState() === state).length;
      }
      calculateAndUpdateState() {
        if (this.updatesPaused) {
          return;
        }
        if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) {
          const readyChildren = this.children.filter((child) => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY);
          let index = 0;
          if (this.currentReadyPicker !== null) {
            const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint();
            index = readyChildren.findIndex((child) => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint));
            if (index < 0) {
              index = 0;
            }
          }
          this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map((child) => ({
            endpoint: child.getEndpoint(),
            picker: child.getPicker()
          })), index), null);
        } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) {
          this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null);
        } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) {
          const errorMessage2 = `round_robin: No connection established. Last error: ${this.lastError}`;
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
            details: errorMessage2
          }), errorMessage2);
        } else {
          this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
        }
        for (const child of this.children) {
          if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) {
            child.exitIdle();
          }
        }
      }
      updateState(newState, picker, errorMessage2) {
        trace2(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        if (newState === connectivity_state_1.ConnectivityState.READY) {
          this.currentReadyPicker = picker;
        } else {
          this.currentReadyPicker = null;
        }
        this.currentState = newState;
        this.channelControlHelper.updateState(newState, picker, errorMessage2);
      }
      resetSubchannelList() {
        for (const child of this.children) {
          child.destroy();
        }
        this.children = [];
      }
      updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) {
        if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) {
          return false;
        }
        if (!maybeEndpointList.ok) {
          if (this.children.length === 0) {
            this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details);
          }
          return true;
        }
        const startIndex = Math.random() * maybeEndpointList.value.length | 0;
        const endpointList = rotateArray(maybeEndpointList.value, startIndex);
        this.resetSubchannelList();
        if (endpointList.length === 0) {
          const errorMessage2 = `No addresses resolved. Resolution note: ${resolutionNote}`;
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage2 }), errorMessage2);
        }
        trace2("Connect to endpoint list " + endpointList.map(subchannel_address_1.endpointToString));
        this.updatesPaused = true;
        this.children = endpointList.map((endpoint) => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, options, resolutionNote));
        for (const child of this.children) {
          child.startConnecting();
        }
        this.updatesPaused = false;
        this.calculateAndUpdateState();
        return true;
      }
      exitIdle() {
      }
      resetBackoff() {
      }
      destroy() {
        this.resetSubchannelList();
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer;
    function setup() {
      (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js
var require_load_balancer_outlier_detection = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js"(exports) {
    "use strict";
    init_esbuild_shims();
    var _a;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OutlierDetectionLoadBalancer = exports.OutlierDetectionLoadBalancingConfig = void 0;
    exports.setup = setup;
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants2();
    var duration_1 = require_duration();
    var experimental_1 = require_experimental();
    var load_balancer_1 = require_load_balancer();
    var load_balancer_child_handler_1 = require_load_balancer_child_handler();
    var picker_1 = require_picker();
    var subchannel_address_1 = require_subchannel_address();
    var subchannel_interface_1 = require_subchannel_interface();
    var logging = require_logging();
    var TRACER_NAME = "outlier_detection";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var TYPE_NAME = "outlier_detection";
    var OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : "true") === "true";
    var defaultSuccessRateEjectionConfig = {
      stdev_factor: 1900,
      enforcement_percentage: 100,
      minimum_hosts: 5,
      request_volume: 100
    };
    var defaultFailurePercentageEjectionConfig = {
      threshold: 85,
      enforcement_percentage: 100,
      minimum_hosts: 5,
      request_volume: 50
    };
    function validateFieldType(obj, fieldName, expectedType, objectName) {
      if (fieldName in obj && obj[fieldName] !== void 0 && typeof obj[fieldName] !== expectedType) {
        const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName;
        throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`);
      }
    }
    __name(validateFieldType, "validateFieldType");
    function validatePositiveDuration(obj, fieldName, objectName) {
      const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName;
      if (fieldName in obj && obj[fieldName] !== void 0) {
        if (!(0, duration_1.isDuration)(obj[fieldName])) {
          throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`);
        }
        if (!(obj[fieldName].seconds >= 0 && obj[fieldName].seconds <= 315576e6 && obj[fieldName].nanos >= 0 && obj[fieldName].nanos <= 999999999)) {
          throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`);
        }
      }
    }
    __name(validatePositiveDuration, "validatePositiveDuration");
    function validatePercentage(obj, fieldName, objectName) {
      const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName;
      validateFieldType(obj, fieldName, "number", objectName);
      if (fieldName in obj && obj[fieldName] !== void 0 && !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) {
        throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`);
      }
    }
    __name(validatePercentage, "validatePercentage");
    var OutlierDetectionLoadBalancingConfig = class _OutlierDetectionLoadBalancingConfig {
      static {
        __name(this, "OutlierDetectionLoadBalancingConfig");
      }
      constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) {
        this.childPolicy = childPolicy;
        if (childPolicy.getLoadBalancerName() === "pick_first") {
          throw new Error("outlier_detection LB policy cannot have a pick_first child policy");
        }
        this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 1e4;
        this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 3e4;
        this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 3e5;
        this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10;
        this.successRateEjection = successRateEjection ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null;
        this.failurePercentageEjection = failurePercentageEjection ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null;
      }
      getLoadBalancerName() {
        return TYPE_NAME;
      }
      toJsonObject() {
        var _a2, _b;
        return {
          outlier_detection: {
            interval: (0, duration_1.msToDuration)(this.intervalMs),
            base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs),
            max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs),
            max_ejection_percent: this.maxEjectionPercent,
            success_rate_ejection: (_a2 = this.successRateEjection) !== null && _a2 !== void 0 ? _a2 : void 0,
            failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : void 0,
            child_policy: [this.childPolicy.toJsonObject()]
          }
        };
      }
      getIntervalMs() {
        return this.intervalMs;
      }
      getBaseEjectionTimeMs() {
        return this.baseEjectionTimeMs;
      }
      getMaxEjectionTimeMs() {
        return this.maxEjectionTimeMs;
      }
      getMaxEjectionPercent() {
        return this.maxEjectionPercent;
      }
      getSuccessRateEjectionConfig() {
        return this.successRateEjection;
      }
      getFailurePercentageEjectionConfig() {
        return this.failurePercentageEjection;
      }
      getChildPolicy() {
        return this.childPolicy;
      }
      static createFromJson(obj) {
        var _a2;
        validatePositiveDuration(obj, "interval");
        validatePositiveDuration(obj, "base_ejection_time");
        validatePositiveDuration(obj, "max_ejection_time");
        validatePercentage(obj, "max_ejection_percent");
        if ("success_rate_ejection" in obj && obj.success_rate_ejection !== void 0) {
          if (typeof obj.success_rate_ejection !== "object") {
            throw new Error("outlier detection config success_rate_ejection must be an object");
          }
          validateFieldType(obj.success_rate_ejection, "stdev_factor", "number", "success_rate_ejection");
          validatePercentage(obj.success_rate_ejection, "enforcement_percentage", "success_rate_ejection");
          validateFieldType(obj.success_rate_ejection, "minimum_hosts", "number", "success_rate_ejection");
          validateFieldType(obj.success_rate_ejection, "request_volume", "number", "success_rate_ejection");
        }
        if ("failure_percentage_ejection" in obj && obj.failure_percentage_ejection !== void 0) {
          if (typeof obj.failure_percentage_ejection !== "object") {
            throw new Error("outlier detection config failure_percentage_ejection must be an object");
          }
          validatePercentage(obj.failure_percentage_ejection, "threshold", "failure_percentage_ejection");
          validatePercentage(obj.failure_percentage_ejection, "enforcement_percentage", "failure_percentage_ejection");
          validateFieldType(obj.failure_percentage_ejection, "minimum_hosts", "number", "failure_percentage_ejection");
          validateFieldType(obj.failure_percentage_ejection, "request_volume", "number", "failure_percentage_ejection");
        }
        if (!("child_policy" in obj) || !Array.isArray(obj.child_policy)) {
          throw new Error("outlier detection config child_policy must be an array");
        }
        const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy);
        if (!childPolicy) {
          throw new Error("outlier detection config child_policy: no valid recognized policy found");
        }
        return new _OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a2 = obj.max_ejection_percent) !== null && _a2 !== void 0 ? _a2 : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy);
      }
    };
    exports.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig;
    var OutlierDetectionSubchannelWrapper = class extends subchannel_interface_1.BaseSubchannelWrapper {
      static {
        __name(this, "OutlierDetectionSubchannelWrapper");
      }
      constructor(childSubchannel, mapEntry) {
        super(childSubchannel);
        this.mapEntry = mapEntry;
        this.refCount = 0;
      }
      ref() {
        this.child.ref();
        this.refCount += 1;
      }
      unref() {
        this.child.unref();
        this.refCount -= 1;
        if (this.refCount <= 0) {
          if (this.mapEntry) {
            const index = this.mapEntry.subchannelWrappers.indexOf(this);
            if (index >= 0) {
              this.mapEntry.subchannelWrappers.splice(index, 1);
            }
          }
        }
      }
      eject() {
        this.setHealthy(false);
      }
      uneject() {
        this.setHealthy(true);
      }
      getMapEntry() {
        return this.mapEntry;
      }
      getWrappedSubchannel() {
        return this.child;
      }
    };
    function createEmptyBucket() {
      return {
        success: 0,
        failure: 0
      };
    }
    __name(createEmptyBucket, "createEmptyBucket");
    var CallCounter = class {
      static {
        __name(this, "CallCounter");
      }
      constructor() {
        this.activeBucket = createEmptyBucket();
        this.inactiveBucket = createEmptyBucket();
      }
      addSuccess() {
        this.activeBucket.success += 1;
      }
      addFailure() {
        this.activeBucket.failure += 1;
      }
      switchBuckets() {
        this.inactiveBucket = this.activeBucket;
        this.activeBucket = createEmptyBucket();
      }
      getLastSuccesses() {
        return this.inactiveBucket.success;
      }
      getLastFailures() {
        return this.inactiveBucket.failure;
      }
    };
    var OutlierDetectionPicker = class {
      static {
        __name(this, "OutlierDetectionPicker");
      }
      constructor(wrappedPicker, countCalls) {
        this.wrappedPicker = wrappedPicker;
        this.countCalls = countCalls;
      }
      pick(pickArgs) {
        const wrappedPick = this.wrappedPicker.pick(pickArgs);
        if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) {
          const subchannelWrapper = wrappedPick.subchannel;
          const mapEntry = subchannelWrapper.getMapEntry();
          if (mapEntry) {
            let onCallEnded = wrappedPick.onCallEnded;
            if (this.countCalls) {
              onCallEnded = /* @__PURE__ */ __name((statusCode, details, metadata) => {
                var _a2;
                if (statusCode === constants_1.Status.OK) {
                  mapEntry.counter.addSuccess();
                } else {
                  mapEntry.counter.addFailure();
                }
                (_a2 = wrappedPick.onCallEnded) === null || _a2 === void 0 ? void 0 : _a2.call(wrappedPick, statusCode, details, metadata);
              }, "onCallEnded");
            }
            return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded });
          } else {
            return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() });
          }
        } else {
          return wrappedPick;
        }
      }
    };
    var OutlierDetectionLoadBalancer = class {
      static {
        __name(this, "OutlierDetectionLoadBalancer");
      }
      constructor(channelControlHelper) {
        this.entryMap = new subchannel_address_1.EndpointMap();
        this.latestConfig = null;
        this.timerStartTime = null;
        this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, {
          createSubchannel: /* @__PURE__ */ __name((subchannelAddress, subchannelArgs) => {
            const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
            const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress);
            const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry);
            if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) {
              subchannelWrapper.eject();
            }
            mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper);
            return subchannelWrapper;
          }, "createSubchannel"),
          updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage2) => {
            if (connectivityState === connectivity_state_1.ConnectivityState.READY) {
              channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage2);
            } else {
              channelControlHelper.updateState(connectivityState, picker, errorMessage2);
            }
          }, "updateState")
        }));
        this.ejectionTimer = setInterval(() => {
        }, 0);
        clearInterval(this.ejectionTimer);
      }
      isCountingEnabled() {
        return this.latestConfig !== null && (this.latestConfig.getSuccessRateEjectionConfig() !== null || this.latestConfig.getFailurePercentageEjectionConfig() !== null);
      }
      getCurrentEjectionPercent() {
        let ejectionCount = 0;
        for (const mapEntry of this.entryMap.values()) {
          if (mapEntry.currentEjectionTimestamp !== null) {
            ejectionCount += 1;
          }
        }
        return ejectionCount * 100 / this.entryMap.size;
      }
      runSuccessRateCheck(ejectionTimestamp) {
        if (!this.latestConfig) {
          return;
        }
        const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig();
        if (!successRateConfig) {
          return;
        }
        trace2("Running success rate check");
        const targetRequestVolume = successRateConfig.request_volume;
        let addresesWithTargetVolume = 0;
        const successRates = [];
        for (const [endpoint, mapEntry] of this.entryMap.entries()) {
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          trace2("Stats for " + (0, subchannel_address_1.endpointToString)(endpoint) + ": successes=" + successes + " failures=" + failures + " targetRequestVolume=" + targetRequestVolume);
          if (successes + failures >= targetRequestVolume) {
            addresesWithTargetVolume += 1;
            successRates.push(successes / (successes + failures));
          }
        }
        trace2("Found " + addresesWithTargetVolume + " success rate candidates; currentEjectionPercent=" + this.getCurrentEjectionPercent() + " successRates=[" + successRates + "]");
        if (addresesWithTargetVolume < successRateConfig.minimum_hosts) {
          return;
        }
        const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length;
        let successRateDeviationSum = 0;
        for (const rate of successRates) {
          const deviation = rate - successRateMean;
          successRateDeviationSum += deviation * deviation;
        }
        const successRateVariance = successRateDeviationSum / successRates.length;
        const successRateStdev = Math.sqrt(successRateVariance);
        const ejectionThreshold = successRateMean - successRateStdev * (successRateConfig.stdev_factor / 1e3);
        trace2("stdev=" + successRateStdev + " ejectionThreshold=" + ejectionThreshold);
        for (const [address, mapEntry] of this.entryMap.entries()) {
          if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) {
            break;
          }
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          if (successes + failures < targetRequestVolume) {
            continue;
          }
          const successRate = successes / (successes + failures);
          trace2("Checking candidate " + address + " successRate=" + successRate);
          if (successRate < ejectionThreshold) {
            const randomNumber = Math.random() * 100;
            trace2("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + successRateConfig.enforcement_percentage);
            if (randomNumber < successRateConfig.enforcement_percentage) {
              trace2("Ejecting candidate " + address);
              this.eject(mapEntry, ejectionTimestamp);
            }
          }
        }
      }
      runFailurePercentageCheck(ejectionTimestamp) {
        if (!this.latestConfig) {
          return;
        }
        const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig();
        if (!failurePercentageConfig) {
          return;
        }
        trace2("Running failure percentage check. threshold=" + failurePercentageConfig.threshold + " request volume threshold=" + failurePercentageConfig.request_volume);
        let addressesWithTargetVolume = 0;
        for (const mapEntry of this.entryMap.values()) {
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          if (successes + failures >= failurePercentageConfig.request_volume) {
            addressesWithTargetVolume += 1;
          }
        }
        if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) {
          return;
        }
        for (const [address, mapEntry] of this.entryMap.entries()) {
          if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) {
            break;
          }
          const successes = mapEntry.counter.getLastSuccesses();
          const failures = mapEntry.counter.getLastFailures();
          trace2("Candidate successes=" + successes + " failures=" + failures);
          if (successes + failures < failurePercentageConfig.request_volume) {
            continue;
          }
          const failurePercentage = failures * 100 / (failures + successes);
          if (failurePercentage > failurePercentageConfig.threshold) {
            const randomNumber = Math.random() * 100;
            trace2("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + failurePercentageConfig.enforcement_percentage);
            if (randomNumber < failurePercentageConfig.enforcement_percentage) {
              trace2("Ejecting candidate " + address);
              this.eject(mapEntry, ejectionTimestamp);
            }
          }
        }
      }
      eject(mapEntry, ejectionTimestamp) {
        mapEntry.currentEjectionTimestamp = /* @__PURE__ */ new Date();
        mapEntry.ejectionTimeMultiplier += 1;
        for (const subchannelWrapper of mapEntry.subchannelWrappers) {
          subchannelWrapper.eject();
        }
      }
      uneject(mapEntry) {
        mapEntry.currentEjectionTimestamp = null;
        for (const subchannelWrapper of mapEntry.subchannelWrappers) {
          subchannelWrapper.uneject();
        }
      }
      switchAllBuckets() {
        for (const mapEntry of this.entryMap.values()) {
          mapEntry.counter.switchBuckets();
        }
      }
      startTimer(delayMs) {
        var _a2, _b;
        this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs);
        (_b = (_a2 = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a2);
      }
      runChecks() {
        const ejectionTimestamp = /* @__PURE__ */ new Date();
        trace2("Ejection timer running");
        this.switchAllBuckets();
        if (!this.latestConfig) {
          return;
        }
        this.timerStartTime = ejectionTimestamp;
        this.startTimer(this.latestConfig.getIntervalMs());
        this.runSuccessRateCheck(ejectionTimestamp);
        this.runFailurePercentageCheck(ejectionTimestamp);
        for (const [address, mapEntry] of this.entryMap.entries()) {
          if (mapEntry.currentEjectionTimestamp === null) {
            if (mapEntry.ejectionTimeMultiplier > 0) {
              mapEntry.ejectionTimeMultiplier -= 1;
            }
          } else {
            const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs();
            const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs();
            const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime());
            returnTime.setMilliseconds(returnTime.getMilliseconds() + Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs)));
            if (returnTime < /* @__PURE__ */ new Date()) {
              trace2("Unejecting " + address);
              this.uneject(mapEntry);
            }
          }
        }
      }
      updateAddressList(endpointList, lbConfig, options, resolutionNote) {
        if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) {
          return false;
        }
        trace2("Received update with config: " + JSON.stringify(lbConfig.toJsonObject(), void 0, 2));
        if (endpointList.ok) {
          for (const endpoint of endpointList.value) {
            if (!this.entryMap.has(endpoint)) {
              trace2("Adding map entry for " + (0, subchannel_address_1.endpointToString)(endpoint));
              this.entryMap.set(endpoint, {
                counter: new CallCounter(),
                currentEjectionTimestamp: null,
                ejectionTimeMultiplier: 0,
                subchannelWrappers: []
              });
            }
          }
          this.entryMap.deleteMissing(endpointList.value);
        }
        const childPolicy = lbConfig.getChildPolicy();
        this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote);
        if (lbConfig.getSuccessRateEjectionConfig() || lbConfig.getFailurePercentageEjectionConfig()) {
          if (this.timerStartTime) {
            trace2("Previous timer existed. Replacing timer");
            clearTimeout(this.ejectionTimer);
            const remainingDelay = lbConfig.getIntervalMs() - ((/* @__PURE__ */ new Date()).getTime() - this.timerStartTime.getTime());
            this.startTimer(remainingDelay);
          } else {
            trace2("Starting new timer");
            this.timerStartTime = /* @__PURE__ */ new Date();
            this.startTimer(lbConfig.getIntervalMs());
            this.switchAllBuckets();
          }
        } else {
          trace2("Counting disabled. Cancelling timer.");
          this.timerStartTime = null;
          clearTimeout(this.ejectionTimer);
          for (const mapEntry of this.entryMap.values()) {
            this.uneject(mapEntry);
            mapEntry.ejectionTimeMultiplier = 0;
          }
        }
        this.latestConfig = lbConfig;
        return true;
      }
      exitIdle() {
        this.childBalancer.exitIdle();
      }
      resetBackoff() {
        this.childBalancer.resetBackoff();
      }
      destroy() {
        clearTimeout(this.ejectionTimer);
        this.childBalancer.destroy();
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    exports.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer;
    function setup() {
      if (OUTLIER_DETECTION_ENABLED) {
        (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig);
      }
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/priority-queue.js
var require_priority_queue = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/priority-queue.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PriorityQueue = void 0;
    var top = 0;
    var parent = /* @__PURE__ */ __name((i) => Math.floor(i / 2), "parent");
    var left = /* @__PURE__ */ __name((i) => i * 2 + 1, "left");
    var right = /* @__PURE__ */ __name((i) => i * 2 + 2, "right");
    var PriorityQueue = class {
      static {
        __name(this, "PriorityQueue");
      }
      /**
       *
       * @param comparator Returns true if the first argument should precede the
       *   second in the queue. Defaults to `(a, b) => a > b`
       */
      constructor(comparator = (a, b) => a > b) {
        this.comparator = comparator;
        this.heap = [];
      }
      /**
       * @returns The number of items currently in the queue
       */
      size() {
        return this.heap.length;
      }
      /**
       * @returns True if there are no items in the queue, false otherwise
       */
      isEmpty() {
        return this.size() == 0;
      }
      /**
       * Look at the front item that would be popped, without modifying the contents
       * of the queue
       * @returns The front item in the queue, or undefined if the queue is empty
       */
      peek() {
        return this.heap[top];
      }
      /**
       * Add the items to the queue
       * @param values The items to add
       * @returns The new size of the queue after adding the items
       */
      push(...values) {
        values.forEach((value) => {
          this.heap.push(value);
          this.siftUp();
        });
        return this.size();
      }
      /**
       * Remove the front item in the queue and return it
       * @returns The front item in the queue, or undefined if the queue is empty
       */
      pop() {
        const poppedValue = this.peek();
        const bottom = this.size() - 1;
        if (bottom > top) {
          this.swap(top, bottom);
        }
        this.heap.pop();
        this.siftDown();
        return poppedValue;
      }
      /**
       * Simultaneously remove the front item in the queue and add the provided
       * item.
       * @param value The item to add
       * @returns The front item in the queue, or undefined if the queue is empty
       */
      replace(value) {
        const replacedValue = this.peek();
        this.heap[top] = value;
        this.siftDown();
        return replacedValue;
      }
      greater(i, j) {
        return this.comparator(this.heap[i], this.heap[j]);
      }
      swap(i, j) {
        [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
      }
      siftUp() {
        let node = this.size() - 1;
        while (node > top && this.greater(node, parent(node))) {
          this.swap(node, parent(node));
          node = parent(node);
        }
      }
      siftDown() {
        let node = top;
        while (left(node) < this.size() && this.greater(left(node), node) || right(node) < this.size() && this.greater(right(node), node)) {
          let maxChild = right(node) < this.size() && this.greater(right(node), left(node)) ? right(node) : left(node);
          this.swap(node, maxChild);
          node = maxChild;
        }
      }
    };
    exports.PriorityQueue = PriorityQueue;
  }
});

// node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js
var require_load_balancer_weighted_round_robin = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WeightedRoundRobinLoadBalancingConfig = void 0;
    exports.setup = setup;
    var connectivity_state_1 = require_connectivity_state();
    var constants_1 = require_constants2();
    var duration_1 = require_duration();
    var load_balancer_1 = require_load_balancer();
    var load_balancer_pick_first_1 = require_load_balancer_pick_first();
    var logging = require_logging();
    var orca_1 = require_orca();
    var picker_1 = require_picker();
    var priority_queue_1 = require_priority_queue();
    var subchannel_address_1 = require_subchannel_address();
    var TRACER_NAME = "weighted_round_robin";
    function trace2(text) {
      logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
    }
    __name(trace2, "trace");
    var TYPE_NAME = "weighted_round_robin";
    var DEFAULT_OOB_REPORTING_PERIOD_MS = 1e4;
    var DEFAULT_BLACKOUT_PERIOD_MS = 1e4;
    var DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 6e4;
    var DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1e3;
    var DEFAULT_ERROR_UTILIZATION_PENALTY = 1;
    function validateFieldType(obj, fieldName, expectedType) {
      if (fieldName in obj && obj[fieldName] !== void 0 && typeof obj[fieldName] !== expectedType) {
        throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`);
      }
    }
    __name(validateFieldType, "validateFieldType");
    function parseDurationField(obj, fieldName) {
      if (fieldName in obj && obj[fieldName] !== void 0 && obj[fieldName] !== null) {
        let durationObject;
        if ((0, duration_1.isDuration)(obj[fieldName])) {
          durationObject = obj[fieldName];
        } else if ((0, duration_1.isDurationMessage)(obj[fieldName])) {
          durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]);
        } else if (typeof obj[fieldName] === "string") {
          const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]);
          if (!parsedDuration) {
            throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`);
          }
          durationObject = parsedDuration;
        } else {
          throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`);
        }
        return (0, duration_1.durationToMs)(durationObject);
      }
      return null;
    }
    __name(parseDurationField, "parseDurationField");
    var WeightedRoundRobinLoadBalancingConfig = class _WeightedRoundRobinLoadBalancingConfig {
      static {
        __name(this, "WeightedRoundRobinLoadBalancingConfig");
      }
      constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) {
        this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== void 0 ? enableOobLoadReport : false;
        this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== void 0 ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS;
        this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== void 0 ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS;
        this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== void 0 ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS;
        this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== void 0 ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100);
        this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== void 0 ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY;
      }
      getLoadBalancerName() {
        return TYPE_NAME;
      }
      toJsonObject() {
        return {
          enable_oob_load_report: this.enableOobLoadReport,
          oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)),
          blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)),
          weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)),
          weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)),
          error_utilization_penalty: this.errorUtilizationPenalty
        };
      }
      static createFromJson(obj) {
        validateFieldType(obj, "enable_oob_load_report", "boolean");
        validateFieldType(obj, "error_utilization_penalty", "number");
        if (obj.error_utilization_penalty < 0) {
          throw new Error("weighted round robin config error_utilization_penalty < 0");
        }
        return new _WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, "oob_load_reporting_period"), parseDurationField(obj, "blackout_period"), parseDurationField(obj, "weight_expiration_period"), parseDurationField(obj, "weight_update_period"), obj.error_utilization_penalty);
      }
      getEnableOobLoadReport() {
        return this.enableOobLoadReport;
      }
      getOobLoadReportingPeriodMs() {
        return this.oobLoadReportingPeriodMs;
      }
      getBlackoutPeriodMs() {
        return this.blackoutPeriodMs;
      }
      getWeightExpirationPeriodMs() {
        return this.weightExpirationPeriodMs;
      }
      getWeightUpdatePeriodMs() {
        return this.weightUpdatePeriodMs;
      }
      getErrorUtilizationPenalty() {
        return this.errorUtilizationPenalty;
      }
    };
    exports.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig;
    var WeightedRoundRobinPicker = class {
      static {
        __name(this, "WeightedRoundRobinPicker");
      }
      constructor(children, metricsHandler) {
        this.metricsHandler = metricsHandler;
        this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline);
        const positiveWeight = children.filter((picker) => picker.weight > 0);
        let averageWeight;
        if (positiveWeight.length < 2) {
          averageWeight = 1;
        } else {
          let weightSum = 0;
          for (const { weight } of positiveWeight) {
            weightSum += weight;
          }
          averageWeight = weightSum / positiveWeight.length;
        }
        for (const child of children) {
          const period = child.weight > 0 ? 1 / child.weight : averageWeight;
          this.queue.push({
            endpointName: child.endpointName,
            picker: child.picker,
            period,
            deadline: Math.random() * period
          });
        }
      }
      pick(pickArgs) {
        const entry = this.queue.pop();
        this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period }));
        const childPick = entry.picker.pick(pickArgs);
        if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) {
          if (this.metricsHandler) {
            return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)((loadReport) => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) });
          } else {
            const subchannelWrapper = childPick.subchannel;
            return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() });
          }
        } else {
          return childPick;
        }
      }
    };
    var WeightedRoundRobinLoadBalancer = class {
      static {
        __name(this, "WeightedRoundRobinLoadBalancer");
      }
      constructor(channelControlHelper) {
        this.channelControlHelper = channelControlHelper;
        this.latestConfig = null;
        this.children = /* @__PURE__ */ new Map();
        this.currentState = connectivity_state_1.ConnectivityState.IDLE;
        this.updatesPaused = false;
        this.lastError = null;
        this.weightUpdateTimer = null;
      }
      countChildrenWithState(state) {
        let count = 0;
        for (const entry of this.children.values()) {
          if (entry.child.getConnectivityState() === state) {
            count += 1;
          }
        }
        return count;
      }
      updateWeight(entry, loadReport) {
        var _a, _b;
        const qps = loadReport.rps_fractional;
        let utilization = loadReport.application_utilization;
        if (utilization > 0 && qps > 0) {
          utilization += loadReport.eps / qps * ((_b = (_a = this.latestConfig) === null || _a === void 0 ? void 0 : _a.getErrorUtilizationPenalty()) !== null && _b !== void 0 ? _b : 0);
        }
        const newWeight = utilization === 0 ? 0 : qps / utilization;
        if (newWeight === 0) {
          return;
        }
        const now = /* @__PURE__ */ new Date();
        if (entry.nonEmptySince === null) {
          entry.nonEmptySince = now;
        }
        entry.lastUpdated = now;
        entry.weight = newWeight;
      }
      getWeight(entry) {
        if (!this.latestConfig) {
          return 0;
        }
        const now = (/* @__PURE__ */ new Date()).getTime();
        if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) {
          entry.nonEmptySince = null;
          return 0;
        }
        const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs();
        if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) {
          return 0;
        }
        return entry.weight;
      }
      calculateAndUpdateState() {
        if (this.updatesPaused || !this.latestConfig) {
          return;
        }
        if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) {
          const weightedPickers = [];
          for (const [endpoint, entry] of this.children) {
            if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) {
              continue;
            }
            weightedPickers.push({
              endpointName: endpoint,
              picker: entry.child.getPicker(),
              weight: this.getWeight(entry)
            });
          }
          trace2("Created picker with weights: " + weightedPickers.map((entry) => entry.endpointName + ":" + entry.weight).join(","));
          let metricsHandler;
          if (!this.latestConfig.getEnableOobLoadReport()) {
            metricsHandler = /* @__PURE__ */ __name((loadReport, endpointName) => {
              const childEntry = this.children.get(endpointName);
              if (childEntry) {
                this.updateWeight(childEntry, loadReport);
              }
            }, "metricsHandler");
          } else {
            metricsHandler = null;
          }
          this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null);
        } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) {
          this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null);
        } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) {
          const errorMessage2 = `weighted_round_robin: No connection established. Last error: ${this.lastError}`;
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
            details: errorMessage2
          }), errorMessage2);
        } else {
          this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
        }
        for (const { child } of this.children.values()) {
          if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) {
            child.exitIdle();
          }
        }
      }
      updateState(newState, picker, errorMessage2) {
        trace2(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
        this.currentState = newState;
        this.channelControlHelper.updateState(newState, picker, errorMessage2);
      }
      updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) {
        var _a, _b;
        if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) {
          return false;
        }
        if (!maybeEndpointList.ok) {
          if (this.children.size === 0) {
            this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details);
          }
          return true;
        }
        if (maybeEndpointList.value.length === 0) {
          const errorMessage2 = `No addresses resolved. Resolution note: ${resolutionNote}`;
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage2 }), errorMessage2);
          return false;
        }
        trace2("Connect to endpoint list " + maybeEndpointList.value.map(subchannel_address_1.endpointToString));
        const now = /* @__PURE__ */ new Date();
        const seenEndpointNames = /* @__PURE__ */ new Set();
        this.updatesPaused = true;
        this.latestConfig = lbConfig;
        for (const endpoint of maybeEndpointList.value) {
          const name = (0, subchannel_address_1.endpointToString)(endpoint);
          seenEndpointNames.add(name);
          let entry = this.children.get(name);
          if (!entry) {
            entry = {
              child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, {
                updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage2) => {
                  if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) {
                    this.channelControlHelper.requestReresolution();
                  }
                  if (connectivityState === connectivity_state_1.ConnectivityState.READY) {
                    entry.nonEmptySince = null;
                  }
                  if (errorMessage2) {
                    this.lastError = errorMessage2;
                  }
                  this.calculateAndUpdateState();
                }, "updateState"),
                createSubchannel: /* @__PURE__ */ __name((subchannelAddress, subchannelArgs) => {
                  const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
                  if (entry === null || entry === void 0 ? void 0 : entry.oobMetricsListener) {
                    return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs());
                  } else {
                    return subchannel;
                  }
                }, "createSubchannel")
              }), options, resolutionNote),
              lastUpdated: now,
              nonEmptySince: null,
              weight: 0,
              oobMetricsListener: null
            };
            this.children.set(name, entry);
          }
          if (lbConfig.getEnableOobLoadReport()) {
            entry.oobMetricsListener = (loadReport) => {
              this.updateWeight(entry, loadReport);
            };
          } else {
            entry.oobMetricsListener = null;
          }
        }
        for (const [endpointName, entry] of this.children) {
          if (seenEndpointNames.has(endpointName)) {
            entry.child.startConnecting();
          } else {
            entry.child.destroy();
            this.children.delete(endpointName);
          }
        }
        this.updatesPaused = false;
        this.calculateAndUpdateState();
        if (this.weightUpdateTimer) {
          clearInterval(this.weightUpdateTimer);
        }
        this.weightUpdateTimer = (_b = (_a = setInterval(() => {
          if (this.currentState === connectivity_state_1.ConnectivityState.READY) {
            this.calculateAndUpdateState();
          }
        }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
        return true;
      }
      exitIdle() {
      }
      resetBackoff() {
      }
      destroy() {
        for (const entry of this.children.values()) {
          entry.child.destroy();
        }
        this.children.clear();
        if (this.weightUpdateTimer) {
          clearInterval(this.weightUpdateTimer);
        }
      }
      getTypeName() {
        return TYPE_NAME;
      }
    };
    function setup() {
      (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig);
    }
    __name(setup, "setup");
  }
});

// node_modules/@grpc/grpc-js/build/src/index.js
var require_src6 = __commonJS({
  "node_modules/@grpc/grpc-js/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.experimental = exports.ServerMetricRecorder = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = exports.addAdminServicesToServer = exports.getChannelzHandlers = exports.getChannelzServiceDefinition = exports.InterceptorConfigurationError = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.compressionAlgorithms = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = void 0;
    var call_credentials_1 = require_call_credentials();
    Object.defineProperty(exports, "CallCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return call_credentials_1.CallCredentials;
    }, "get") });
    var channel_1 = require_channel();
    Object.defineProperty(exports, "Channel", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channel_1.ChannelImplementation;
    }, "get") });
    var compression_algorithms_1 = require_compression_algorithms();
    Object.defineProperty(exports, "compressionAlgorithms", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return compression_algorithms_1.CompressionAlgorithms;
    }, "get") });
    var connectivity_state_1 = require_connectivity_state();
    Object.defineProperty(exports, "connectivityState", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return connectivity_state_1.ConnectivityState;
    }, "get") });
    var channel_credentials_1 = require_channel_credentials();
    Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channel_credentials_1.ChannelCredentials;
    }, "get") });
    var client_1 = require_client();
    Object.defineProperty(exports, "Client", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_1.Client;
    }, "get") });
    var constants_1 = require_constants2();
    Object.defineProperty(exports, "logVerbosity", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.LogVerbosity;
    }, "get") });
    Object.defineProperty(exports, "status", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.Status;
    }, "get") });
    Object.defineProperty(exports, "propagate", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.Propagate;
    }, "get") });
    var logging = require_logging();
    var make_client_1 = require_make_client();
    Object.defineProperty(exports, "loadPackageDefinition", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return make_client_1.loadPackageDefinition;
    }, "get") });
    Object.defineProperty(exports, "makeClientConstructor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return make_client_1.makeClientConstructor;
    }, "get") });
    Object.defineProperty(exports, "makeGenericClientConstructor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return make_client_1.makeClientConstructor;
    }, "get") });
    var metadata_1 = require_metadata();
    Object.defineProperty(exports, "Metadata", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return metadata_1.Metadata;
    }, "get") });
    var server_1 = require_server();
    Object.defineProperty(exports, "Server", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_1.Server;
    }, "get") });
    var server_credentials_1 = require_server_credentials();
    Object.defineProperty(exports, "ServerCredentials", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_credentials_1.ServerCredentials;
    }, "get") });
    var status_builder_1 = require_status_builder();
    Object.defineProperty(exports, "StatusBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return status_builder_1.StatusBuilder;
    }, "get") });
    exports.credentials = {
      /**
       * Combine a ChannelCredentials with any number of CallCredentials into a
       * single ChannelCredentials object.
       * @param channelCredentials The ChannelCredentials object.
       * @param callCredentials Any number of CallCredentials objects.
       * @return The resulting ChannelCredentials object.
       */
      combineChannelCredentials: /* @__PURE__ */ __name((channelCredentials, ...callCredentials) => {
        return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials);
      }, "combineChannelCredentials"),
      /**
       * Combine any number of CallCredentials into a single CallCredentials
       * object.
       * @param first The first CallCredentials object.
       * @param additional Any number of additional CallCredentials objects.
       * @return The resulting CallCredentials object.
       */
      combineCallCredentials: /* @__PURE__ */ __name((first, ...additional) => {
        return additional.reduce((acc, other) => acc.compose(other), first);
      }, "combineCallCredentials"),
      // from channel-credentials.ts
      createInsecure: channel_credentials_1.ChannelCredentials.createInsecure,
      createSsl: channel_credentials_1.ChannelCredentials.createSsl,
      createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext,
      // from call-credentials.ts
      createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator,
      createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential,
      createEmpty: call_credentials_1.CallCredentials.createEmpty
    };
    var closeClient = /* @__PURE__ */ __name((client) => client.close(), "closeClient");
    exports.closeClient = closeClient;
    var waitForClientReady = /* @__PURE__ */ __name((client, deadline, callback) => client.waitForReady(deadline, callback), "waitForClientReady");
    exports.waitForClientReady = waitForClientReady;
    var loadObject = /* @__PURE__ */ __name((value, options) => {
      throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead");
    }, "loadObject");
    exports.loadObject = loadObject;
    var load = /* @__PURE__ */ __name((filename, format, options) => {
      throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead");
    }, "load");
    exports.load = load;
    var setLogger = /* @__PURE__ */ __name((logger) => {
      logging.setLogger(logger);
    }, "setLogger");
    exports.setLogger = setLogger;
    var setLogVerbosity = /* @__PURE__ */ __name((verbosity) => {
      logging.setLoggerVerbosity(verbosity);
    }, "setLogVerbosity");
    exports.setLogVerbosity = setLogVerbosity;
    var getClientChannel = /* @__PURE__ */ __name((client) => {
      return client_1.Client.prototype.getChannel.call(client);
    }, "getClientChannel");
    exports.getClientChannel = getClientChannel;
    var client_interceptors_1 = require_client_interceptors();
    Object.defineProperty(exports, "ListenerBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.ListenerBuilder;
    }, "get") });
    Object.defineProperty(exports, "RequesterBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.RequesterBuilder;
    }, "get") });
    Object.defineProperty(exports, "InterceptingCall", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.InterceptingCall;
    }, "get") });
    Object.defineProperty(exports, "InterceptorConfigurationError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return client_interceptors_1.InterceptorConfigurationError;
    }, "get") });
    var channelz_1 = require_channelz();
    Object.defineProperty(exports, "getChannelzServiceDefinition", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channelz_1.getChannelzServiceDefinition;
    }, "get") });
    Object.defineProperty(exports, "getChannelzHandlers", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return channelz_1.getChannelzHandlers;
    }, "get") });
    var admin_1 = require_admin();
    Object.defineProperty(exports, "addAdminServicesToServer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return admin_1.addAdminServicesToServer;
    }, "get") });
    var server_interceptors_1 = require_server_interceptors();
    Object.defineProperty(exports, "ServerListenerBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_interceptors_1.ServerListenerBuilder;
    }, "get") });
    Object.defineProperty(exports, "ResponderBuilder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_interceptors_1.ResponderBuilder;
    }, "get") });
    Object.defineProperty(exports, "ServerInterceptingCall", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return server_interceptors_1.ServerInterceptingCall;
    }, "get") });
    var orca_1 = require_orca();
    Object.defineProperty(exports, "ServerMetricRecorder", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return orca_1.ServerMetricRecorder;
    }, "get") });
    var experimental = require_experimental();
    exports.experimental = experimental;
    var resolver_dns = require_resolver_dns();
    var resolver_uds = require_resolver_uds();
    var resolver_ip = require_resolver_ip();
    var load_balancer_pick_first = require_load_balancer_pick_first();
    var load_balancer_round_robin = require_load_balancer_round_robin();
    var load_balancer_outlier_detection = require_load_balancer_outlier_detection();
    var load_balancer_weighted_round_robin = require_load_balancer_weighted_round_robin();
    var channelz = require_channelz();
    (() => {
      resolver_dns.setup();
      resolver_uds.setup();
      resolver_ip.setup();
      load_balancer_pick_first.setup();
      load_balancer_round_robin.setup();
      load_balancer_outlier_detection.setup();
      load_balancer_weighted_round_robin.setup();
      channelz.setup();
    })();
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js
var require_create_service_client_constructor = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createServiceClientConstructor = void 0;
    var grpc = require_src6();
    function createServiceClientConstructor(path11, name) {
      const serviceDefinition = {
        export: {
          path: path11,
          requestStream: false,
          responseStream: false,
          requestSerialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "requestSerialize"),
          requestDeserialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "requestDeserialize"),
          responseSerialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "responseSerialize"),
          responseDeserialize: /* @__PURE__ */ __name((arg) => {
            return arg;
          }, "responseDeserialize")
        }
      };
      return grpc.makeGenericClientConstructor(serviceDefinition, name);
    }
    __name(createServiceClientConstructor, "createServiceClientConstructor");
    exports.createServiceClientConstructor = createServiceClientConstructor;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js
var require_grpc_exporter_transport = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createOtlpGrpcExporterTransport = exports.GrpcExporterTransport = exports.createEmptyMetadata = exports.createSslCredentials = exports.createInsecureCredentials = void 0;
    var GRPC_COMPRESSION_NONE = 0;
    var GRPC_COMPRESSION_GZIP = 2;
    function toGrpcCompression(compression) {
      return compression === "gzip" ? GRPC_COMPRESSION_GZIP : GRPC_COMPRESSION_NONE;
    }
    __name(toGrpcCompression, "toGrpcCompression");
    function createInsecureCredentials() {
      const {
        credentials
        // eslint-disable-next-line @typescript-eslint/no-require-imports
      } = require_src6();
      return credentials.createInsecure();
    }
    __name(createInsecureCredentials, "createInsecureCredentials");
    exports.createInsecureCredentials = createInsecureCredentials;
    function createSslCredentials(rootCert, privateKey, certChain) {
      const {
        credentials
        // eslint-disable-next-line @typescript-eslint/no-require-imports
      } = require_src6();
      return credentials.createSsl(rootCert, privateKey, certChain);
    }
    __name(createSslCredentials, "createSslCredentials");
    exports.createSslCredentials = createSslCredentials;
    function createEmptyMetadata() {
      const {
        Metadata
        // eslint-disable-next-line @typescript-eslint/no-require-imports
      } = require_src6();
      return new Metadata();
    }
    __name(createEmptyMetadata, "createEmptyMetadata");
    exports.createEmptyMetadata = createEmptyMetadata;
    var GrpcExporterTransport = class {
      static {
        __name(this, "GrpcExporterTransport");
      }
      _parameters;
      _client;
      _metadata;
      constructor(_parameters) {
        this._parameters = _parameters;
      }
      shutdown() {
        this._client?.close();
      }
      send(data, timeoutMillis) {
        const buffer = Buffer.from(data);
        if (this._client == null) {
          const {
            createServiceClientConstructor
            // eslint-disable-next-line @typescript-eslint/no-require-imports
          } = require_create_service_client_constructor();
          try {
            this._metadata = this._parameters.metadata();
          } catch (error) {
            return Promise.resolve({
              status: "failure",
              error
            });
          }
          const clientConstructor = createServiceClientConstructor(this._parameters.grpcPath, this._parameters.grpcName);
          try {
            this._client = new clientConstructor(this._parameters.address, this._parameters.credentials(), {
              "grpc.default_compression_algorithm": toGrpcCompression(this._parameters.compression)
            });
          } catch (error) {
            return Promise.resolve({
              status: "failure",
              error
            });
          }
        }
        return new Promise((resolve2) => {
          const deadline = Date.now() + timeoutMillis;
          if (this._metadata == null) {
            return resolve2({
              error: new Error("metadata was null"),
              status: "failure"
            });
          }
          this._client.export(buffer, this._metadata, { deadline }, (err, response) => {
            if (err) {
              resolve2({
                status: "failure",
                error: err
              });
            } else {
              resolve2({
                data: response,
                status: "success"
              });
            }
          });
        });
      }
    };
    exports.GrpcExporterTransport = GrpcExporterTransport;
    function createOtlpGrpcExporterTransport(options) {
      return new GrpcExporterTransport(options);
    }
    __name(createOtlpGrpcExporterTransport, "createOtlpGrpcExporterTransport");
    exports.createOtlpGrpcExporterTransport = createOtlpGrpcExporterTransport;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js
var require_version2 = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js
var require_otlp_grpc_configuration = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getOtlpGrpcDefaultConfiguration = exports.mergeOtlpGrpcConfigurationWithDefaults = exports.validateAndNormalizeUrl = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    var version_1 = require_version2();
    var url_1 = __require("url");
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    function validateAndNormalizeUrl(url) {
      url = url.trim();
      const hasProtocol = url.match(/^([\w]{1,8}):\/\//);
      if (!hasProtocol) {
        url = `https://${url}`;
      }
      const target = new url_1.URL(url);
      if (target.protocol === "unix:") {
        return url;
      }
      if (target.pathname && target.pathname !== "/") {
        api_1.diag.warn("URL path should not be set when using grpc, the path part of the URL will be ignored.");
      }
      if (target.protocol !== "" && !target.protocol?.match(/^(http)s?:$/)) {
        api_1.diag.warn("URL protocol should be http(s)://. Using http://.");
      }
      return target.host;
    }
    __name(validateAndNormalizeUrl, "validateAndNormalizeUrl");
    exports.validateAndNormalizeUrl = validateAndNormalizeUrl;
    function overrideMetadataEntriesIfNotPresent(metadata, additionalMetadata) {
      for (const [key, value] of Object.entries(additionalMetadata.getMap())) {
        if (metadata.get(key).length < 1) {
          metadata.set(key, value);
        }
      }
    }
    __name(overrideMetadataEntriesIfNotPresent, "overrideMetadataEntriesIfNotPresent");
    function mergeOtlpGrpcConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
      const rawUrl = userProvidedConfiguration.url ?? fallbackConfiguration.url ?? defaultConfiguration.url;
      return {
        ...(0, otlp_exporter_base_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
        metadata: /* @__PURE__ */ __name(() => {
          const metadata = defaultConfiguration.metadata();
          overrideMetadataEntriesIfNotPresent(
            metadata,
            // clone to ensure we don't modify what the user gave us in case they hold on to the returned reference
            userProvidedConfiguration.metadata?.().clone() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()
          );
          overrideMetadataEntriesIfNotPresent(metadata, fallbackConfiguration.metadata?.() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)());
          return metadata;
        }, "metadata"),
        url: validateAndNormalizeUrl(rawUrl),
        credentials: userProvidedConfiguration.credentials ?? fallbackConfiguration.credentials?.(rawUrl) ?? defaultConfiguration.credentials(rawUrl)
      };
    }
    __name(mergeOtlpGrpcConfigurationWithDefaults, "mergeOtlpGrpcConfigurationWithDefaults");
    exports.mergeOtlpGrpcConfigurationWithDefaults = mergeOtlpGrpcConfigurationWithDefaults;
    function getOtlpGrpcDefaultConfiguration() {
      return {
        ...(0, otlp_exporter_base_1.getSharedConfigurationDefaults)(),
        metadata: /* @__PURE__ */ __name(() => {
          const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)();
          metadata.set("User-Agent", `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`);
          return metadata;
        }, "metadata"),
        url: "http://localhost:4317",
        credentials: /* @__PURE__ */ __name((url) => {
          if (url.startsWith("http://")) {
            return () => (0, grpc_exporter_transport_1.createInsecureCredentials)();
          } else {
            return () => (0, grpc_exporter_transport_1.createSslCredentials)();
          }
        }, "credentials")
      };
    }
    __name(getOtlpGrpcDefaultConfiguration, "getOtlpGrpcDefaultConfiguration");
    exports.getOtlpGrpcDefaultConfiguration = getOtlpGrpcDefaultConfiguration;
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js
function isExportRetryable(statusCode) {
  const retryCodes = [429, 502, 503, 504];
  return retryCodes.includes(statusCode);
}
function parseRetryAfterToMills(retryAfter) {
  if (retryAfter == null) {
    return void 0;
  }
  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 = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js"() {
    init_esbuild_shims();
    __name(isExportRetryable, "isExportRetryable");
    __name(parseRetryAfterToMills, "parseRetryAfterToMills");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js
var http_transport_utils_exports = {};
__export(http_transport_utils_exports, {
  compressAndSend: () => compressAndSend,
  createHttpAgent: () => createHttpAgent,
  sendWithHttp: () => sendWithHttp
});
import * as http from "http";
import * as https from "https";
import * as zlib from "zlib";
import { Readable } from "stream";
function sendWithHttp(params, agent, data, onDone, timeoutMillis) {
  const parsedUrl = new URL(params.url);
  const options = {
    hostname: parsedUrl.hostname,
    port: parsedUrl.port,
    path: parsedUrl.pathname,
    method: "POST",
    headers: {
      ...params.headers()
    },
    agent
  };
  const request4 = parsedUrl.protocol === "http:" ? http.request : https.request;
  const req = request4(options, (res) => {
    const responseData = [];
    res.on("data", (chunk) => responseData.push(chunk));
    res.on("end", () => {
      if (res.statusCode && res.statusCode < 299) {
        onDone({
          status: "success",
          data: Buffer.concat(responseData)
        });
      } else if (res.statusCode && isExportRetryable(res.statusCode)) {
        onDone({
          status: "retryable",
          retryInMillis: parseRetryAfterToMills(res.headers["retry-after"])
        });
      } else {
        const error = new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString());
        onDone({
          status: "failure",
          error
        });
      }
    });
  });
  req.setTimeout(timeoutMillis, () => {
    req.destroy();
    onDone({
      status: "failure",
      error: new Error("Request Timeout")
    });
  });
  req.on("error", (error) => {
    onDone({
      status: "failure",
      error
    });
  });
  compressAndSend(req, params.compression, data, (error) => {
    onDone({
      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 createHttpAgent(rawUrl, agentOptions) {
  const parsedUrl = new URL(rawUrl);
  const Agent3 = parsedUrl.protocol === "http:" ? http.Agent : https.Agent;
  return new Agent3(agentOptions);
}
var init_http_transport_utils = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js"() {
    init_esbuild_shims();
    init_is_export_retryable();
    init_types();
    __name(sendWithHttp, "sendWithHttp");
    __name(compressAndSend, "compressAndSend");
    __name(readableFromUint8Array, "readableFromUint8Array");
    __name(createHttpAgent, "createHttpAgent");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js
function createHttpExporterTransport(parameters) {
  return new HttpExporterTransport(parameters);
}
var HttpExporterTransport;
var init_http_exporter_transport = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js"() {
    init_esbuild_shims();
    HttpExporterTransport = class {
      static {
        __name(this, "HttpExporterTransport");
      }
      _parameters;
      _utils = null;
      constructor(_parameters) {
        this._parameters = _parameters;
      }
      async send(data, timeoutMillis) {
        const { agent, send } = this._loadUtils();
        return new Promise((resolve2) => {
          send(this._parameters, agent, data, (result) => {
            resolve2(result);
          }, timeoutMillis);
        });
      }
      shutdown() {
      }
      _loadUtils() {
        let utils = this._utils;
        if (utils === null) {
          const {
            sendWithHttp: sendWithHttp2,
            createHttpAgent: createHttpAgent2
            // eslint-disable-next-line @typescript-eslint/no-require-imports
          } = (init_http_transport_utils(), __toCommonJS(http_transport_utils_exports));
          utils = this._utils = {
            agent: createHttpAgent2(this._parameters.url, this._parameters.agentOptions),
            send: sendWithHttp2
          };
        }
        return utils;
      }
    };
    __name(createHttpExporterTransport, "createHttpExporterTransport");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js
function getJitter() {
  return Math.random() * (2 * JITTER) - JITTER;
}
function createRetryingTransport(options) {
  return new RetryingTransport(options.transport);
}
var MAX_ATTEMPTS, INITIAL_BACKOFF, MAX_BACKOFF, BACKOFF_MULTIPLIER, JITTER, RetryingTransport;
var init_retrying_transport = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js"() {
    init_esbuild_shims();
    MAX_ATTEMPTS = 5;
    INITIAL_BACKOFF = 1e3;
    MAX_BACKOFF = 5e3;
    BACKOFF_MULTIPLIER = 1.5;
    JITTER = 0.2;
    __name(getJitter, "getJitter");
    RetryingTransport = class {
      static {
        __name(this, "RetryingTransport");
      }
      _transport;
      constructor(_transport) {
        this._transport = _transport;
      }
      retry(data, timeoutMillis, inMillis) {
        return new Promise((resolve2, reject) => {
          setTimeout(() => {
            this._transport.send(data, timeoutMillis).then(resolve2, reject);
          }, inMillis);
        });
      }
      async send(data, timeoutMillis) {
        const deadline = Date.now() + timeoutMillis;
        let result = await this._transport.send(data, timeoutMillis);
        let attempts = MAX_ATTEMPTS;
        let nextBackoff = INITIAL_BACKOFF;
        while (result.status === "retryable" && attempts > 0) {
          attempts--;
          const backoff = Math.max(Math.min(nextBackoff, MAX_BACKOFF) + getJitter(), 0);
          nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;
          const retryInMillis = result.retryInMillis ?? backoff;
          const remainingTimeoutMillis = deadline - Date.now();
          if (retryInMillis > remainingTimeoutMillis) {
            return result;
          }
          result = await this.retry(data, remainingTimeoutMillis, retryInMillis);
        }
        return result;
      }
      shutdown() {
        return this._transport.shutdown();
      }
    };
    __name(createRetryingTransport, "createRetryingTransport");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js
function createOtlpHttpExportDelegate(options, serializer) {
  return createOtlpExportDelegate({
    transport: createRetryingTransport({
      transport: createHttpExporterTransport(options)
    }),
    serializer,
    promiseHandler: createBoundedQueueExportPromiseHandler(options)
  }, { timeout: options.timeoutMillis });
}
var init_otlp_http_export_delegate = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js"() {
    init_esbuild_shims();
    init_otlp_export_delegate();
    init_http_exporter_transport();
    init_bounded_queue_export_promise_handler();
    init_retrying_transport();
    __name(createOtlpHttpExportDelegate, "createOtlpHttpExportDelegate");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-env-configuration.js
function parseAndValidateTimeoutFromEnv(timeoutEnvVar) {
  const envTimeout = process.env[timeoutEnvVar]?.trim();
  if (envTimeout != null && envTimeout !== "") {
    const definedTimeout = Number(envTimeout);
    if (Number.isFinite(definedTimeout) && definedTimeout > 0) {
      return definedTimeout;
    }
    diag.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`);
  }
  return void 0;
}
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 = process.env[compressionEnvVar]?.trim();
  if (compression === "") {
    return void 0;
  }
  if (compression == null || compression === "none" || compression === "gzip") {
    return compression;
  }
  diag.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`);
  return void 0;
}
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 init_shared_env_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-env-configuration.js"() {
    init_esbuild_shims();
    init_esm();
    __name(parseAndValidateTimeoutFromEnv, "parseAndValidateTimeoutFromEnv");
    __name(getTimeoutFromEnv, "getTimeoutFromEnv");
    __name(parseAndValidateCompressionFromEnv, "parseAndValidateCompressionFromEnv");
    __name(getCompressionFromEnv, "getCompressionFromEnv");
    __name(getSharedConfigurationFromEnvironment, "getSharedConfigurationFromEnvironment");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/util.js
function validateAndNormalizeHeaders(partialHeaders) {
  return () => {
    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 = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/util.js"() {
    init_esbuild_shims();
    init_esm();
    __name(validateAndNormalizeHeaders, "validateAndNormalizeHeaders");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-configuration.js
function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) {
  const requiredHeaders = {
    ...defaultHeaders()
  };
  const headers = {};
  return () => {
    if (fallbackHeaders != null) {
      Object.assign(headers, fallbackHeaders());
    }
    if (userProvidedHeaders != null) {
      Object.assign(headers, userProvidedHeaders());
    }
    return Object.assign(headers, requiredHeaders);
  };
}
function validateUserProvidedUrl(url) {
  if (url == null) {
    return void 0;
  }
  try {
    new URL(url);
    return url;
  } catch {
    throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`);
  }
}
function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
  return {
    ...mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
    headers: mergeHeaders(validateAndNormalizeHeaders(userProvidedConfiguration.headers), fallbackConfiguration.headers, defaultConfiguration.headers),
    url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? fallbackConfiguration.url ?? defaultConfiguration.url,
    agentOptions: userProvidedConfiguration.agentOptions ?? fallbackConfiguration.agentOptions ?? defaultConfiguration.agentOptions
  };
}
function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {
  return {
    ...getSharedConfigurationDefaults(),
    headers: /* @__PURE__ */ __name(() => requiredHeaders, "headers"),
    url: "http://localhost:4318/" + signalResourcePath,
    agentOptions: { keepAlive: true }
  };
}
var init_otlp_http_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-configuration.js"() {
    init_esbuild_shims();
    init_shared_configuration();
    init_util();
    __name(mergeHeaders, "mergeHeaders");
    __name(validateUserProvidedUrl, "validateUserProvidedUrl");
    __name(mergeOtlpHttpConfigurationWithDefaults, "mergeOtlpHttpConfigurationWithDefaults");
    __name(getHttpConfigurationDefaults, "getHttpConfigurationDefaults");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-env-configuration.js
function getStaticHeadersFromEnv(signalIdentifier) {
  const signalSpecificRawHeaders = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim();
  const nonSignalSpecificRawHeaders = process.env["OTEL_EXPORTER_OTLP_HEADERS"]?.trim();
  const signalSpecificHeaders = (0, import_core2.parseKeyPairsIntoRecord)(signalSpecificRawHeaders);
  const nonSignalSpecificHeaders = (0, import_core2.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders);
  if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) {
    return void 0;
  }
  return Object.assign({}, (0, import_core2.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders), (0, import_core2.parseKeyPairsIntoRecord)(signalSpecificRawHeaders));
}
function appendRootPathToUrlIfNeeded(url) {
  try {
    const parsedUrl = new URL(url);
    return parsedUrl.toString();
  } catch {
    diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`);
    return void 0;
  }
}
function appendResourcePathToUrl(url, path11) {
  try {
    new URL(url);
  } catch {
    diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`);
    return void 0;
  }
  if (!url.endsWith("/")) {
    url = url + "/";
  }
  url += path11;
  try {
    new URL(url);
  } catch {
    diag.warn(`Configuration: Provided URL appended with '${path11}' is not a valid URL, using 'undefined' instead of '${url}'`);
    return void 0;
  }
  return url;
}
function getNonSpecificUrlFromEnv(signalResourcePath) {
  const envUrl = process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim();
  if (envUrl == null || envUrl === "") {
    return void 0;
  }
  return appendResourcePathToUrl(envUrl, signalResourcePath);
}
function getSpecificUrlFromEnv(signalIdentifier) {
  const envUrl = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim();
  if (envUrl == null || envUrl === "") {
    return void 0;
  }
  return appendRootPathToUrlIfNeeded(envUrl);
}
function getHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) {
  return {
    ...getSharedConfigurationFromEnvironment(signalIdentifier),
    url: getSpecificUrlFromEnv(signalIdentifier) ?? getNonSpecificUrlFromEnv(signalResourcePath),
    headers: wrapStaticHeadersInFunction(getStaticHeadersFromEnv(signalIdentifier))
  };
}
var import_core2;
var init_otlp_http_env_configuration = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-env-configuration.js"() {
    init_esbuild_shims();
    import_core2 = __toESM(require_src3());
    init_esm();
    init_shared_env_configuration();
    init_shared_configuration();
    __name(getStaticHeadersFromEnv, "getStaticHeadersFromEnv");
    __name(appendRootPathToUrlIfNeeded, "appendRootPathToUrlIfNeeded");
    __name(appendResourcePathToUrl, "appendResourcePathToUrl");
    __name(getNonSpecificUrlFromEnv, "getNonSpecificUrlFromEnv");
    __name(getSpecificUrlFromEnv, "getSpecificUrlFromEnv");
    __name(getHttpConfigurationFromEnvironment, "getHttpConfigurationFromEnvironment");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-node-http-options.js
function convertLegacyAgentOptions(config) {
  if (config?.keepAlive != null) {
    if (config.httpAgentOptions != null) {
      if (config.httpAgentOptions.keepAlive == null) {
        config.httpAgentOptions.keepAlive = config.keepAlive;
      }
    } else {
      config.httpAgentOptions = {
        keepAlive: config.keepAlive
      };
    }
  }
  return config.httpAgentOptions;
}
function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) {
  if (config.metadata) {
    diag.warn("Metadata cannot be set when using http");
  }
  return mergeOtlpHttpConfigurationWithDefaults({
    url: config.url,
    headers: wrapStaticHeadersInFunction(config.headers),
    concurrencyLimit: config.concurrencyLimit,
    timeoutMillis: config.timeoutMillis,
    compression: config.compression,
    agentOptions: convertLegacyAgentOptions(config)
  }, getHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath), getHttpConfigurationDefaults(requiredHeaders, signalResourcePath));
}
var init_convert_legacy_node_http_options = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-node-http-options.js"() {
    init_esbuild_shims();
    init_otlp_http_configuration();
    init_otlp_http_env_configuration();
    init_esm();
    init_shared_configuration();
    __name(convertLegacyAgentOptions, "convertLegacyAgentOptions");
    __name(convertLegacyHttpOptions, "convertLegacyHttpOptions");
  }
});

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/index-node-http.js
var index_node_http_exports = {};
__export(index_node_http_exports, {
  convertLegacyHttpOptions: () => convertLegacyHttpOptions,
  createOtlpHttpExportDelegate: () => createOtlpHttpExportDelegate,
  getSharedConfigurationFromEnvironment: () => getSharedConfigurationFromEnvironment
});
var init_index_node_http = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/index-node-http.js"() {
    init_esbuild_shims();
    init_otlp_http_export_delegate();
    init_shared_env_configuration();
    init_convert_legacy_node_http_options();
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js
var require_otlp_grpc_env_configuration = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getOtlpGrpcConfigurationFromEnv = void 0;
    var core_1 = require_src3();
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var fs9 = __require("fs");
    var path11 = __require("path");
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    function fallbackIfNullishOrBlank(signalSpecific, nonSignalSpecific) {
      if (signalSpecific != null && signalSpecific !== "") {
        return signalSpecific;
      }
      if (nonSignalSpecific != null && nonSignalSpecific !== "") {
        return nonSignalSpecific;
      }
      return void 0;
    }
    __name(fallbackIfNullishOrBlank, "fallbackIfNullishOrBlank");
    function getMetadataFromEnv(signalIdentifier) {
      const signalSpecificRawHeaders = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim();
      const nonSignalSpecificRawHeaders = process.env["OTEL_EXPORTER_OTLP_HEADERS"]?.trim();
      const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders);
      const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders);
      if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) {
        return void 0;
      }
      const mergeHeaders2 = Object.assign({}, nonSignalSpecificHeaders, signalSpecificHeaders);
      const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)();
      for (const [key, value] of Object.entries(mergeHeaders2)) {
        metadata.set(key, value);
      }
      return metadata;
    }
    __name(getMetadataFromEnv, "getMetadataFromEnv");
    function getMetadataProviderFromEnv(signalIdentifier) {
      const metadata = getMetadataFromEnv(signalIdentifier);
      if (metadata == null) {
        return void 0;
      }
      return () => metadata;
    }
    __name(getMetadataProviderFromEnv, "getMetadataProviderFromEnv");
    function getUrlFromEnv(signalIdentifier) {
      const specificEndpoint = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim();
      const nonSpecificEndpoint = process.env[`OTEL_EXPORTER_OTLP_ENDPOINT`]?.trim();
      return fallbackIfNullishOrBlank(specificEndpoint, nonSpecificEndpoint);
    }
    __name(getUrlFromEnv, "getUrlFromEnv");
    function getInsecureSettingFromEnv(signalIdentifier) {
      const signalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_INSECURE`]?.toLowerCase().trim();
      const nonSignalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_INSECURE`]?.toLowerCase().trim();
      return fallbackIfNullishOrBlank(signalSpecificInsecureValue, nonSignalSpecificInsecureValue) === "true";
    }
    __name(getInsecureSettingFromEnv, "getInsecureSettingFromEnv");
    function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) {
      const signalSpecificPath = process.env[signalSpecificEnvVar]?.trim();
      const nonSignalSpecificPath = process.env[nonSignalSpecificEnvVar]?.trim();
      const filePath = fallbackIfNullishOrBlank(signalSpecificPath, nonSignalSpecificPath);
      if (filePath != null) {
        try {
          return fs9.readFileSync(path11.resolve(process.cwd(), filePath));
        } catch {
          api_1.diag.warn(warningMessage);
          return void 0;
        }
      } else {
        return void 0;
      }
    }
    __name(readFileFromEnv, "readFileFromEnv");
    function getClientCertificateFromEnv(signalIdentifier) {
      return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file");
    }
    __name(getClientCertificateFromEnv, "getClientCertificateFromEnv");
    function getClientKeyFromEnv(signalIdentifier) {
      return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file");
    }
    __name(getClientKeyFromEnv, "getClientKeyFromEnv");
    function getRootCertificateFromEnv(signalIdentifier) {
      return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file");
    }
    __name(getRootCertificateFromEnv, "getRootCertificateFromEnv");
    function getCredentialsFromEnvIgnoreInsecure(signalIdentifier) {
      const clientKey = getClientKeyFromEnv(signalIdentifier);
      const clientCertificate = getClientCertificateFromEnv(signalIdentifier);
      const rootCertificate = getRootCertificateFromEnv(signalIdentifier);
      const clientChainIntact = clientKey != null && clientCertificate != null;
      if (rootCertificate != null && !clientChainIntact) {
        api_1.diag.warn("Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate");
        return (0, grpc_exporter_transport_1.createSslCredentials)(getRootCertificateFromEnv(signalIdentifier));
      }
      return (0, grpc_exporter_transport_1.createSslCredentials)(rootCertificate, clientKey, clientCertificate);
    }
    __name(getCredentialsFromEnvIgnoreInsecure, "getCredentialsFromEnvIgnoreInsecure");
    function getCredentialsFromEnv(signalIdentifier) {
      if (getInsecureSettingFromEnv(signalIdentifier)) {
        return (0, grpc_exporter_transport_1.createInsecureCredentials)();
      }
      return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);
    }
    __name(getCredentialsFromEnv, "getCredentialsFromEnv");
    function getOtlpGrpcConfigurationFromEnv(signalIdentifier) {
      return {
        ...(0, node_http_1.getSharedConfigurationFromEnvironment)(signalIdentifier),
        metadata: getMetadataProviderFromEnv(signalIdentifier),
        url: getUrlFromEnv(signalIdentifier),
        credentials: /* @__PURE__ */ __name((finalResolvedUrl) => {
          if (finalResolvedUrl.startsWith("http://")) {
            return () => {
              return (0, grpc_exporter_transport_1.createInsecureCredentials)();
            };
          } else if (finalResolvedUrl.startsWith("https://")) {
            return () => {
              return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);
            };
          }
          return () => {
            return getCredentialsFromEnv(signalIdentifier);
          };
        }, "credentials")
      };
    }
    __name(getOtlpGrpcConfigurationFromEnv, "getOtlpGrpcConfigurationFromEnv");
    exports.getOtlpGrpcConfigurationFromEnv = getOtlpGrpcConfigurationFromEnv;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js
var require_convert_legacy_otlp_grpc_options = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.convertLegacyOtlpGrpcOptions = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var otlp_grpc_configuration_1 = require_otlp_grpc_configuration();
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    var otlp_grpc_env_configuration_1 = require_otlp_grpc_env_configuration();
    function convertLegacyOtlpGrpcOptions(config, signalIdentifier) {
      if (config.headers) {
        api_1.diag.warn("Headers cannot be set when using grpc");
      }
      const userProvidedCredentials = config.credentials;
      return (0, otlp_grpc_configuration_1.mergeOtlpGrpcConfigurationWithDefaults)({
        url: config.url,
        metadata: /* @__PURE__ */ __name(() => {
          return config.metadata ?? (0, grpc_exporter_transport_1.createEmptyMetadata)();
        }, "metadata"),
        compression: config.compression,
        timeoutMillis: config.timeoutMillis,
        concurrencyLimit: config.concurrencyLimit,
        credentials: userProvidedCredentials != null ? () => userProvidedCredentials : void 0
      }, (0, otlp_grpc_env_configuration_1.getOtlpGrpcConfigurationFromEnv)(signalIdentifier), (0, otlp_grpc_configuration_1.getOtlpGrpcDefaultConfiguration)());
    }
    __name(convertLegacyOtlpGrpcOptions, "convertLegacyOtlpGrpcOptions");
    exports.convertLegacyOtlpGrpcOptions = convertLegacyOtlpGrpcOptions;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js
var require_otlp_grpc_export_delegate = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createOtlpGrpcExportDelegate = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var grpc_exporter_transport_1 = require_grpc_exporter_transport();
    function createOtlpGrpcExportDelegate(options, serializer, grpcName, grpcPath) {
      return (0, otlp_exporter_base_1.createOtlpNetworkExportDelegate)(options, serializer, (0, grpc_exporter_transport_1.createOtlpGrpcExporterTransport)({
        address: options.url,
        compression: options.compression,
        credentials: options.credentials,
        metadata: options.metadata,
        grpcName,
        grpcPath
      }));
    }
    __name(createOtlpGrpcExportDelegate, "createOtlpGrpcExportDelegate");
    exports.createOtlpGrpcExportDelegate = createOtlpGrpcExportDelegate;
  }
});

// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js
var require_src7 = __commonJS({
  "node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createOtlpGrpcExportDelegate = exports.convertLegacyOtlpGrpcOptions = void 0;
    var convert_legacy_otlp_grpc_options_1 = require_convert_legacy_otlp_grpc_options();
    Object.defineProperty(exports, "convertLegacyOtlpGrpcOptions", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return convert_legacy_otlp_grpc_options_1.convertLegacyOtlpGrpcOptions;
    }, "get") });
    var otlp_grpc_export_delegate_1 = require_otlp_grpc_export_delegate();
    Object.defineProperty(exports, "createOtlpGrpcExportDelegate", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return otlp_grpc_export_delegate_1.createOtlpGrpcExportDelegate;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js
var require_root2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    var $protobuf = require_minimal2();
    var $Reader = $protobuf.Reader;
    var $Writer = $protobuf.Writer;
    var $util = $protobuf.util;
    var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
    $root.opentelemetry = function() {
      var opentelemetry = {};
      opentelemetry.proto = function() {
        var proto = {};
        proto.common = function() {
          var common = {};
          common.v1 = function() {
            var v1 = {};
            v1.AnyValue = function() {
              function AnyValue(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(AnyValue, "AnyValue");
              AnyValue.prototype.stringValue = null;
              AnyValue.prototype.boolValue = null;
              AnyValue.prototype.intValue = null;
              AnyValue.prototype.doubleValue = null;
              AnyValue.prototype.arrayValue = null;
              AnyValue.prototype.kvlistValue = null;
              AnyValue.prototype.bytesValue = null;
              var $oneOfFields;
              Object.defineProperty(AnyValue.prototype, "value", {
                get: $util.oneOfGetter($oneOfFields = ["stringValue", "boolValue", "intValue", "doubleValue", "arrayValue", "kvlistValue", "bytesValue"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              AnyValue.create = /* @__PURE__ */ __name(function create(properties) {
                return new AnyValue(properties);
              }, "create");
              AnyValue.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.stringValue != null && Object.hasOwnProperty.call(message, "stringValue"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.stringValue);
                if (message.boolValue != null && Object.hasOwnProperty.call(message, "boolValue"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).bool(message.boolValue);
                if (message.intValue != null && Object.hasOwnProperty.call(message, "intValue"))
                  writer.uint32(
                    /* id 3, wireType 0 =*/
                    24
                  ).int64(message.intValue);
                if (message.doubleValue != null && Object.hasOwnProperty.call(message, "doubleValue"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).double(message.doubleValue);
                if (message.arrayValue != null && Object.hasOwnProperty.call(message, "arrayValue"))
                  $root.opentelemetry.proto.common.v1.ArrayValue.encode(message.arrayValue, writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).fork()).ldelim();
                if (message.kvlistValue != null && Object.hasOwnProperty.call(message, "kvlistValue"))
                  $root.opentelemetry.proto.common.v1.KeyValueList.encode(message.kvlistValue, writer.uint32(
                    /* id 6, wireType 2 =*/
                    50
                  ).fork()).ldelim();
                if (message.bytesValue != null && Object.hasOwnProperty.call(message, "bytesValue"))
                  writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).bytes(message.bytesValue);
                return writer;
              }, "encode");
              AnyValue.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              AnyValue.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.AnyValue();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.stringValue = reader.string();
                      break;
                    }
                    case 2: {
                      message.boolValue = reader.bool();
                      break;
                    }
                    case 3: {
                      message.intValue = reader.int64();
                      break;
                    }
                    case 4: {
                      message.doubleValue = reader.double();
                      break;
                    }
                    case 5: {
                      message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.decode(reader, reader.uint32());
                      break;
                    }
                    case 6: {
                      message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.decode(reader, reader.uint32());
                      break;
                    }
                    case 7: {
                      message.bytesValue = reader.bytes();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              AnyValue.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              AnyValue.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.stringValue != null && message.hasOwnProperty("stringValue")) {
                  properties.value = 1;
                  if (!$util.isString(message.stringValue))
                    return "stringValue: string expected";
                }
                if (message.boolValue != null && message.hasOwnProperty("boolValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (typeof message.boolValue !== "boolean")
                    return "boolValue: boolean expected";
                }
                if (message.intValue != null && message.hasOwnProperty("intValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!$util.isInteger(message.intValue) && !(message.intValue && $util.isInteger(message.intValue.low) && $util.isInteger(message.intValue.high)))
                    return "intValue: integer|Long expected";
                }
                if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (typeof message.doubleValue !== "number")
                    return "doubleValue: number expected";
                }
                if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  {
                    var error = $root.opentelemetry.proto.common.v1.ArrayValue.verify(message.arrayValue);
                    if (error)
                      return "arrayValue." + error;
                  }
                }
                if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  {
                    var error = $root.opentelemetry.proto.common.v1.KeyValueList.verify(message.kvlistValue);
                    if (error)
                      return "kvlistValue." + error;
                  }
                }
                if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!(message.bytesValue && typeof message.bytesValue.length === "number" || $util.isString(message.bytesValue)))
                    return "bytesValue: buffer expected";
                }
                return null;
              }, "verify");
              AnyValue.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.AnyValue)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.AnyValue();
                if (object.stringValue != null)
                  message.stringValue = String(object.stringValue);
                if (object.boolValue != null)
                  message.boolValue = Boolean(object.boolValue);
                if (object.intValue != null) {
                  if ($util.Long)
                    (message.intValue = $util.Long.fromValue(object.intValue)).unsigned = false;
                  else if (typeof object.intValue === "string")
                    message.intValue = parseInt(object.intValue, 10);
                  else if (typeof object.intValue === "number")
                    message.intValue = object.intValue;
                  else if (typeof object.intValue === "object")
                    message.intValue = new $util.LongBits(object.intValue.low >>> 0, object.intValue.high >>> 0).toNumber();
                }
                if (object.doubleValue != null)
                  message.doubleValue = Number(object.doubleValue);
                if (object.arrayValue != null) {
                  if (typeof object.arrayValue !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.AnyValue.arrayValue: object expected");
                  message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.fromObject(object.arrayValue);
                }
                if (object.kvlistValue != null) {
                  if (typeof object.kvlistValue !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.AnyValue.kvlistValue: object expected");
                  message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.fromObject(object.kvlistValue);
                }
                if (object.bytesValue != null) {
                  if (typeof object.bytesValue === "string")
                    $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0);
                  else if (object.bytesValue.length >= 0)
                    message.bytesValue = object.bytesValue;
                }
                return message;
              }, "fromObject");
              AnyValue.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (message.stringValue != null && message.hasOwnProperty("stringValue")) {
                  object.stringValue = message.stringValue;
                  if (options.oneofs)
                    object.value = "stringValue";
                }
                if (message.boolValue != null && message.hasOwnProperty("boolValue")) {
                  object.boolValue = message.boolValue;
                  if (options.oneofs)
                    object.value = "boolValue";
                }
                if (message.intValue != null && message.hasOwnProperty("intValue")) {
                  if (typeof message.intValue === "number")
                    object.intValue = options.longs === String ? String(message.intValue) : message.intValue;
                  else
                    object.intValue = options.longs === String ? $util.Long.prototype.toString.call(message.intValue) : options.longs === Number ? new $util.LongBits(message.intValue.low >>> 0, message.intValue.high >>> 0).toNumber() : message.intValue;
                  if (options.oneofs)
                    object.value = "intValue";
                }
                if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) {
                  object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue;
                  if (options.oneofs)
                    object.value = "doubleValue";
                }
                if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) {
                  object.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.toObject(message.arrayValue, options);
                  if (options.oneofs)
                    object.value = "arrayValue";
                }
                if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) {
                  object.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.toObject(message.kvlistValue, options);
                  if (options.oneofs)
                    object.value = "kvlistValue";
                }
                if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) {
                  object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue;
                  if (options.oneofs)
                    object.value = "bytesValue";
                }
                return object;
              }, "toObject");
              AnyValue.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              AnyValue.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.AnyValue";
              }, "getTypeUrl");
              return AnyValue;
            }();
            v1.ArrayValue = function() {
              function ArrayValue(properties) {
                this.values = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ArrayValue, "ArrayValue");
              ArrayValue.prototype.values = $util.emptyArray;
              ArrayValue.create = /* @__PURE__ */ __name(function create(properties) {
                return new ArrayValue(properties);
              }, "create");
              ArrayValue.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.values != null && message.values.length)
                  for (var i = 0; i < message.values.length; ++i)
                    $root.opentelemetry.proto.common.v1.AnyValue.encode(message.values[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              ArrayValue.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ArrayValue.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.ArrayValue();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.values && message.values.length))
                        message.values = [];
                      message.values.push($root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ArrayValue.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ArrayValue.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.values != null && message.hasOwnProperty("values")) {
                  if (!Array.isArray(message.values))
                    return "values: array expected";
                  for (var i = 0; i < message.values.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.values[i]);
                    if (error)
                      return "values." + error;
                  }
                }
                return null;
              }, "verify");
              ArrayValue.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.ArrayValue)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.ArrayValue();
                if (object.values) {
                  if (!Array.isArray(object.values))
                    throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: array expected");
                  message.values = [];
                  for (var i = 0; i < object.values.length; ++i) {
                    if (typeof object.values[i] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: object expected");
                    message.values[i] = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.values[i]);
                  }
                }
                return message;
              }, "fromObject");
              ArrayValue.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.values = [];
                if (message.values && message.values.length) {
                  object.values = [];
                  for (var j = 0; j < message.values.length; ++j)
                    object.values[j] = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.values[j], options);
                }
                return object;
              }, "toObject");
              ArrayValue.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ArrayValue.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.ArrayValue";
              }, "getTypeUrl");
              return ArrayValue;
            }();
            v1.KeyValueList = function() {
              function KeyValueList(properties) {
                this.values = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(KeyValueList, "KeyValueList");
              KeyValueList.prototype.values = $util.emptyArray;
              KeyValueList.create = /* @__PURE__ */ __name(function create(properties) {
                return new KeyValueList(properties);
              }, "create");
              KeyValueList.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.values != null && message.values.length)
                  for (var i = 0; i < message.values.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.values[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              KeyValueList.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              KeyValueList.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValueList();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.values && message.values.length))
                        message.values = [];
                      message.values.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              KeyValueList.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              KeyValueList.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.values != null && message.hasOwnProperty("values")) {
                  if (!Array.isArray(message.values))
                    return "values: array expected";
                  for (var i = 0; i < message.values.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.values[i]);
                    if (error)
                      return "values." + error;
                  }
                }
                return null;
              }, "verify");
              KeyValueList.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.KeyValueList)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.KeyValueList();
                if (object.values) {
                  if (!Array.isArray(object.values))
                    throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: array expected");
                  message.values = [];
                  for (var i = 0; i < object.values.length; ++i) {
                    if (typeof object.values[i] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: object expected");
                    message.values[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.values[i]);
                  }
                }
                return message;
              }, "fromObject");
              KeyValueList.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.values = [];
                if (message.values && message.values.length) {
                  object.values = [];
                  for (var j = 0; j < message.values.length; ++j)
                    object.values[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.values[j], options);
                }
                return object;
              }, "toObject");
              KeyValueList.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              KeyValueList.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValueList";
              }, "getTypeUrl");
              return KeyValueList;
            }();
            v1.KeyValue = function() {
              function KeyValue(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(KeyValue, "KeyValue");
              KeyValue.prototype.key = null;
              KeyValue.prototype.value = null;
              KeyValue.create = /* @__PURE__ */ __name(function create(properties) {
                return new KeyValue(properties);
              }, "create");
              KeyValue.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.key != null && Object.hasOwnProperty.call(message, "key"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.key);
                if (message.value != null && Object.hasOwnProperty.call(message, "value"))
                  $root.opentelemetry.proto.common.v1.AnyValue.encode(message.value, writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).fork()).ldelim();
                return writer;
              }, "encode");
              KeyValue.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              KeyValue.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValue();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.key = reader.string();
                      break;
                    }
                    case 2: {
                      message.value = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32());
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              KeyValue.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              KeyValue.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.key != null && message.hasOwnProperty("key")) {
                  if (!$util.isString(message.key))
                    return "key: string expected";
                }
                if (message.value != null && message.hasOwnProperty("value")) {
                  var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.value);
                  if (error)
                    return "value." + error;
                }
                return null;
              }, "verify");
              KeyValue.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.KeyValue)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.KeyValue();
                if (object.key != null)
                  message.key = String(object.key);
                if (object.value != null) {
                  if (typeof object.value !== "object")
                    throw TypeError(".opentelemetry.proto.common.v1.KeyValue.value: object expected");
                  message.value = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.value);
                }
                return message;
              }, "fromObject");
              KeyValue.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.defaults) {
                  object.key = "";
                  object.value = null;
                }
                if (message.key != null && message.hasOwnProperty("key"))
                  object.key = message.key;
                if (message.value != null && message.hasOwnProperty("value"))
                  object.value = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.value, options);
                return object;
              }, "toObject");
              KeyValue.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              KeyValue.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValue";
              }, "getTypeUrl");
              return KeyValue;
            }();
            v1.InstrumentationScope = function() {
              function InstrumentationScope(properties) {
                this.attributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(InstrumentationScope, "InstrumentationScope");
              InstrumentationScope.prototype.name = null;
              InstrumentationScope.prototype.version = null;
              InstrumentationScope.prototype.attributes = $util.emptyArray;
              InstrumentationScope.prototype.droppedAttributesCount = null;
              InstrumentationScope.create = /* @__PURE__ */ __name(function create(properties) {
                return new InstrumentationScope(properties);
              }, "create");
              InstrumentationScope.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.name);
                if (message.version != null && Object.hasOwnProperty.call(message, "version"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.version);
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 4, wireType 0 =*/
                    32
                  ).uint32(message.droppedAttributesCount);
                return writer;
              }, "encode");
              InstrumentationScope.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              InstrumentationScope.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.InstrumentationScope();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.name = reader.string();
                      break;
                    }
                    case 2: {
                      message.version = reader.string();
                      break;
                    }
                    case 3: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 4: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              InstrumentationScope.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              InstrumentationScope.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.name != null && message.hasOwnProperty("name")) {
                  if (!$util.isString(message.name))
                    return "name: string expected";
                }
                if (message.version != null && message.hasOwnProperty("version")) {
                  if (!$util.isString(message.version))
                    return "version: string expected";
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                return null;
              }, "verify");
              InstrumentationScope.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.InstrumentationScope)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.InstrumentationScope();
                if (object.name != null)
                  message.name = String(object.name);
                if (object.version != null)
                  message.version = String(object.version);
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                return message;
              }, "fromObject");
              InstrumentationScope.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.attributes = [];
                if (options.defaults) {
                  object.name = "";
                  object.version = "";
                  object.droppedAttributesCount = 0;
                }
                if (message.name != null && message.hasOwnProperty("name"))
                  object.name = message.name;
                if (message.version != null && message.hasOwnProperty("version"))
                  object.version = message.version;
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                return object;
              }, "toObject");
              InstrumentationScope.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              InstrumentationScope.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.InstrumentationScope";
              }, "getTypeUrl");
              return InstrumentationScope;
            }();
            v1.EntityRef = function() {
              function EntityRef(properties) {
                this.idKeys = [];
                this.descriptionKeys = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(EntityRef, "EntityRef");
              EntityRef.prototype.schemaUrl = null;
              EntityRef.prototype.type = null;
              EntityRef.prototype.idKeys = $util.emptyArray;
              EntityRef.prototype.descriptionKeys = $util.emptyArray;
              EntityRef.create = /* @__PURE__ */ __name(function create(properties) {
                return new EntityRef(properties);
              }, "create");
              EntityRef.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.schemaUrl);
                if (message.type != null && Object.hasOwnProperty.call(message, "type"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.type);
                if (message.idKeys != null && message.idKeys.length)
                  for (var i = 0; i < message.idKeys.length; ++i)
                    writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).string(message.idKeys[i]);
                if (message.descriptionKeys != null && message.descriptionKeys.length)
                  for (var i = 0; i < message.descriptionKeys.length; ++i)
                    writer.uint32(
                      /* id 4, wireType 2 =*/
                      34
                    ).string(message.descriptionKeys[i]);
                return writer;
              }, "encode");
              EntityRef.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              EntityRef.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.EntityRef();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    case 2: {
                      message.type = reader.string();
                      break;
                    }
                    case 3: {
                      if (!(message.idKeys && message.idKeys.length))
                        message.idKeys = [];
                      message.idKeys.push(reader.string());
                      break;
                    }
                    case 4: {
                      if (!(message.descriptionKeys && message.descriptionKeys.length))
                        message.descriptionKeys = [];
                      message.descriptionKeys.push(reader.string());
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              EntityRef.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              EntityRef.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                if (message.type != null && message.hasOwnProperty("type")) {
                  if (!$util.isString(message.type))
                    return "type: string expected";
                }
                if (message.idKeys != null && message.hasOwnProperty("idKeys")) {
                  if (!Array.isArray(message.idKeys))
                    return "idKeys: array expected";
                  for (var i = 0; i < message.idKeys.length; ++i)
                    if (!$util.isString(message.idKeys[i]))
                      return "idKeys: string[] expected";
                }
                if (message.descriptionKeys != null && message.hasOwnProperty("descriptionKeys")) {
                  if (!Array.isArray(message.descriptionKeys))
                    return "descriptionKeys: array expected";
                  for (var i = 0; i < message.descriptionKeys.length; ++i)
                    if (!$util.isString(message.descriptionKeys[i]))
                      return "descriptionKeys: string[] expected";
                }
                return null;
              }, "verify");
              EntityRef.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.common.v1.EntityRef)
                  return object;
                var message = new $root.opentelemetry.proto.common.v1.EntityRef();
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                if (object.type != null)
                  message.type = String(object.type);
                if (object.idKeys) {
                  if (!Array.isArray(object.idKeys))
                    throw TypeError(".opentelemetry.proto.common.v1.EntityRef.idKeys: array expected");
                  message.idKeys = [];
                  for (var i = 0; i < object.idKeys.length; ++i)
                    message.idKeys[i] = String(object.idKeys[i]);
                }
                if (object.descriptionKeys) {
                  if (!Array.isArray(object.descriptionKeys))
                    throw TypeError(".opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected");
                  message.descriptionKeys = [];
                  for (var i = 0; i < object.descriptionKeys.length; ++i)
                    message.descriptionKeys[i] = String(object.descriptionKeys[i]);
                }
                return message;
              }, "fromObject");
              EntityRef.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults) {
                  object.idKeys = [];
                  object.descriptionKeys = [];
                }
                if (options.defaults) {
                  object.schemaUrl = "";
                  object.type = "";
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                if (message.type != null && message.hasOwnProperty("type"))
                  object.type = message.type;
                if (message.idKeys && message.idKeys.length) {
                  object.idKeys = [];
                  for (var j = 0; j < message.idKeys.length; ++j)
                    object.idKeys[j] = message.idKeys[j];
                }
                if (message.descriptionKeys && message.descriptionKeys.length) {
                  object.descriptionKeys = [];
                  for (var j = 0; j < message.descriptionKeys.length; ++j)
                    object.descriptionKeys[j] = message.descriptionKeys[j];
                }
                return object;
              }, "toObject");
              EntityRef.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              EntityRef.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.common.v1.EntityRef";
              }, "getTypeUrl");
              return EntityRef;
            }();
            return v1;
          }();
          return common;
        }();
        proto.resource = function() {
          var resource = {};
          resource.v1 = function() {
            var v1 = {};
            v1.Resource = function() {
              function Resource(properties) {
                this.attributes = [];
                this.entityRefs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Resource, "Resource");
              Resource.prototype.attributes = $util.emptyArray;
              Resource.prototype.droppedAttributesCount = null;
              Resource.prototype.entityRefs = $util.emptyArray;
              Resource.create = /* @__PURE__ */ __name(function create(properties) {
                return new Resource(properties);
              }, "create");
              Resource.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).uint32(message.droppedAttributesCount);
                if (message.entityRefs != null && message.entityRefs.length)
                  for (var i = 0; i < message.entityRefs.length; ++i)
                    $root.opentelemetry.proto.common.v1.EntityRef.encode(message.entityRefs[i], writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Resource.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Resource.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.resource.v1.Resource();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    case 3: {
                      if (!(message.entityRefs && message.entityRefs.length))
                        message.entityRefs = [];
                      message.entityRefs.push($root.opentelemetry.proto.common.v1.EntityRef.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Resource.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Resource.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                if (message.entityRefs != null && message.hasOwnProperty("entityRefs")) {
                  if (!Array.isArray(message.entityRefs))
                    return "entityRefs: array expected";
                  for (var i = 0; i < message.entityRefs.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.EntityRef.verify(message.entityRefs[i]);
                    if (error)
                      return "entityRefs." + error;
                  }
                }
                return null;
              }, "verify");
              Resource.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.resource.v1.Resource)
                  return object;
                var message = new $root.opentelemetry.proto.resource.v1.Resource();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                if (object.entityRefs) {
                  if (!Array.isArray(object.entityRefs))
                    throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: array expected");
                  message.entityRefs = [];
                  for (var i = 0; i < object.entityRefs.length; ++i) {
                    if (typeof object.entityRefs[i] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: object expected");
                    message.entityRefs[i] = $root.opentelemetry.proto.common.v1.EntityRef.fromObject(object.entityRefs[i]);
                  }
                }
                return message;
              }, "fromObject");
              Resource.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults) {
                  object.attributes = [];
                  object.entityRefs = [];
                }
                if (options.defaults)
                  object.droppedAttributesCount = 0;
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                if (message.entityRefs && message.entityRefs.length) {
                  object.entityRefs = [];
                  for (var j = 0; j < message.entityRefs.length; ++j)
                    object.entityRefs[j] = $root.opentelemetry.proto.common.v1.EntityRef.toObject(message.entityRefs[j], options);
                }
                return object;
              }, "toObject");
              Resource.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Resource.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.resource.v1.Resource";
              }, "getTypeUrl");
              return Resource;
            }();
            return v1;
          }();
          return resource;
        }();
        proto.trace = function() {
          var trace2 = {};
          trace2.v1 = function() {
            var v1 = {};
            v1.TracesData = function() {
              function TracesData(properties) {
                this.resourceSpans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(TracesData, "TracesData");
              TracesData.prototype.resourceSpans = $util.emptyArray;
              TracesData.create = /* @__PURE__ */ __name(function create(properties) {
                return new TracesData(properties);
              }, "create");
              TracesData.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceSpans != null && message.resourceSpans.length)
                  for (var i = 0; i < message.resourceSpans.length; ++i)
                    $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              TracesData.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              TracesData.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.TracesData();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.resourceSpans && message.resourceSpans.length))
                        message.resourceSpans = [];
                      message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              TracesData.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              TracesData.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) {
                  if (!Array.isArray(message.resourceSpans))
                    return "resourceSpans: array expected";
                  for (var i = 0; i < message.resourceSpans.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]);
                    if (error)
                      return "resourceSpans." + error;
                  }
                }
                return null;
              }, "verify");
              TracesData.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.TracesData)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.TracesData();
                if (object.resourceSpans) {
                  if (!Array.isArray(object.resourceSpans))
                    throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: array expected");
                  message.resourceSpans = [];
                  for (var i = 0; i < object.resourceSpans.length; ++i) {
                    if (typeof object.resourceSpans[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected");
                    message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]);
                  }
                }
                return message;
              }, "fromObject");
              TracesData.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.resourceSpans = [];
                if (message.resourceSpans && message.resourceSpans.length) {
                  object.resourceSpans = [];
                  for (var j = 0; j < message.resourceSpans.length; ++j)
                    object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options);
                }
                return object;
              }, "toObject");
              TracesData.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              TracesData.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.TracesData";
              }, "getTypeUrl");
              return TracesData;
            }();
            v1.ResourceSpans = function() {
              function ResourceSpans(properties) {
                this.scopeSpans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ResourceSpans, "ResourceSpans");
              ResourceSpans.prototype.resource = null;
              ResourceSpans.prototype.scopeSpans = $util.emptyArray;
              ResourceSpans.prototype.schemaUrl = null;
              ResourceSpans.create = /* @__PURE__ */ __name(function create(properties) {
                return new ResourceSpans(properties);
              }, "create");
              ResourceSpans.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resource != null && Object.hasOwnProperty.call(message, "resource"))
                  $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.scopeSpans != null && message.scopeSpans.length)
                  for (var i = 0; i < message.scopeSpans.length; ++i)
                    $root.opentelemetry.proto.trace.v1.ScopeSpans.encode(message.scopeSpans[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ResourceSpans.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ResourceSpans.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ResourceSpans();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.scopeSpans && message.scopeSpans.length))
                        message.scopeSpans = [];
                      message.scopeSpans.push($root.opentelemetry.proto.trace.v1.ScopeSpans.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ResourceSpans.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ResourceSpans.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resource != null && message.hasOwnProperty("resource")) {
                  var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error)
                    return "resource." + error;
                }
                if (message.scopeSpans != null && message.hasOwnProperty("scopeSpans")) {
                  if (!Array.isArray(message.scopeSpans))
                    return "scopeSpans: array expected";
                  for (var i = 0; i < message.scopeSpans.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.ScopeSpans.verify(message.scopeSpans[i]);
                    if (error)
                      return "scopeSpans." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ResourceSpans.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.ResourceSpans)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.ResourceSpans();
                if (object.resource != null) {
                  if (typeof object.resource !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource);
                }
                if (object.scopeSpans) {
                  if (!Array.isArray(object.scopeSpans))
                    throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: array expected");
                  message.scopeSpans = [];
                  for (var i = 0; i < object.scopeSpans.length; ++i) {
                    if (typeof object.scopeSpans[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected");
                    message.scopeSpans[i] = $root.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(object.scopeSpans[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ResourceSpans.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.scopeSpans = [];
                if (options.defaults) {
                  object.resource = null;
                  object.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options);
                if (message.scopeSpans && message.scopeSpans.length) {
                  object.scopeSpans = [];
                  for (var j = 0; j < message.scopeSpans.length; ++j)
                    object.scopeSpans[j] = $root.opentelemetry.proto.trace.v1.ScopeSpans.toObject(message.scopeSpans[j], options);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ResourceSpans.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ResourceSpans.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ResourceSpans";
              }, "getTypeUrl");
              return ResourceSpans;
            }();
            v1.ScopeSpans = function() {
              function ScopeSpans(properties) {
                this.spans = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ScopeSpans, "ScopeSpans");
              ScopeSpans.prototype.scope = null;
              ScopeSpans.prototype.spans = $util.emptyArray;
              ScopeSpans.prototype.schemaUrl = null;
              ScopeSpans.create = /* @__PURE__ */ __name(function create(properties) {
                return new ScopeSpans(properties);
              }, "create");
              ScopeSpans.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.scope != null && Object.hasOwnProperty.call(message, "scope"))
                  $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.spans != null && message.spans.length)
                  for (var i = 0; i < message.spans.length; ++i)
                    $root.opentelemetry.proto.trace.v1.Span.encode(message.spans[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ScopeSpans.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ScopeSpans.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ScopeSpans();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.spans && message.spans.length))
                        message.spans = [];
                      message.spans.push($root.opentelemetry.proto.trace.v1.Span.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ScopeSpans.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ScopeSpans.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.scope != null && message.hasOwnProperty("scope")) {
                  var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error)
                    return "scope." + error;
                }
                if (message.spans != null && message.hasOwnProperty("spans")) {
                  if (!Array.isArray(message.spans))
                    return "spans: array expected";
                  for (var i = 0; i < message.spans.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.Span.verify(message.spans[i]);
                    if (error)
                      return "spans." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ScopeSpans.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.ScopeSpans)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.ScopeSpans();
                if (object.scope != null) {
                  if (typeof object.scope !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope);
                }
                if (object.spans) {
                  if (!Array.isArray(object.spans))
                    throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: array expected");
                  message.spans = [];
                  for (var i = 0; i < object.spans.length; ++i) {
                    if (typeof object.spans[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected");
                    message.spans[i] = $root.opentelemetry.proto.trace.v1.Span.fromObject(object.spans[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ScopeSpans.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.spans = [];
                if (options.defaults) {
                  object.scope = null;
                  object.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options);
                if (message.spans && message.spans.length) {
                  object.spans = [];
                  for (var j = 0; j < message.spans.length; ++j)
                    object.spans[j] = $root.opentelemetry.proto.trace.v1.Span.toObject(message.spans[j], options);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ScopeSpans.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ScopeSpans.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ScopeSpans";
              }, "getTypeUrl");
              return ScopeSpans;
            }();
            v1.Span = function() {
              function Span(properties) {
                this.attributes = [];
                this.events = [];
                this.links = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Span, "Span");
              Span.prototype.traceId = null;
              Span.prototype.spanId = null;
              Span.prototype.traceState = null;
              Span.prototype.parentSpanId = null;
              Span.prototype.flags = null;
              Span.prototype.name = null;
              Span.prototype.kind = null;
              Span.prototype.startTimeUnixNano = null;
              Span.prototype.endTimeUnixNano = null;
              Span.prototype.attributes = $util.emptyArray;
              Span.prototype.droppedAttributesCount = null;
              Span.prototype.events = $util.emptyArray;
              Span.prototype.droppedEventsCount = null;
              Span.prototype.links = $util.emptyArray;
              Span.prototype.droppedLinksCount = null;
              Span.prototype.status = null;
              Span.create = /* @__PURE__ */ __name(function create(properties) {
                return new Span(properties);
              }, "create");
              Span.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).bytes(message.traceId);
                if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).bytes(message.spanId);
                if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.traceState);
                if (message.parentSpanId != null && Object.hasOwnProperty.call(message, "parentSpanId"))
                  writer.uint32(
                    /* id 4, wireType 2 =*/
                    34
                  ).bytes(message.parentSpanId);
                if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                  writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).string(message.name);
                if (message.kind != null && Object.hasOwnProperty.call(message, "kind"))
                  writer.uint32(
                    /* id 6, wireType 0 =*/
                    48
                  ).int32(message.kind);
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 7, wireType 1 =*/
                    57
                  ).fixed64(message.startTimeUnixNano);
                if (message.endTimeUnixNano != null && Object.hasOwnProperty.call(message, "endTimeUnixNano"))
                  writer.uint32(
                    /* id 8, wireType 1 =*/
                    65
                  ).fixed64(message.endTimeUnixNano);
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 9, wireType 2 =*/
                      74
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 10, wireType 0 =*/
                    80
                  ).uint32(message.droppedAttributesCount);
                if (message.events != null && message.events.length)
                  for (var i = 0; i < message.events.length; ++i)
                    $root.opentelemetry.proto.trace.v1.Span.Event.encode(message.events[i], writer.uint32(
                      /* id 11, wireType 2 =*/
                      90
                    ).fork()).ldelim();
                if (message.droppedEventsCount != null && Object.hasOwnProperty.call(message, "droppedEventsCount"))
                  writer.uint32(
                    /* id 12, wireType 0 =*/
                    96
                  ).uint32(message.droppedEventsCount);
                if (message.links != null && message.links.length)
                  for (var i = 0; i < message.links.length; ++i)
                    $root.opentelemetry.proto.trace.v1.Span.Link.encode(message.links[i], writer.uint32(
                      /* id 13, wireType 2 =*/
                      106
                    ).fork()).ldelim();
                if (message.droppedLinksCount != null && Object.hasOwnProperty.call(message, "droppedLinksCount"))
                  writer.uint32(
                    /* id 14, wireType 0 =*/
                    112
                  ).uint32(message.droppedLinksCount);
                if (message.status != null && Object.hasOwnProperty.call(message, "status"))
                  $root.opentelemetry.proto.trace.v1.Status.encode(message.status, writer.uint32(
                    /* id 15, wireType 2 =*/
                    122
                  ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 16, wireType 5 =*/
                    133
                  ).fixed32(message.flags);
                return writer;
              }, "encode");
              Span.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Span.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.traceId = reader.bytes();
                      break;
                    }
                    case 2: {
                      message.spanId = reader.bytes();
                      break;
                    }
                    case 3: {
                      message.traceState = reader.string();
                      break;
                    }
                    case 4: {
                      message.parentSpanId = reader.bytes();
                      break;
                    }
                    case 16: {
                      message.flags = reader.fixed32();
                      break;
                    }
                    case 5: {
                      message.name = reader.string();
                      break;
                    }
                    case 6: {
                      message.kind = reader.int32();
                      break;
                    }
                    case 7: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 8: {
                      message.endTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 9: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 10: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    case 11: {
                      if (!(message.events && message.events.length))
                        message.events = [];
                      message.events.push($root.opentelemetry.proto.trace.v1.Span.Event.decode(reader, reader.uint32()));
                      break;
                    }
                    case 12: {
                      message.droppedEventsCount = reader.uint32();
                      break;
                    }
                    case 13: {
                      if (!(message.links && message.links.length))
                        message.links = [];
                      message.links.push($root.opentelemetry.proto.trace.v1.Span.Link.decode(reader, reader.uint32()));
                      break;
                    }
                    case 14: {
                      message.droppedLinksCount = reader.uint32();
                      break;
                    }
                    case 15: {
                      message.status = $root.opentelemetry.proto.trace.v1.Status.decode(reader, reader.uint32());
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Span.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Span.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.traceId != null && message.hasOwnProperty("traceId")) {
                  if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                    return "traceId: buffer expected";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId")) {
                  if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                    return "spanId: buffer expected";
                }
                if (message.traceState != null && message.hasOwnProperty("traceState")) {
                  if (!$util.isString(message.traceState))
                    return "traceState: string expected";
                }
                if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId")) {
                  if (!(message.parentSpanId && typeof message.parentSpanId.length === "number" || $util.isString(message.parentSpanId)))
                    return "parentSpanId: buffer expected";
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.name != null && message.hasOwnProperty("name")) {
                  if (!$util.isString(message.name))
                    return "name: string expected";
                }
                if (message.kind != null && message.hasOwnProperty("kind"))
                  switch (message.kind) {
                    default:
                      return "kind: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                      break;
                  }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano")) {
                  if (!$util.isInteger(message.endTimeUnixNano) && !(message.endTimeUnixNano && $util.isInteger(message.endTimeUnixNano.low) && $util.isInteger(message.endTimeUnixNano.high)))
                    return "endTimeUnixNano: integer|Long expected";
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                if (message.events != null && message.hasOwnProperty("events")) {
                  if (!Array.isArray(message.events))
                    return "events: array expected";
                  for (var i = 0; i < message.events.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.Span.Event.verify(message.events[i]);
                    if (error)
                      return "events." + error;
                  }
                }
                if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount")) {
                  if (!$util.isInteger(message.droppedEventsCount))
                    return "droppedEventsCount: integer expected";
                }
                if (message.links != null && message.hasOwnProperty("links")) {
                  if (!Array.isArray(message.links))
                    return "links: array expected";
                  for (var i = 0; i < message.links.length; ++i) {
                    var error = $root.opentelemetry.proto.trace.v1.Span.Link.verify(message.links[i]);
                    if (error)
                      return "links." + error;
                  }
                }
                if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) {
                  if (!$util.isInteger(message.droppedLinksCount))
                    return "droppedLinksCount: integer expected";
                }
                if (message.status != null && message.hasOwnProperty("status")) {
                  var error = $root.opentelemetry.proto.trace.v1.Status.verify(message.status);
                  if (error)
                    return "status." + error;
                }
                return null;
              }, "verify");
              Span.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.Span)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.Span();
                if (object.traceId != null) {
                  if (typeof object.traceId === "string")
                    $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                  else if (object.traceId.length >= 0)
                    message.traceId = object.traceId;
                }
                if (object.spanId != null) {
                  if (typeof object.spanId === "string")
                    $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                  else if (object.spanId.length >= 0)
                    message.spanId = object.spanId;
                }
                if (object.traceState != null)
                  message.traceState = String(object.traceState);
                if (object.parentSpanId != null) {
                  if (typeof object.parentSpanId === "string")
                    $util.base64.decode(object.parentSpanId, message.parentSpanId = $util.newBuffer($util.base64.length(object.parentSpanId)), 0);
                  else if (object.parentSpanId.length >= 0)
                    message.parentSpanId = object.parentSpanId;
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.name != null)
                  message.name = String(object.name);
                switch (object.kind) {
                  default:
                    if (typeof object.kind === "number") {
                      message.kind = object.kind;
                      break;
                    }
                    break;
                  case "SPAN_KIND_UNSPECIFIED":
                  case 0:
                    message.kind = 0;
                    break;
                  case "SPAN_KIND_INTERNAL":
                  case 1:
                    message.kind = 1;
                    break;
                  case "SPAN_KIND_SERVER":
                  case 2:
                    message.kind = 2;
                    break;
                  case "SPAN_KIND_CLIENT":
                  case 3:
                    message.kind = 3;
                    break;
                  case "SPAN_KIND_PRODUCER":
                  case 4:
                    message.kind = 4;
                    break;
                  case "SPAN_KIND_CONSUMER":
                  case 5:
                    message.kind = 5;
                    break;
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.endTimeUnixNano != null) {
                  if ($util.Long)
                    (message.endTimeUnixNano = $util.Long.fromValue(object.endTimeUnixNano)).unsigned = false;
                  else if (typeof object.endTimeUnixNano === "string")
                    message.endTimeUnixNano = parseInt(object.endTimeUnixNano, 10);
                  else if (typeof object.endTimeUnixNano === "number")
                    message.endTimeUnixNano = object.endTimeUnixNano;
                  else if (typeof object.endTimeUnixNano === "object")
                    message.endTimeUnixNano = new $util.LongBits(object.endTimeUnixNano.low >>> 0, object.endTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                if (object.events) {
                  if (!Array.isArray(object.events))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.events: array expected");
                  message.events = [];
                  for (var i = 0; i < object.events.length; ++i) {
                    if (typeof object.events[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.events: object expected");
                    message.events[i] = $root.opentelemetry.proto.trace.v1.Span.Event.fromObject(object.events[i]);
                  }
                }
                if (object.droppedEventsCount != null)
                  message.droppedEventsCount = object.droppedEventsCount >>> 0;
                if (object.links) {
                  if (!Array.isArray(object.links))
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.links: array expected");
                  message.links = [];
                  for (var i = 0; i < object.links.length; ++i) {
                    if (typeof object.links[i] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.links: object expected");
                    message.links[i] = $root.opentelemetry.proto.trace.v1.Span.Link.fromObject(object.links[i]);
                  }
                }
                if (object.droppedLinksCount != null)
                  message.droppedLinksCount = object.droppedLinksCount >>> 0;
                if (object.status != null) {
                  if (typeof object.status !== "object")
                    throw TypeError(".opentelemetry.proto.trace.v1.Span.status: object expected");
                  message.status = $root.opentelemetry.proto.trace.v1.Status.fromObject(object.status);
                }
                return message;
              }, "fromObject");
              Span.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults) {
                  object.attributes = [];
                  object.events = [];
                  object.links = [];
                }
                if (options.defaults) {
                  if (options.bytes === String)
                    object.traceId = "";
                  else {
                    object.traceId = [];
                    if (options.bytes !== Array)
                      object.traceId = $util.newBuffer(object.traceId);
                  }
                  if (options.bytes === String)
                    object.spanId = "";
                  else {
                    object.spanId = [];
                    if (options.bytes !== Array)
                      object.spanId = $util.newBuffer(object.spanId);
                  }
                  object.traceState = "";
                  if (options.bytes === String)
                    object.parentSpanId = "";
                  else {
                    object.parentSpanId = [];
                    if (options.bytes !== Array)
                      object.parentSpanId = $util.newBuffer(object.parentSpanId);
                  }
                  object.name = "";
                  object.kind = options.enums === String ? "SPAN_KIND_UNSPECIFIED" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.endTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.endTimeUnixNano = options.longs === String ? "0" : 0;
                  object.droppedAttributesCount = 0;
                  object.droppedEventsCount = 0;
                  object.droppedLinksCount = 0;
                  object.status = null;
                  object.flags = 0;
                }
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                if (message.spanId != null && message.hasOwnProperty("spanId"))
                  object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                if (message.traceState != null && message.hasOwnProperty("traceState"))
                  object.traceState = message.traceState;
                if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId"))
                  object.parentSpanId = options.bytes === String ? $util.base64.encode(message.parentSpanId, 0, message.parentSpanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.parentSpanId) : message.parentSpanId;
                if (message.name != null && message.hasOwnProperty("name"))
                  object.name = message.name;
                if (message.kind != null && message.hasOwnProperty("kind"))
                  object.kind = options.enums === String ? $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] === void 0 ? message.kind : $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] : message.kind;
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano"))
                  if (typeof message.endTimeUnixNano === "number")
                    object.endTimeUnixNano = options.longs === String ? String(message.endTimeUnixNano) : message.endTimeUnixNano;
                  else
                    object.endTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.endTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.endTimeUnixNano.low >>> 0, message.endTimeUnixNano.high >>> 0).toNumber() : message.endTimeUnixNano;
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                if (message.events && message.events.length) {
                  object.events = [];
                  for (var j = 0; j < message.events.length; ++j)
                    object.events[j] = $root.opentelemetry.proto.trace.v1.Span.Event.toObject(message.events[j], options);
                }
                if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount"))
                  object.droppedEventsCount = message.droppedEventsCount;
                if (message.links && message.links.length) {
                  object.links = [];
                  for (var j = 0; j < message.links.length; ++j)
                    object.links[j] = $root.opentelemetry.proto.trace.v1.Span.Link.toObject(message.links[j], options);
                }
                if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount"))
                  object.droppedLinksCount = message.droppedLinksCount;
                if (message.status != null && message.hasOwnProperty("status"))
                  object.status = $root.opentelemetry.proto.trace.v1.Status.toObject(message.status, options);
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                return object;
              }, "toObject");
              Span.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Span.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span";
              }, "getTypeUrl");
              Span.SpanKind = function() {
                var valuesById = {}, values = Object.create(valuesById);
                values[valuesById[0] = "SPAN_KIND_UNSPECIFIED"] = 0;
                values[valuesById[1] = "SPAN_KIND_INTERNAL"] = 1;
                values[valuesById[2] = "SPAN_KIND_SERVER"] = 2;
                values[valuesById[3] = "SPAN_KIND_CLIENT"] = 3;
                values[valuesById[4] = "SPAN_KIND_PRODUCER"] = 4;
                values[valuesById[5] = "SPAN_KIND_CONSUMER"] = 5;
                return values;
              }();
              Span.Event = function() {
                function Event(properties) {
                  this.attributes = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(Event, "Event");
                Event.prototype.timeUnixNano = null;
                Event.prototype.name = null;
                Event.prototype.attributes = $util.emptyArray;
                Event.prototype.droppedAttributesCount = null;
                Event.create = /* @__PURE__ */ __name(function create(properties) {
                  return new Event(properties);
                }, "create");
                Event.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                    writer.uint32(
                      /* id 1, wireType 1 =*/
                      9
                    ).fixed64(message.timeUnixNano);
                  if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.name);
                  if (message.attributes != null && message.attributes.length)
                    for (var i = 0; i < message.attributes.length; ++i)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                        /* id 3, wireType 2 =*/
                        26
                      ).fork()).ldelim();
                  if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                    writer.uint32(
                      /* id 4, wireType 0 =*/
                      32
                    ).uint32(message.droppedAttributesCount);
                  return writer;
                }, "encode");
                Event.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                Event.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Event();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.timeUnixNano = reader.fixed64();
                        break;
                      }
                      case 2: {
                        message.name = reader.string();
                        break;
                      }
                      case 3: {
                        if (!(message.attributes && message.attributes.length))
                          message.attributes = [];
                        message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                        break;
                      }
                      case 4: {
                        message.droppedAttributesCount = reader.uint32();
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                Event.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                Event.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                    if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                      return "timeUnixNano: integer|Long expected";
                  }
                  if (message.name != null && message.hasOwnProperty("name")) {
                    if (!$util.isString(message.name))
                      return "name: string expected";
                  }
                  if (message.attributes != null && message.hasOwnProperty("attributes")) {
                    if (!Array.isArray(message.attributes))
                      return "attributes: array expected";
                    for (var i = 0; i < message.attributes.length; ++i) {
                      var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                      if (error)
                        return "attributes." + error;
                    }
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                    if (!$util.isInteger(message.droppedAttributesCount))
                      return "droppedAttributesCount: integer expected";
                  }
                  return null;
                }, "verify");
                Event.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Event)
                    return object;
                  var message = new $root.opentelemetry.proto.trace.v1.Span.Event();
                  if (object.timeUnixNano != null) {
                    if ($util.Long)
                      (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                    else if (typeof object.timeUnixNano === "string")
                      message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                    else if (typeof object.timeUnixNano === "number")
                      message.timeUnixNano = object.timeUnixNano;
                    else if (typeof object.timeUnixNano === "object")
                      message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                  }
                  if (object.name != null)
                    message.name = String(object.name);
                  if (object.attributes) {
                    if (!Array.isArray(object.attributes))
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: array expected");
                    message.attributes = [];
                    for (var i = 0; i < object.attributes.length; ++i) {
                      if (typeof object.attributes[i] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: object expected");
                      message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                    }
                  }
                  if (object.droppedAttributesCount != null)
                    message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                  return message;
                }, "fromObject");
                Event.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.arrays || options.defaults)
                    object.attributes = [];
                  if (options.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                    } else
                      object.timeUnixNano = options.longs === String ? "0" : 0;
                    object.name = "";
                    object.droppedAttributesCount = 0;
                  }
                  if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                    if (typeof message.timeUnixNano === "number")
                      object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                    else
                      object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                  if (message.name != null && message.hasOwnProperty("name"))
                    object.name = message.name;
                  if (message.attributes && message.attributes.length) {
                    object.attributes = [];
                    for (var j = 0; j < message.attributes.length; ++j)
                      object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                    object.droppedAttributesCount = message.droppedAttributesCount;
                  return object;
                }, "toObject");
                Event.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                Event.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Event";
                }, "getTypeUrl");
                return Event;
              }();
              Span.Link = function() {
                function Link(properties) {
                  this.attributes = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(Link, "Link");
                Link.prototype.traceId = null;
                Link.prototype.spanId = null;
                Link.prototype.traceState = null;
                Link.prototype.attributes = $util.emptyArray;
                Link.prototype.droppedAttributesCount = null;
                Link.prototype.flags = null;
                Link.create = /* @__PURE__ */ __name(function create(properties) {
                  return new Link(properties);
                }, "create");
                Link.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                    writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).bytes(message.traceId);
                  if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).bytes(message.spanId);
                  if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState"))
                    writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).string(message.traceState);
                  if (message.attributes != null && message.attributes.length)
                    for (var i = 0; i < message.attributes.length; ++i)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                        /* id 4, wireType 2 =*/
                        34
                      ).fork()).ldelim();
                  if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                    writer.uint32(
                      /* id 5, wireType 0 =*/
                      40
                    ).uint32(message.droppedAttributesCount);
                  if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                    writer.uint32(
                      /* id 6, wireType 5 =*/
                      53
                    ).fixed32(message.flags);
                  return writer;
                }, "encode");
                Link.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                Link.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Link();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.traceId = reader.bytes();
                        break;
                      }
                      case 2: {
                        message.spanId = reader.bytes();
                        break;
                      }
                      case 3: {
                        message.traceState = reader.string();
                        break;
                      }
                      case 4: {
                        if (!(message.attributes && message.attributes.length))
                          message.attributes = [];
                        message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                        break;
                      }
                      case 5: {
                        message.droppedAttributesCount = reader.uint32();
                        break;
                      }
                      case 6: {
                        message.flags = reader.fixed32();
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                Link.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                Link.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.traceId != null && message.hasOwnProperty("traceId")) {
                    if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                      return "traceId: buffer expected";
                  }
                  if (message.spanId != null && message.hasOwnProperty("spanId")) {
                    if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                      return "spanId: buffer expected";
                  }
                  if (message.traceState != null && message.hasOwnProperty("traceState")) {
                    if (!$util.isString(message.traceState))
                      return "traceState: string expected";
                  }
                  if (message.attributes != null && message.hasOwnProperty("attributes")) {
                    if (!Array.isArray(message.attributes))
                      return "attributes: array expected";
                    for (var i = 0; i < message.attributes.length; ++i) {
                      var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                      if (error)
                        return "attributes." + error;
                    }
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                    if (!$util.isInteger(message.droppedAttributesCount))
                      return "droppedAttributesCount: integer expected";
                  }
                  if (message.flags != null && message.hasOwnProperty("flags")) {
                    if (!$util.isInteger(message.flags))
                      return "flags: integer expected";
                  }
                  return null;
                }, "verify");
                Link.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Link)
                    return object;
                  var message = new $root.opentelemetry.proto.trace.v1.Span.Link();
                  if (object.traceId != null) {
                    if (typeof object.traceId === "string")
                      $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                    else if (object.traceId.length >= 0)
                      message.traceId = object.traceId;
                  }
                  if (object.spanId != null) {
                    if (typeof object.spanId === "string")
                      $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                    else if (object.spanId.length >= 0)
                      message.spanId = object.spanId;
                  }
                  if (object.traceState != null)
                    message.traceState = String(object.traceState);
                  if (object.attributes) {
                    if (!Array.isArray(object.attributes))
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: array expected");
                    message.attributes = [];
                    for (var i = 0; i < object.attributes.length; ++i) {
                      if (typeof object.attributes[i] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: object expected");
                      message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                    }
                  }
                  if (object.droppedAttributesCount != null)
                    message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                  if (object.flags != null)
                    message.flags = object.flags >>> 0;
                  return message;
                }, "fromObject");
                Link.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.arrays || options.defaults)
                    object.attributes = [];
                  if (options.defaults) {
                    if (options.bytes === String)
                      object.traceId = "";
                    else {
                      object.traceId = [];
                      if (options.bytes !== Array)
                        object.traceId = $util.newBuffer(object.traceId);
                    }
                    if (options.bytes === String)
                      object.spanId = "";
                    else {
                      object.spanId = [];
                      if (options.bytes !== Array)
                        object.spanId = $util.newBuffer(object.spanId);
                    }
                    object.traceState = "";
                    object.droppedAttributesCount = 0;
                    object.flags = 0;
                  }
                  if (message.traceId != null && message.hasOwnProperty("traceId"))
                    object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                  if (message.spanId != null && message.hasOwnProperty("spanId"))
                    object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                  if (message.traceState != null && message.hasOwnProperty("traceState"))
                    object.traceState = message.traceState;
                  if (message.attributes && message.attributes.length) {
                    object.attributes = [];
                    for (var j = 0; j < message.attributes.length; ++j)
                      object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                  }
                  if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                    object.droppedAttributesCount = message.droppedAttributesCount;
                  if (message.flags != null && message.hasOwnProperty("flags"))
                    object.flags = message.flags;
                  return object;
                }, "toObject");
                Link.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                Link.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Link";
                }, "getTypeUrl");
                return Link;
              }();
              return Span;
            }();
            v1.Status = function() {
              function Status(properties) {
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Status, "Status");
              Status.prototype.message = null;
              Status.prototype.code = null;
              Status.create = /* @__PURE__ */ __name(function create(properties) {
                return new Status(properties);
              }, "create");
              Status.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.message != null && Object.hasOwnProperty.call(message, "message"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.message);
                if (message.code != null && Object.hasOwnProperty.call(message, "code"))
                  writer.uint32(
                    /* id 3, wireType 0 =*/
                    24
                  ).int32(message.code);
                return writer;
              }, "encode");
              Status.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Status.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Status();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 2: {
                      message.message = reader.string();
                      break;
                    }
                    case 3: {
                      message.code = reader.int32();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Status.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Status.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.message != null && message.hasOwnProperty("message")) {
                  if (!$util.isString(message.message))
                    return "message: string expected";
                }
                if (message.code != null && message.hasOwnProperty("code"))
                  switch (message.code) {
                    default:
                      return "code: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                return null;
              }, "verify");
              Status.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.trace.v1.Status)
                  return object;
                var message = new $root.opentelemetry.proto.trace.v1.Status();
                if (object.message != null)
                  message.message = String(object.message);
                switch (object.code) {
                  default:
                    if (typeof object.code === "number") {
                      message.code = object.code;
                      break;
                    }
                    break;
                  case "STATUS_CODE_UNSET":
                  case 0:
                    message.code = 0;
                    break;
                  case "STATUS_CODE_OK":
                  case 1:
                    message.code = 1;
                    break;
                  case "STATUS_CODE_ERROR":
                  case 2:
                    message.code = 2;
                    break;
                }
                return message;
              }, "fromObject");
              Status.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.defaults) {
                  object.message = "";
                  object.code = options.enums === String ? "STATUS_CODE_UNSET" : 0;
                }
                if (message.message != null && message.hasOwnProperty("message"))
                  object.message = message.message;
                if (message.code != null && message.hasOwnProperty("code"))
                  object.code = options.enums === String ? $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] === void 0 ? message.code : $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] : message.code;
                return object;
              }, "toObject");
              Status.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Status.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Status";
              }, "getTypeUrl");
              Status.StatusCode = function() {
                var valuesById = {}, values = Object.create(valuesById);
                values[valuesById[0] = "STATUS_CODE_UNSET"] = 0;
                values[valuesById[1] = "STATUS_CODE_OK"] = 1;
                values[valuesById[2] = "STATUS_CODE_ERROR"] = 2;
                return values;
              }();
              return Status;
            }();
            v1.SpanFlags = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "SPAN_FLAGS_DO_NOT_USE"] = 0;
              values[valuesById[255] = "SPAN_FLAGS_TRACE_FLAGS_MASK"] = 255;
              values[valuesById[256] = "SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK"] = 256;
              values[valuesById[512] = "SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK"] = 512;
              return values;
            }();
            return v1;
          }();
          return trace2;
        }();
        proto.collector = function() {
          var collector = {};
          collector.trace = function() {
            var trace2 = {};
            trace2.v1 = function() {
              var v1 = {};
              v1.TraceService = function() {
                function TraceService(rpcImpl, requestDelimited, responseDelimited) {
                  $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);
                }
                __name(TraceService, "TraceService");
                (TraceService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = TraceService;
                TraceService.create = /* @__PURE__ */ __name(function create(rpcImpl, requestDelimited, responseDelimited) {
                  return new this(rpcImpl, requestDelimited, responseDelimited);
                }, "create");
                Object.defineProperty(TraceService.prototype["export"] = /* @__PURE__ */ __name(function export_(request4, callback) {
                  return this.rpcCall(export_, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse, request4, callback);
                }, "export_"), "name", { value: "Export" });
                return TraceService;
              }();
              v1.ExportTraceServiceRequest = function() {
                function ExportTraceServiceRequest(properties) {
                  this.resourceSpans = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportTraceServiceRequest, "ExportTraceServiceRequest");
                ExportTraceServiceRequest.prototype.resourceSpans = $util.emptyArray;
                ExportTraceServiceRequest.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportTraceServiceRequest(properties);
                }, "create");
                ExportTraceServiceRequest.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceSpans != null && message.resourceSpans.length)
                    for (var i = 0; i < message.resourceSpans.length; ++i)
                      $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(
                        /* id 1, wireType 2 =*/
                        10
                      ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportTraceServiceRequest.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportTraceServiceRequest.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        if (!(message.resourceSpans && message.resourceSpans.length))
                          message.resourceSpans = [];
                        message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32()));
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportTraceServiceRequest.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportTraceServiceRequest.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) {
                    if (!Array.isArray(message.resourceSpans))
                      return "resourceSpans: array expected";
                    for (var i = 0; i < message.resourceSpans.length; ++i) {
                      var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]);
                      if (error)
                        return "resourceSpans." + error;
                    }
                  }
                  return null;
                }, "verify");
                ExportTraceServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest();
                  if (object.resourceSpans) {
                    if (!Array.isArray(object.resourceSpans))
                      throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: array expected");
                    message.resourceSpans = [];
                    for (var i = 0; i < object.resourceSpans.length; ++i) {
                      if (typeof object.resourceSpans[i] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected");
                      message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportTraceServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.arrays || options.defaults)
                    object.resourceSpans = [];
                  if (message.resourceSpans && message.resourceSpans.length) {
                    object.resourceSpans = [];
                    for (var j = 0; j < message.resourceSpans.length; ++j)
                      object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options);
                  }
                  return object;
                }, "toObject");
                ExportTraceServiceRequest.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportTraceServiceRequest.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest";
                }, "getTypeUrl");
                return ExportTraceServiceRequest;
              }();
              v1.ExportTraceServiceResponse = function() {
                function ExportTraceServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportTraceServiceResponse, "ExportTraceServiceResponse");
                ExportTraceServiceResponse.prototype.partialSuccess = null;
                ExportTraceServiceResponse.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportTraceServiceResponse(properties);
                }, "create");
                ExportTraceServiceResponse.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess"))
                    $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.encode(message.partialSuccess, writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportTraceServiceResponse.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportTraceServiceResponse.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.decode(reader, reader.uint32());
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportTraceServiceResponse.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportTraceServiceResponse.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) {
                    var error = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(message.partialSuccess);
                    if (error)
                      return "partialSuccess." + error;
                  }
                  return null;
                }, "verify");
                ExportTraceServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse();
                  if (object.partialSuccess != null) {
                    if (typeof object.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.fromObject(object.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportTraceServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.defaults)
                    object.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.toObject(message.partialSuccess, options);
                  return object;
                }, "toObject");
                ExportTraceServiceResponse.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportTraceServiceResponse.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse";
                }, "getTypeUrl");
                return ExportTraceServiceResponse;
              }();
              v1.ExportTracePartialSuccess = function() {
                function ExportTracePartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportTracePartialSuccess, "ExportTracePartialSuccess");
                ExportTracePartialSuccess.prototype.rejectedSpans = null;
                ExportTracePartialSuccess.prototype.errorMessage = null;
                ExportTracePartialSuccess.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportTracePartialSuccess(properties);
                }, "create");
                ExportTracePartialSuccess.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.rejectedSpans != null && Object.hasOwnProperty.call(message, "rejectedSpans"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).int64(message.rejectedSpans);
                  if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.errorMessage);
                  return writer;
                }, "encode");
                ExportTracePartialSuccess.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportTracePartialSuccess.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.rejectedSpans = reader.int64();
                        break;
                      }
                      case 2: {
                        message.errorMessage = reader.string();
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportTracePartialSuccess.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportTracePartialSuccess.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans")) {
                    if (!$util.isInteger(message.rejectedSpans) && !(message.rejectedSpans && $util.isInteger(message.rejectedSpans.low) && $util.isInteger(message.rejectedSpans.high)))
                      return "rejectedSpans: integer|Long expected";
                  }
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) {
                    if (!$util.isString(message.errorMessage))
                      return "errorMessage: string expected";
                  }
                  return null;
                }, "verify");
                ExportTracePartialSuccess.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess();
                  if (object.rejectedSpans != null) {
                    if ($util.Long)
                      (message.rejectedSpans = $util.Long.fromValue(object.rejectedSpans)).unsigned = false;
                    else if (typeof object.rejectedSpans === "string")
                      message.rejectedSpans = parseInt(object.rejectedSpans, 10);
                    else if (typeof object.rejectedSpans === "number")
                      message.rejectedSpans = object.rejectedSpans;
                    else if (typeof object.rejectedSpans === "object")
                      message.rejectedSpans = new $util.LongBits(object.rejectedSpans.low >>> 0, object.rejectedSpans.high >>> 0).toNumber();
                  }
                  if (object.errorMessage != null)
                    message.errorMessage = String(object.errorMessage);
                  return message;
                }, "fromObject");
                ExportTracePartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.rejectedSpans = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                    } else
                      object.rejectedSpans = options.longs === String ? "0" : 0;
                    object.errorMessage = "";
                  }
                  if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans"))
                    if (typeof message.rejectedSpans === "number")
                      object.rejectedSpans = options.longs === String ? String(message.rejectedSpans) : message.rejectedSpans;
                    else
                      object.rejectedSpans = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedSpans) : options.longs === Number ? new $util.LongBits(message.rejectedSpans.low >>> 0, message.rejectedSpans.high >>> 0).toNumber() : message.rejectedSpans;
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage"))
                    object.errorMessage = message.errorMessage;
                  return object;
                }, "toObject");
                ExportTracePartialSuccess.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportTracePartialSuccess.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess";
                }, "getTypeUrl");
                return ExportTracePartialSuccess;
              }();
              return v1;
            }();
            return trace2;
          }();
          collector.metrics = function() {
            var metrics2 = {};
            metrics2.v1 = function() {
              var v1 = {};
              v1.MetricsService = function() {
                function MetricsService(rpcImpl, requestDelimited, responseDelimited) {
                  $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);
                }
                __name(MetricsService, "MetricsService");
                (MetricsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = MetricsService;
                MetricsService.create = /* @__PURE__ */ __name(function create(rpcImpl, requestDelimited, responseDelimited) {
                  return new this(rpcImpl, requestDelimited, responseDelimited);
                }, "create");
                Object.defineProperty(MetricsService.prototype["export"] = /* @__PURE__ */ __name(function export_(request4, callback) {
                  return this.rpcCall(export_, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse, request4, callback);
                }, "export_"), "name", { value: "Export" });
                return MetricsService;
              }();
              v1.ExportMetricsServiceRequest = function() {
                function ExportMetricsServiceRequest(properties) {
                  this.resourceMetrics = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportMetricsServiceRequest, "ExportMetricsServiceRequest");
                ExportMetricsServiceRequest.prototype.resourceMetrics = $util.emptyArray;
                ExportMetricsServiceRequest.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportMetricsServiceRequest(properties);
                }, "create");
                ExportMetricsServiceRequest.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceMetrics != null && message.resourceMetrics.length)
                    for (var i = 0; i < message.resourceMetrics.length; ++i)
                      $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(
                        /* id 1, wireType 2 =*/
                        10
                      ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportMetricsServiceRequest.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportMetricsServiceRequest.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        if (!(message.resourceMetrics && message.resourceMetrics.length))
                          message.resourceMetrics = [];
                        message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32()));
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportMetricsServiceRequest.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportMetricsServiceRequest.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) {
                    if (!Array.isArray(message.resourceMetrics))
                      return "resourceMetrics: array expected";
                    for (var i = 0; i < message.resourceMetrics.length; ++i) {
                      var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]);
                      if (error)
                        return "resourceMetrics." + error;
                    }
                  }
                  return null;
                }, "verify");
                ExportMetricsServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest();
                  if (object.resourceMetrics) {
                    if (!Array.isArray(object.resourceMetrics))
                      throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: array expected");
                    message.resourceMetrics = [];
                    for (var i = 0; i < object.resourceMetrics.length; ++i) {
                      if (typeof object.resourceMetrics[i] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected");
                      message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportMetricsServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.arrays || options.defaults)
                    object.resourceMetrics = [];
                  if (message.resourceMetrics && message.resourceMetrics.length) {
                    object.resourceMetrics = [];
                    for (var j = 0; j < message.resourceMetrics.length; ++j)
                      object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options);
                  }
                  return object;
                }, "toObject");
                ExportMetricsServiceRequest.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportMetricsServiceRequest.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest";
                }, "getTypeUrl");
                return ExportMetricsServiceRequest;
              }();
              v1.ExportMetricsServiceResponse = function() {
                function ExportMetricsServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportMetricsServiceResponse, "ExportMetricsServiceResponse");
                ExportMetricsServiceResponse.prototype.partialSuccess = null;
                ExportMetricsServiceResponse.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportMetricsServiceResponse(properties);
                }, "create");
                ExportMetricsServiceResponse.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess"))
                    $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.encode(message.partialSuccess, writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportMetricsServiceResponse.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportMetricsServiceResponse.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.decode(reader, reader.uint32());
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportMetricsServiceResponse.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportMetricsServiceResponse.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) {
                    var error = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(message.partialSuccess);
                    if (error)
                      return "partialSuccess." + error;
                  }
                  return null;
                }, "verify");
                ExportMetricsServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse();
                  if (object.partialSuccess != null) {
                    if (typeof object.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.fromObject(object.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportMetricsServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.defaults)
                    object.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.toObject(message.partialSuccess, options);
                  return object;
                }, "toObject");
                ExportMetricsServiceResponse.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportMetricsServiceResponse.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse";
                }, "getTypeUrl");
                return ExportMetricsServiceResponse;
              }();
              v1.ExportMetricsPartialSuccess = function() {
                function ExportMetricsPartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportMetricsPartialSuccess, "ExportMetricsPartialSuccess");
                ExportMetricsPartialSuccess.prototype.rejectedDataPoints = null;
                ExportMetricsPartialSuccess.prototype.errorMessage = null;
                ExportMetricsPartialSuccess.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportMetricsPartialSuccess(properties);
                }, "create");
                ExportMetricsPartialSuccess.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.rejectedDataPoints != null && Object.hasOwnProperty.call(message, "rejectedDataPoints"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).int64(message.rejectedDataPoints);
                  if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.errorMessage);
                  return writer;
                }, "encode");
                ExportMetricsPartialSuccess.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportMetricsPartialSuccess.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.rejectedDataPoints = reader.int64();
                        break;
                      }
                      case 2: {
                        message.errorMessage = reader.string();
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportMetricsPartialSuccess.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportMetricsPartialSuccess.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints")) {
                    if (!$util.isInteger(message.rejectedDataPoints) && !(message.rejectedDataPoints && $util.isInteger(message.rejectedDataPoints.low) && $util.isInteger(message.rejectedDataPoints.high)))
                      return "rejectedDataPoints: integer|Long expected";
                  }
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) {
                    if (!$util.isString(message.errorMessage))
                      return "errorMessage: string expected";
                  }
                  return null;
                }, "verify");
                ExportMetricsPartialSuccess.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess();
                  if (object.rejectedDataPoints != null) {
                    if ($util.Long)
                      (message.rejectedDataPoints = $util.Long.fromValue(object.rejectedDataPoints)).unsigned = false;
                    else if (typeof object.rejectedDataPoints === "string")
                      message.rejectedDataPoints = parseInt(object.rejectedDataPoints, 10);
                    else if (typeof object.rejectedDataPoints === "number")
                      message.rejectedDataPoints = object.rejectedDataPoints;
                    else if (typeof object.rejectedDataPoints === "object")
                      message.rejectedDataPoints = new $util.LongBits(object.rejectedDataPoints.low >>> 0, object.rejectedDataPoints.high >>> 0).toNumber();
                  }
                  if (object.errorMessage != null)
                    message.errorMessage = String(object.errorMessage);
                  return message;
                }, "fromObject");
                ExportMetricsPartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.rejectedDataPoints = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                    } else
                      object.rejectedDataPoints = options.longs === String ? "0" : 0;
                    object.errorMessage = "";
                  }
                  if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints"))
                    if (typeof message.rejectedDataPoints === "number")
                      object.rejectedDataPoints = options.longs === String ? String(message.rejectedDataPoints) : message.rejectedDataPoints;
                    else
                      object.rejectedDataPoints = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedDataPoints) : options.longs === Number ? new $util.LongBits(message.rejectedDataPoints.low >>> 0, message.rejectedDataPoints.high >>> 0).toNumber() : message.rejectedDataPoints;
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage"))
                    object.errorMessage = message.errorMessage;
                  return object;
                }, "toObject");
                ExportMetricsPartialSuccess.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportMetricsPartialSuccess.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess";
                }, "getTypeUrl");
                return ExportMetricsPartialSuccess;
              }();
              return v1;
            }();
            return metrics2;
          }();
          collector.logs = function() {
            var logs3 = {};
            logs3.v1 = function() {
              var v1 = {};
              v1.LogsService = function() {
                function LogsService(rpcImpl, requestDelimited, responseDelimited) {
                  $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);
                }
                __name(LogsService, "LogsService");
                (LogsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = LogsService;
                LogsService.create = /* @__PURE__ */ __name(function create(rpcImpl, requestDelimited, responseDelimited) {
                  return new this(rpcImpl, requestDelimited, responseDelimited);
                }, "create");
                Object.defineProperty(LogsService.prototype["export"] = /* @__PURE__ */ __name(function export_(request4, callback) {
                  return this.rpcCall(export_, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse, request4, callback);
                }, "export_"), "name", { value: "Export" });
                return LogsService;
              }();
              v1.ExportLogsServiceRequest = function() {
                function ExportLogsServiceRequest(properties) {
                  this.resourceLogs = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportLogsServiceRequest, "ExportLogsServiceRequest");
                ExportLogsServiceRequest.prototype.resourceLogs = $util.emptyArray;
                ExportLogsServiceRequest.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportLogsServiceRequest(properties);
                }, "create");
                ExportLogsServiceRequest.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceLogs != null && message.resourceLogs.length)
                    for (var i = 0; i < message.resourceLogs.length; ++i)
                      $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(
                        /* id 1, wireType 2 =*/
                        10
                      ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportLogsServiceRequest.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportLogsServiceRequest.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        if (!(message.resourceLogs && message.resourceLogs.length))
                          message.resourceLogs = [];
                        message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32()));
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportLogsServiceRequest.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportLogsServiceRequest.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) {
                    if (!Array.isArray(message.resourceLogs))
                      return "resourceLogs: array expected";
                    for (var i = 0; i < message.resourceLogs.length; ++i) {
                      var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]);
                      if (error)
                        return "resourceLogs." + error;
                    }
                  }
                  return null;
                }, "verify");
                ExportLogsServiceRequest.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest();
                  if (object.resourceLogs) {
                    if (!Array.isArray(object.resourceLogs))
                      throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: array expected");
                    message.resourceLogs = [];
                    for (var i = 0; i < object.resourceLogs.length; ++i) {
                      if (typeof object.resourceLogs[i] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected");
                      message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]);
                    }
                  }
                  return message;
                }, "fromObject");
                ExportLogsServiceRequest.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.arrays || options.defaults)
                    object.resourceLogs = [];
                  if (message.resourceLogs && message.resourceLogs.length) {
                    object.resourceLogs = [];
                    for (var j = 0; j < message.resourceLogs.length; ++j)
                      object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options);
                  }
                  return object;
                }, "toObject");
                ExportLogsServiceRequest.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportLogsServiceRequest.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest";
                }, "getTypeUrl");
                return ExportLogsServiceRequest;
              }();
              v1.ExportLogsServiceResponse = function() {
                function ExportLogsServiceResponse(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportLogsServiceResponse, "ExportLogsServiceResponse");
                ExportLogsServiceResponse.prototype.partialSuccess = null;
                ExportLogsServiceResponse.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportLogsServiceResponse(properties);
                }, "create");
                ExportLogsServiceResponse.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess"))
                    $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.encode(message.partialSuccess, writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                  return writer;
                }, "encode");
                ExportLogsServiceResponse.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportLogsServiceResponse.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.decode(reader, reader.uint32());
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportLogsServiceResponse.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportLogsServiceResponse.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) {
                    var error = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(message.partialSuccess);
                    if (error)
                      return "partialSuccess." + error;
                  }
                  return null;
                }, "verify");
                ExportLogsServiceResponse.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse();
                  if (object.partialSuccess != null) {
                    if (typeof object.partialSuccess !== "object")
                      throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.partialSuccess: object expected");
                    message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.fromObject(object.partialSuccess);
                  }
                  return message;
                }, "fromObject");
                ExportLogsServiceResponse.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.defaults)
                    object.partialSuccess = null;
                  if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess"))
                    object.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.toObject(message.partialSuccess, options);
                  return object;
                }, "toObject");
                ExportLogsServiceResponse.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportLogsServiceResponse.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse";
                }, "getTypeUrl");
                return ExportLogsServiceResponse;
              }();
              v1.ExportLogsPartialSuccess = function() {
                function ExportLogsPartialSuccess(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ExportLogsPartialSuccess, "ExportLogsPartialSuccess");
                ExportLogsPartialSuccess.prototype.rejectedLogRecords = null;
                ExportLogsPartialSuccess.prototype.errorMessage = null;
                ExportLogsPartialSuccess.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ExportLogsPartialSuccess(properties);
                }, "create");
                ExportLogsPartialSuccess.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.rejectedLogRecords != null && Object.hasOwnProperty.call(message, "rejectedLogRecords"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).int64(message.rejectedLogRecords);
                  if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage"))
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).string(message.errorMessage);
                  return writer;
                }, "encode");
                ExportLogsPartialSuccess.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ExportLogsPartialSuccess.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.rejectedLogRecords = reader.int64();
                        break;
                      }
                      case 2: {
                        message.errorMessage = reader.string();
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ExportLogsPartialSuccess.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ExportLogsPartialSuccess.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords")) {
                    if (!$util.isInteger(message.rejectedLogRecords) && !(message.rejectedLogRecords && $util.isInteger(message.rejectedLogRecords.low) && $util.isInteger(message.rejectedLogRecords.high)))
                      return "rejectedLogRecords: integer|Long expected";
                  }
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) {
                    if (!$util.isString(message.errorMessage))
                      return "errorMessage: string expected";
                  }
                  return null;
                }, "verify");
                ExportLogsPartialSuccess.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess)
                    return object;
                  var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess();
                  if (object.rejectedLogRecords != null) {
                    if ($util.Long)
                      (message.rejectedLogRecords = $util.Long.fromValue(object.rejectedLogRecords)).unsigned = false;
                    else if (typeof object.rejectedLogRecords === "string")
                      message.rejectedLogRecords = parseInt(object.rejectedLogRecords, 10);
                    else if (typeof object.rejectedLogRecords === "number")
                      message.rejectedLogRecords = object.rejectedLogRecords;
                    else if (typeof object.rejectedLogRecords === "object")
                      message.rejectedLogRecords = new $util.LongBits(object.rejectedLogRecords.low >>> 0, object.rejectedLogRecords.high >>> 0).toNumber();
                  }
                  if (object.errorMessage != null)
                    message.errorMessage = String(object.errorMessage);
                  return message;
                }, "fromObject");
                ExportLogsPartialSuccess.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.defaults) {
                    if ($util.Long) {
                      var long = new $util.Long(0, 0, false);
                      object.rejectedLogRecords = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                    } else
                      object.rejectedLogRecords = options.longs === String ? "0" : 0;
                    object.errorMessage = "";
                  }
                  if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords"))
                    if (typeof message.rejectedLogRecords === "number")
                      object.rejectedLogRecords = options.longs === String ? String(message.rejectedLogRecords) : message.rejectedLogRecords;
                    else
                      object.rejectedLogRecords = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedLogRecords) : options.longs === Number ? new $util.LongBits(message.rejectedLogRecords.low >>> 0, message.rejectedLogRecords.high >>> 0).toNumber() : message.rejectedLogRecords;
                  if (message.errorMessage != null && message.hasOwnProperty("errorMessage"))
                    object.errorMessage = message.errorMessage;
                  return object;
                }, "toObject");
                ExportLogsPartialSuccess.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ExportLogsPartialSuccess.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess";
                }, "getTypeUrl");
                return ExportLogsPartialSuccess;
              }();
              return v1;
            }();
            return logs3;
          }();
          return collector;
        }();
        proto.metrics = function() {
          var metrics2 = {};
          metrics2.v1 = function() {
            var v1 = {};
            v1.MetricsData = function() {
              function MetricsData(properties) {
                this.resourceMetrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(MetricsData, "MetricsData");
              MetricsData.prototype.resourceMetrics = $util.emptyArray;
              MetricsData.create = /* @__PURE__ */ __name(function create(properties) {
                return new MetricsData(properties);
              }, "create");
              MetricsData.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceMetrics != null && message.resourceMetrics.length)
                  for (var i = 0; i < message.resourceMetrics.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              MetricsData.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              MetricsData.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.MetricsData();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.resourceMetrics && message.resourceMetrics.length))
                        message.resourceMetrics = [];
                      message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              MetricsData.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              MetricsData.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) {
                  if (!Array.isArray(message.resourceMetrics))
                    return "resourceMetrics: array expected";
                  for (var i = 0; i < message.resourceMetrics.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]);
                    if (error)
                      return "resourceMetrics." + error;
                  }
                }
                return null;
              }, "verify");
              MetricsData.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.MetricsData)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.MetricsData();
                if (object.resourceMetrics) {
                  if (!Array.isArray(object.resourceMetrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: array expected");
                  message.resourceMetrics = [];
                  for (var i = 0; i < object.resourceMetrics.length; ++i) {
                    if (typeof object.resourceMetrics[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected");
                    message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]);
                  }
                }
                return message;
              }, "fromObject");
              MetricsData.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.resourceMetrics = [];
                if (message.resourceMetrics && message.resourceMetrics.length) {
                  object.resourceMetrics = [];
                  for (var j = 0; j < message.resourceMetrics.length; ++j)
                    object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options);
                }
                return object;
              }, "toObject");
              MetricsData.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              MetricsData.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.MetricsData";
              }, "getTypeUrl");
              return MetricsData;
            }();
            v1.ResourceMetrics = function() {
              function ResourceMetrics(properties) {
                this.scopeMetrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ResourceMetrics, "ResourceMetrics");
              ResourceMetrics.prototype.resource = null;
              ResourceMetrics.prototype.scopeMetrics = $util.emptyArray;
              ResourceMetrics.prototype.schemaUrl = null;
              ResourceMetrics.create = /* @__PURE__ */ __name(function create(properties) {
                return new ResourceMetrics(properties);
              }, "create");
              ResourceMetrics.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resource != null && Object.hasOwnProperty.call(message, "resource"))
                  $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.scopeMetrics != null && message.scopeMetrics.length)
                  for (var i = 0; i < message.scopeMetrics.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(message.scopeMetrics[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ResourceMetrics.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ResourceMetrics.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.scopeMetrics && message.scopeMetrics.length))
                        message.scopeMetrics = [];
                      message.scopeMetrics.push($root.opentelemetry.proto.metrics.v1.ScopeMetrics.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ResourceMetrics.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ResourceMetrics.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resource != null && message.hasOwnProperty("resource")) {
                  var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error)
                    return "resource." + error;
                }
                if (message.scopeMetrics != null && message.hasOwnProperty("scopeMetrics")) {
                  if (!Array.isArray(message.scopeMetrics))
                    return "scopeMetrics: array expected";
                  for (var i = 0; i < message.scopeMetrics.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(message.scopeMetrics[i]);
                    if (error)
                      return "scopeMetrics." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ResourceMetrics.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ResourceMetrics)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics();
                if (object.resource != null) {
                  if (typeof object.resource !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource);
                }
                if (object.scopeMetrics) {
                  if (!Array.isArray(object.scopeMetrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: array expected");
                  message.scopeMetrics = [];
                  for (var i = 0; i < object.scopeMetrics.length; ++i) {
                    if (typeof object.scopeMetrics[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected");
                    message.scopeMetrics[i] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(object.scopeMetrics[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ResourceMetrics.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.scopeMetrics = [];
                if (options.defaults) {
                  object.resource = null;
                  object.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options);
                if (message.scopeMetrics && message.scopeMetrics.length) {
                  object.scopeMetrics = [];
                  for (var j = 0; j < message.scopeMetrics.length; ++j)
                    object.scopeMetrics[j] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.toObject(message.scopeMetrics[j], options);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ResourceMetrics.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ResourceMetrics.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ResourceMetrics";
              }, "getTypeUrl");
              return ResourceMetrics;
            }();
            v1.ScopeMetrics = function() {
              function ScopeMetrics(properties) {
                this.metrics = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ScopeMetrics, "ScopeMetrics");
              ScopeMetrics.prototype.scope = null;
              ScopeMetrics.prototype.metrics = $util.emptyArray;
              ScopeMetrics.prototype.schemaUrl = null;
              ScopeMetrics.create = /* @__PURE__ */ __name(function create(properties) {
                return new ScopeMetrics(properties);
              }, "create");
              ScopeMetrics.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.scope != null && Object.hasOwnProperty.call(message, "scope"))
                  $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.metrics != null && message.metrics.length)
                  for (var i = 0; i < message.metrics.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Metric.encode(message.metrics[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ScopeMetrics.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ScopeMetrics.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.metrics && message.metrics.length))
                        message.metrics = [];
                      message.metrics.push($root.opentelemetry.proto.metrics.v1.Metric.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ScopeMetrics.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ScopeMetrics.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.scope != null && message.hasOwnProperty("scope")) {
                  var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error)
                    return "scope." + error;
                }
                if (message.metrics != null && message.hasOwnProperty("metrics")) {
                  if (!Array.isArray(message.metrics))
                    return "metrics: array expected";
                  for (var i = 0; i < message.metrics.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Metric.verify(message.metrics[i]);
                    if (error)
                      return "metrics." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ScopeMetrics.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ScopeMetrics)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics();
                if (object.scope != null) {
                  if (typeof object.scope !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope);
                }
                if (object.metrics) {
                  if (!Array.isArray(object.metrics))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: array expected");
                  message.metrics = [];
                  for (var i = 0; i < object.metrics.length; ++i) {
                    if (typeof object.metrics[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected");
                    message.metrics[i] = $root.opentelemetry.proto.metrics.v1.Metric.fromObject(object.metrics[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ScopeMetrics.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.metrics = [];
                if (options.defaults) {
                  object.scope = null;
                  object.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options);
                if (message.metrics && message.metrics.length) {
                  object.metrics = [];
                  for (var j = 0; j < message.metrics.length; ++j)
                    object.metrics[j] = $root.opentelemetry.proto.metrics.v1.Metric.toObject(message.metrics[j], options);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ScopeMetrics.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ScopeMetrics.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ScopeMetrics";
              }, "getTypeUrl");
              return ScopeMetrics;
            }();
            v1.Metric = function() {
              function Metric(properties) {
                this.metadata = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Metric, "Metric");
              Metric.prototype.name = null;
              Metric.prototype.description = null;
              Metric.prototype.unit = null;
              Metric.prototype.gauge = null;
              Metric.prototype.sum = null;
              Metric.prototype.histogram = null;
              Metric.prototype.exponentialHistogram = null;
              Metric.prototype.summary = null;
              Metric.prototype.metadata = $util.emptyArray;
              var $oneOfFields;
              Object.defineProperty(Metric.prototype, "data", {
                get: $util.oneOfGetter($oneOfFields = ["gauge", "sum", "histogram", "exponentialHistogram", "summary"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Metric.create = /* @__PURE__ */ __name(function create(properties) {
                return new Metric(properties);
              }, "create");
              Metric.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.name != null && Object.hasOwnProperty.call(message, "name"))
                  writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).string(message.name);
                if (message.description != null && Object.hasOwnProperty.call(message, "description"))
                  writer.uint32(
                    /* id 2, wireType 2 =*/
                    18
                  ).string(message.description);
                if (message.unit != null && Object.hasOwnProperty.call(message, "unit"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.unit);
                if (message.gauge != null && Object.hasOwnProperty.call(message, "gauge"))
                  $root.opentelemetry.proto.metrics.v1.Gauge.encode(message.gauge, writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).fork()).ldelim();
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  $root.opentelemetry.proto.metrics.v1.Sum.encode(message.sum, writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).fork()).ldelim();
                if (message.histogram != null && Object.hasOwnProperty.call(message, "histogram"))
                  $root.opentelemetry.proto.metrics.v1.Histogram.encode(message.histogram, writer.uint32(
                    /* id 9, wireType 2 =*/
                    74
                  ).fork()).ldelim();
                if (message.exponentialHistogram != null && Object.hasOwnProperty.call(message, "exponentialHistogram"))
                  $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.encode(message.exponentialHistogram, writer.uint32(
                    /* id 10, wireType 2 =*/
                    82
                  ).fork()).ldelim();
                if (message.summary != null && Object.hasOwnProperty.call(message, "summary"))
                  $root.opentelemetry.proto.metrics.v1.Summary.encode(message.summary, writer.uint32(
                    /* id 11, wireType 2 =*/
                    90
                  ).fork()).ldelim();
                if (message.metadata != null && message.metadata.length)
                  for (var i = 0; i < message.metadata.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.metadata[i], writer.uint32(
                      /* id 12, wireType 2 =*/
                      98
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Metric.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Metric.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Metric();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.name = reader.string();
                      break;
                    }
                    case 2: {
                      message.description = reader.string();
                      break;
                    }
                    case 3: {
                      message.unit = reader.string();
                      break;
                    }
                    case 5: {
                      message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.decode(reader, reader.uint32());
                      break;
                    }
                    case 7: {
                      message.sum = $root.opentelemetry.proto.metrics.v1.Sum.decode(reader, reader.uint32());
                      break;
                    }
                    case 9: {
                      message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.decode(reader, reader.uint32());
                      break;
                    }
                    case 10: {
                      message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.decode(reader, reader.uint32());
                      break;
                    }
                    case 11: {
                      message.summary = $root.opentelemetry.proto.metrics.v1.Summary.decode(reader, reader.uint32());
                      break;
                    }
                    case 12: {
                      if (!(message.metadata && message.metadata.length))
                        message.metadata = [];
                      message.metadata.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Metric.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Metric.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.name != null && message.hasOwnProperty("name")) {
                  if (!$util.isString(message.name))
                    return "name: string expected";
                }
                if (message.description != null && message.hasOwnProperty("description")) {
                  if (!$util.isString(message.description))
                    return "description: string expected";
                }
                if (message.unit != null && message.hasOwnProperty("unit")) {
                  if (!$util.isString(message.unit))
                    return "unit: string expected";
                }
                if (message.gauge != null && message.hasOwnProperty("gauge")) {
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Gauge.verify(message.gauge);
                    if (error)
                      return "gauge." + error;
                  }
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Sum.verify(message.sum);
                    if (error)
                      return "sum." + error;
                  }
                }
                if (message.histogram != null && message.hasOwnProperty("histogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Histogram.verify(message.histogram);
                    if (error)
                      return "histogram." + error;
                  }
                }
                if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(message.exponentialHistogram);
                    if (error)
                      return "exponentialHistogram." + error;
                  }
                }
                if (message.summary != null && message.hasOwnProperty("summary")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error = $root.opentelemetry.proto.metrics.v1.Summary.verify(message.summary);
                    if (error)
                      return "summary." + error;
                  }
                }
                if (message.metadata != null && message.hasOwnProperty("metadata")) {
                  if (!Array.isArray(message.metadata))
                    return "metadata: array expected";
                  for (var i = 0; i < message.metadata.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.metadata[i]);
                    if (error)
                      return "metadata." + error;
                  }
                }
                return null;
              }, "verify");
              Metric.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Metric)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Metric();
                if (object.name != null)
                  message.name = String(object.name);
                if (object.description != null)
                  message.description = String(object.description);
                if (object.unit != null)
                  message.unit = String(object.unit);
                if (object.gauge != null) {
                  if (typeof object.gauge !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.gauge: object expected");
                  message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.fromObject(object.gauge);
                }
                if (object.sum != null) {
                  if (typeof object.sum !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.sum: object expected");
                  message.sum = $root.opentelemetry.proto.metrics.v1.Sum.fromObject(object.sum);
                }
                if (object.histogram != null) {
                  if (typeof object.histogram !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.histogram: object expected");
                  message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.fromObject(object.histogram);
                }
                if (object.exponentialHistogram != null) {
                  if (typeof object.exponentialHistogram !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.exponentialHistogram: object expected");
                  message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.fromObject(object.exponentialHistogram);
                }
                if (object.summary != null) {
                  if (typeof object.summary !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.summary: object expected");
                  message.summary = $root.opentelemetry.proto.metrics.v1.Summary.fromObject(object.summary);
                }
                if (object.metadata) {
                  if (!Array.isArray(object.metadata))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: array expected");
                  message.metadata = [];
                  for (var i = 0; i < object.metadata.length; ++i) {
                    if (typeof object.metadata[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: object expected");
                    message.metadata[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.metadata[i]);
                  }
                }
                return message;
              }, "fromObject");
              Metric.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.metadata = [];
                if (options.defaults) {
                  object.name = "";
                  object.description = "";
                  object.unit = "";
                }
                if (message.name != null && message.hasOwnProperty("name"))
                  object.name = message.name;
                if (message.description != null && message.hasOwnProperty("description"))
                  object.description = message.description;
                if (message.unit != null && message.hasOwnProperty("unit"))
                  object.unit = message.unit;
                if (message.gauge != null && message.hasOwnProperty("gauge")) {
                  object.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.toObject(message.gauge, options);
                  if (options.oneofs)
                    object.data = "gauge";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  object.sum = $root.opentelemetry.proto.metrics.v1.Sum.toObject(message.sum, options);
                  if (options.oneofs)
                    object.data = "sum";
                }
                if (message.histogram != null && message.hasOwnProperty("histogram")) {
                  object.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.toObject(message.histogram, options);
                  if (options.oneofs)
                    object.data = "histogram";
                }
                if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) {
                  object.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.toObject(message.exponentialHistogram, options);
                  if (options.oneofs)
                    object.data = "exponentialHistogram";
                }
                if (message.summary != null && message.hasOwnProperty("summary")) {
                  object.summary = $root.opentelemetry.proto.metrics.v1.Summary.toObject(message.summary, options);
                  if (options.oneofs)
                    object.data = "summary";
                }
                if (message.metadata && message.metadata.length) {
                  object.metadata = [];
                  for (var j = 0; j < message.metadata.length; ++j)
                    object.metadata[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.metadata[j], options);
                }
                return object;
              }, "toObject");
              Metric.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Metric.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Metric";
              }, "getTypeUrl");
              return Metric;
            }();
            v1.Gauge = function() {
              function Gauge(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Gauge, "Gauge");
              Gauge.prototype.dataPoints = $util.emptyArray;
              Gauge.create = /* @__PURE__ */ __name(function create(properties) {
                return new Gauge(properties);
              }, "create");
              Gauge.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Gauge.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Gauge.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Gauge();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Gauge.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Gauge.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                return null;
              }, "verify");
              Gauge.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Gauge)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Gauge();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                return message;
              }, "fromObject");
              Gauge.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.dataPoints = [];
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options);
                }
                return object;
              }, "toObject");
              Gauge.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Gauge.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Gauge";
              }, "getTypeUrl");
              return Gauge;
            }();
            v1.Sum = function() {
              function Sum(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Sum, "Sum");
              Sum.prototype.dataPoints = $util.emptyArray;
              Sum.prototype.aggregationTemporality = null;
              Sum.prototype.isMonotonic = null;
              Sum.create = /* @__PURE__ */ __name(function create(properties) {
                return new Sum(properties);
              }, "create");
              Sum.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.aggregationTemporality);
                if (message.isMonotonic != null && Object.hasOwnProperty.call(message, "isMonotonic"))
                  writer.uint32(
                    /* id 3, wireType 0 =*/
                    24
                  ).bool(message.isMonotonic);
                return writer;
              }, "encode");
              Sum.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Sum.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Sum();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.aggregationTemporality = reader.int32();
                      break;
                    }
                    case 3: {
                      message.isMonotonic = reader.bool();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Sum.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Sum.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  switch (message.aggregationTemporality) {
                    default:
                      return "aggregationTemporality: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic")) {
                  if (typeof message.isMonotonic !== "boolean")
                    return "isMonotonic: boolean expected";
                }
                return null;
              }, "verify");
              Sum.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Sum)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Sum();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                switch (object.aggregationTemporality) {
                  default:
                    if (typeof object.aggregationTemporality === "number") {
                      message.aggregationTemporality = object.aggregationTemporality;
                      break;
                    }
                    break;
                  case "AGGREGATION_TEMPORALITY_UNSPECIFIED":
                  case 0:
                    message.aggregationTemporality = 0;
                    break;
                  case "AGGREGATION_TEMPORALITY_DELTA":
                  case 1:
                    message.aggregationTemporality = 1;
                    break;
                  case "AGGREGATION_TEMPORALITY_CUMULATIVE":
                  case 2:
                    message.aggregationTemporality = 2;
                    break;
                }
                if (object.isMonotonic != null)
                  message.isMonotonic = Boolean(object.isMonotonic);
                return message;
              }, "fromObject");
              Sum.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.dataPoints = [];
                if (options.defaults) {
                  object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                  object.isMonotonic = false;
                }
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === void 0 ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality;
                if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic"))
                  object.isMonotonic = message.isMonotonic;
                return object;
              }, "toObject");
              Sum.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Sum.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Sum";
              }, "getTypeUrl");
              return Sum;
            }();
            v1.Histogram = function() {
              function Histogram(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Histogram, "Histogram");
              Histogram.prototype.dataPoints = $util.emptyArray;
              Histogram.prototype.aggregationTemporality = null;
              Histogram.create = /* @__PURE__ */ __name(function create(properties) {
                return new Histogram(properties);
              }, "create");
              Histogram.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.aggregationTemporality);
                return writer;
              }, "encode");
              Histogram.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Histogram.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Histogram();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.HistogramDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.aggregationTemporality = reader.int32();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Histogram.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Histogram.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  switch (message.aggregationTemporality) {
                    default:
                      return "aggregationTemporality: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                return null;
              }, "verify");
              Histogram.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Histogram)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Histogram();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                switch (object.aggregationTemporality) {
                  default:
                    if (typeof object.aggregationTemporality === "number") {
                      message.aggregationTemporality = object.aggregationTemporality;
                      break;
                    }
                    break;
                  case "AGGREGATION_TEMPORALITY_UNSPECIFIED":
                  case 0:
                    message.aggregationTemporality = 0;
                    break;
                  case "AGGREGATION_TEMPORALITY_DELTA":
                  case 1:
                    message.aggregationTemporality = 1;
                    break;
                  case "AGGREGATION_TEMPORALITY_CUMULATIVE":
                  case 2:
                    message.aggregationTemporality = 2;
                    break;
                }
                return message;
              }, "fromObject");
              Histogram.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.dataPoints = [];
                if (options.defaults)
                  object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.toObject(message.dataPoints[j], options);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === void 0 ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality;
                return object;
              }, "toObject");
              Histogram.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Histogram.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Histogram";
              }, "getTypeUrl");
              return Histogram;
            }();
            v1.ExponentialHistogram = function() {
              function ExponentialHistogram(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ExponentialHistogram, "ExponentialHistogram");
              ExponentialHistogram.prototype.dataPoints = $util.emptyArray;
              ExponentialHistogram.prototype.aggregationTemporality = null;
              ExponentialHistogram.create = /* @__PURE__ */ __name(function create(properties) {
                return new ExponentialHistogram(properties);
              }, "create");
              ExponentialHistogram.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.aggregationTemporality);
                return writer;
              }, "encode");
              ExponentialHistogram.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ExponentialHistogram.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.aggregationTemporality = reader.int32();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ExponentialHistogram.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ExponentialHistogram.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  switch (message.aggregationTemporality) {
                    default:
                      return "aggregationTemporality: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                      break;
                  }
                return null;
              }, "verify");
              ExponentialHistogram.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogram)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                switch (object.aggregationTemporality) {
                  default:
                    if (typeof object.aggregationTemporality === "number") {
                      message.aggregationTemporality = object.aggregationTemporality;
                      break;
                    }
                    break;
                  case "AGGREGATION_TEMPORALITY_UNSPECIFIED":
                  case 0:
                    message.aggregationTemporality = 0;
                    break;
                  case "AGGREGATION_TEMPORALITY_DELTA":
                  case 1:
                    message.aggregationTemporality = 1;
                    break;
                  case "AGGREGATION_TEMPORALITY_CUMULATIVE":
                  case 2:
                    message.aggregationTemporality = 2;
                    break;
                }
                return message;
              }, "fromObject");
              ExponentialHistogram.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.dataPoints = [];
                if (options.defaults)
                  object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0;
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.toObject(message.dataPoints[j], options);
                }
                if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality"))
                  object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === void 0 ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality;
                return object;
              }, "toObject");
              ExponentialHistogram.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ExponentialHistogram.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogram";
              }, "getTypeUrl");
              return ExponentialHistogram;
            }();
            v1.Summary = function() {
              function Summary(properties) {
                this.dataPoints = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Summary, "Summary");
              Summary.prototype.dataPoints = $util.emptyArray;
              Summary.create = /* @__PURE__ */ __name(function create(properties) {
                return new Summary(properties);
              }, "create");
              Summary.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i = 0; i < message.dataPoints.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(message.dataPoints[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Summary.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Summary.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Summary();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.dataPoints && message.dataPoints.length))
                        message.dataPoints = [];
                      message.dataPoints.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Summary.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Summary.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) {
                  if (!Array.isArray(message.dataPoints))
                    return "dataPoints: array expected";
                  for (var i = 0; i < message.dataPoints.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(message.dataPoints[i]);
                    if (error)
                      return "dataPoints." + error;
                  }
                }
                return null;
              }, "verify");
              Summary.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Summary)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Summary();
                if (object.dataPoints) {
                  if (!Array.isArray(object.dataPoints))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: array expected");
                  message.dataPoints = [];
                  for (var i = 0; i < object.dataPoints.length; ++i) {
                    if (typeof object.dataPoints[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected");
                    message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(object.dataPoints[i]);
                  }
                }
                return message;
              }, "fromObject");
              Summary.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.dataPoints = [];
                if (message.dataPoints && message.dataPoints.length) {
                  object.dataPoints = [];
                  for (var j = 0; j < message.dataPoints.length; ++j)
                    object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.toObject(message.dataPoints[j], options);
                }
                return object;
              }, "toObject");
              Summary.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Summary.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Summary";
              }, "getTypeUrl");
              return Summary;
            }();
            v1.AggregationTemporality = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0;
              values[valuesById[1] = "AGGREGATION_TEMPORALITY_DELTA"] = 1;
              values[valuesById[2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2;
              return values;
            }();
            v1.DataPointFlags = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "DATA_POINT_FLAGS_DO_NOT_USE"] = 0;
              values[valuesById[1] = "DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK"] = 1;
              return values;
            }();
            v1.NumberDataPoint = function() {
              function NumberDataPoint(properties) {
                this.attributes = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(NumberDataPoint, "NumberDataPoint");
              NumberDataPoint.prototype.attributes = $util.emptyArray;
              NumberDataPoint.prototype.startTimeUnixNano = null;
              NumberDataPoint.prototype.timeUnixNano = null;
              NumberDataPoint.prototype.asDouble = null;
              NumberDataPoint.prototype.asInt = null;
              NumberDataPoint.prototype.exemplars = $util.emptyArray;
              NumberDataPoint.prototype.flags = null;
              var $oneOfFields;
              Object.defineProperty(NumberDataPoint.prototype, "value", {
                get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              NumberDataPoint.create = /* @__PURE__ */ __name(function create(properties) {
                return new NumberDataPoint(properties);
              }, "create");
              NumberDataPoint.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).double(message.asDouble);
                if (message.exemplars != null && message.exemplars.length)
                  for (var i = 0; i < message.exemplars.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(
                      /* id 5, wireType 2 =*/
                      42
                    ).fork()).ldelim();
                if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt"))
                  writer.uint32(
                    /* id 6, wireType 1 =*/
                    49
                  ).sfixed64(message.asInt);
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 7, wireType 2 =*/
                      58
                    ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 8, wireType 0 =*/
                    64
                  ).uint32(message.flags);
                return writer;
              }, "encode");
              NumberDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              NumberDataPoint.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 7: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.asDouble = reader.double();
                      break;
                    }
                    case 6: {
                      message.asInt = reader.sfixed64();
                      break;
                    }
                    case 5: {
                      if (!(message.exemplars && message.exemplars.length))
                        message.exemplars = [];
                      message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32()));
                      break;
                    }
                    case 8: {
                      message.flags = reader.uint32();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              NumberDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              NumberDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  properties.value = 1;
                  if (typeof message.asDouble !== "number")
                    return "asDouble: number expected";
                }
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high)))
                    return "asInt: integer|Long expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i = 0; i < message.exemplars.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]);
                    if (error)
                      return "exemplars." + error;
                  }
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                return null;
              }, "verify");
              NumberDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.NumberDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.asDouble != null)
                  message.asDouble = Number(object.asDouble);
                if (object.asInt != null) {
                  if ($util.Long)
                    (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false;
                  else if (typeof object.asInt === "string")
                    message.asInt = parseInt(object.asInt, 10);
                  else if (typeof object.asInt === "number")
                    message.asInt = object.asInt;
                  else if (typeof object.asInt === "object")
                    message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber();
                }
                if (object.exemplars) {
                  if (!Array.isArray(object.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i = 0; i < object.exemplars.length; ++i) {
                    if (typeof object.exemplars[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected");
                    message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]);
                  }
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                return message;
              }, "fromObject");
              NumberDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults) {
                  object.exemplars = [];
                  object.attributes = [];
                }
                if (options.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options.longs === String ? "0" : 0;
                  object.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  object.asDouble = options.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble;
                  if (options.oneofs)
                    object.value = "asDouble";
                }
                if (message.exemplars && message.exemplars.length) {
                  object.exemplars = [];
                  for (var j = 0; j < message.exemplars.length; ++j)
                    object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options);
                }
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (typeof message.asInt === "number")
                    object.asInt = options.longs === String ? String(message.asInt) : message.asInt;
                  else
                    object.asInt = options.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt;
                  if (options.oneofs)
                    object.value = "asInt";
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                return object;
              }, "toObject");
              NumberDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              NumberDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.NumberDataPoint";
              }, "getTypeUrl");
              return NumberDataPoint;
            }();
            v1.HistogramDataPoint = function() {
              function HistogramDataPoint(properties) {
                this.attributes = [];
                this.bucketCounts = [];
                this.explicitBounds = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(HistogramDataPoint, "HistogramDataPoint");
              HistogramDataPoint.prototype.attributes = $util.emptyArray;
              HistogramDataPoint.prototype.startTimeUnixNano = null;
              HistogramDataPoint.prototype.timeUnixNano = null;
              HistogramDataPoint.prototype.count = null;
              HistogramDataPoint.prototype.sum = null;
              HistogramDataPoint.prototype.bucketCounts = $util.emptyArray;
              HistogramDataPoint.prototype.explicitBounds = $util.emptyArray;
              HistogramDataPoint.prototype.exemplars = $util.emptyArray;
              HistogramDataPoint.prototype.flags = null;
              HistogramDataPoint.prototype.min = null;
              HistogramDataPoint.prototype.max = null;
              var $oneOfFields;
              Object.defineProperty(HistogramDataPoint.prototype, "_sum", {
                get: $util.oneOfGetter($oneOfFields = ["sum"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(HistogramDataPoint.prototype, "_min", {
                get: $util.oneOfGetter($oneOfFields = ["min"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(HistogramDataPoint.prototype, "_max", {
                get: $util.oneOfGetter($oneOfFields = ["max"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              HistogramDataPoint.create = /* @__PURE__ */ __name(function create(properties) {
                return new HistogramDataPoint(properties);
              }, "create");
              HistogramDataPoint.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.count != null && Object.hasOwnProperty.call(message, "count"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).fixed64(message.count);
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  writer.uint32(
                    /* id 5, wireType 1 =*/
                    41
                  ).double(message.sum);
                if (message.bucketCounts != null && message.bucketCounts.length) {
                  writer.uint32(
                    /* id 6, wireType 2 =*/
                    50
                  ).fork();
                  for (var i = 0; i < message.bucketCounts.length; ++i)
                    writer.fixed64(message.bucketCounts[i]);
                  writer.ldelim();
                }
                if (message.explicitBounds != null && message.explicitBounds.length) {
                  writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).fork();
                  for (var i = 0; i < message.explicitBounds.length; ++i)
                    writer.double(message.explicitBounds[i]);
                  writer.ldelim();
                }
                if (message.exemplars != null && message.exemplars.length)
                  for (var i = 0; i < message.exemplars.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(
                      /* id 8, wireType 2 =*/
                      66
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 9, wireType 2 =*/
                      74
                    ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 10, wireType 0 =*/
                    80
                  ).uint32(message.flags);
                if (message.min != null && Object.hasOwnProperty.call(message, "min"))
                  writer.uint32(
                    /* id 11, wireType 1 =*/
                    89
                  ).double(message.min);
                if (message.max != null && Object.hasOwnProperty.call(message, "max"))
                  writer.uint32(
                    /* id 12, wireType 1 =*/
                    97
                  ).double(message.max);
                return writer;
              }, "encode");
              HistogramDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              HistogramDataPoint.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 9: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.count = reader.fixed64();
                      break;
                    }
                    case 5: {
                      message.sum = reader.double();
                      break;
                    }
                    case 6: {
                      if (!(message.bucketCounts && message.bucketCounts.length))
                        message.bucketCounts = [];
                      if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                          message.bucketCounts.push(reader.fixed64());
                      } else
                        message.bucketCounts.push(reader.fixed64());
                      break;
                    }
                    case 7: {
                      if (!(message.explicitBounds && message.explicitBounds.length))
                        message.explicitBounds = [];
                      if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                          message.explicitBounds.push(reader.double());
                      } else
                        message.explicitBounds.push(reader.double());
                      break;
                    }
                    case 8: {
                      if (!(message.exemplars && message.exemplars.length))
                        message.exemplars = [];
                      message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32()));
                      break;
                    }
                    case 10: {
                      message.flags = reader.uint32();
                      break;
                    }
                    case 11: {
                      message.min = reader.double();
                      break;
                    }
                    case 12: {
                      message.max = reader.double();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              HistogramDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              HistogramDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.count != null && message.hasOwnProperty("count")) {
                  if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high)))
                    return "count: integer|Long expected";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  properties._sum = 1;
                  if (typeof message.sum !== "number")
                    return "sum: number expected";
                }
                if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) {
                  if (!Array.isArray(message.bucketCounts))
                    return "bucketCounts: array expected";
                  for (var i = 0; i < message.bucketCounts.length; ++i)
                    if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high)))
                      return "bucketCounts: integer|Long[] expected";
                }
                if (message.explicitBounds != null && message.hasOwnProperty("explicitBounds")) {
                  if (!Array.isArray(message.explicitBounds))
                    return "explicitBounds: array expected";
                  for (var i = 0; i < message.explicitBounds.length; ++i)
                    if (typeof message.explicitBounds[i] !== "number")
                      return "explicitBounds: number[] expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i = 0; i < message.exemplars.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]);
                    if (error)
                      return "exemplars." + error;
                  }
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.min != null && message.hasOwnProperty("min")) {
                  properties._min = 1;
                  if (typeof message.min !== "number")
                    return "min: number expected";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  properties._max = 1;
                  if (typeof message.max !== "number")
                    return "max: number expected";
                }
                return null;
              }, "verify");
              HistogramDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.HistogramDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object.count)).unsigned = false;
                  else if (typeof object.count === "string")
                    message.count = parseInt(object.count, 10);
                  else if (typeof object.count === "number")
                    message.count = object.count;
                  else if (typeof object.count === "object")
                    message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber();
                }
                if (object.sum != null)
                  message.sum = Number(object.sum);
                if (object.bucketCounts) {
                  if (!Array.isArray(object.bucketCounts))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.bucketCounts: array expected");
                  message.bucketCounts = [];
                  for (var i = 0; i < object.bucketCounts.length; ++i)
                    if ($util.Long)
                      (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = false;
                    else if (typeof object.bucketCounts[i] === "string")
                      message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10);
                    else if (typeof object.bucketCounts[i] === "number")
                      message.bucketCounts[i] = object.bucketCounts[i];
                    else if (typeof object.bucketCounts[i] === "object")
                      message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber();
                }
                if (object.explicitBounds) {
                  if (!Array.isArray(object.explicitBounds))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.explicitBounds: array expected");
                  message.explicitBounds = [];
                  for (var i = 0; i < object.explicitBounds.length; ++i)
                    message.explicitBounds[i] = Number(object.explicitBounds[i]);
                }
                if (object.exemplars) {
                  if (!Array.isArray(object.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i = 0; i < object.exemplars.length; ++i) {
                    if (typeof object.exemplars[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected");
                    message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]);
                  }
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.min != null)
                  message.min = Number(object.min);
                if (object.max != null)
                  message.max = Number(object.max);
                return message;
              }, "fromObject");
              HistogramDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults) {
                  object.bucketCounts = [];
                  object.explicitBounds = [];
                  object.exemplars = [];
                  object.attributes = [];
                }
                if (options.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.count = options.longs === String ? "0" : 0;
                  object.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.count != null && message.hasOwnProperty("count"))
                  if (typeof message.count === "number")
                    object.count = options.longs === String ? String(message.count) : message.count;
                  else
                    object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count;
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                  if (options.oneofs)
                    object._sum = "sum";
                }
                if (message.bucketCounts && message.bucketCounts.length) {
                  object.bucketCounts = [];
                  for (var j = 0; j < message.bucketCounts.length; ++j)
                    if (typeof message.bucketCounts[j] === "number")
                      object.bucketCounts[j] = options.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j];
                    else
                      object.bucketCounts[j] = options.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber() : message.bucketCounts[j];
                }
                if (message.explicitBounds && message.explicitBounds.length) {
                  object.explicitBounds = [];
                  for (var j = 0; j < message.explicitBounds.length; ++j)
                    object.explicitBounds[j] = options.json && !isFinite(message.explicitBounds[j]) ? String(message.explicitBounds[j]) : message.explicitBounds[j];
                }
                if (message.exemplars && message.exemplars.length) {
                  object.exemplars = [];
                  for (var j = 0; j < message.exemplars.length; ++j)
                    object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options);
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                if (message.min != null && message.hasOwnProperty("min")) {
                  object.min = options.json && !isFinite(message.min) ? String(message.min) : message.min;
                  if (options.oneofs)
                    object._min = "min";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  object.max = options.json && !isFinite(message.max) ? String(message.max) : message.max;
                  if (options.oneofs)
                    object._max = "max";
                }
                return object;
              }, "toObject");
              HistogramDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              HistogramDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.HistogramDataPoint";
              }, "getTypeUrl");
              return HistogramDataPoint;
            }();
            v1.ExponentialHistogramDataPoint = function() {
              function ExponentialHistogramDataPoint(properties) {
                this.attributes = [];
                this.exemplars = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ExponentialHistogramDataPoint, "ExponentialHistogramDataPoint");
              ExponentialHistogramDataPoint.prototype.attributes = $util.emptyArray;
              ExponentialHistogramDataPoint.prototype.startTimeUnixNano = null;
              ExponentialHistogramDataPoint.prototype.timeUnixNano = null;
              ExponentialHistogramDataPoint.prototype.count = null;
              ExponentialHistogramDataPoint.prototype.sum = null;
              ExponentialHistogramDataPoint.prototype.scale = null;
              ExponentialHistogramDataPoint.prototype.zeroCount = null;
              ExponentialHistogramDataPoint.prototype.positive = null;
              ExponentialHistogramDataPoint.prototype.negative = null;
              ExponentialHistogramDataPoint.prototype.flags = null;
              ExponentialHistogramDataPoint.prototype.exemplars = $util.emptyArray;
              ExponentialHistogramDataPoint.prototype.min = null;
              ExponentialHistogramDataPoint.prototype.max = null;
              ExponentialHistogramDataPoint.prototype.zeroThreshold = null;
              var $oneOfFields;
              Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_sum", {
                get: $util.oneOfGetter($oneOfFields = ["sum"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_min", {
                get: $util.oneOfGetter($oneOfFields = ["min"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_max", {
                get: $util.oneOfGetter($oneOfFields = ["max"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              ExponentialHistogramDataPoint.create = /* @__PURE__ */ __name(function create(properties) {
                return new ExponentialHistogramDataPoint(properties);
              }, "create");
              ExponentialHistogramDataPoint.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.count != null && Object.hasOwnProperty.call(message, "count"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).fixed64(message.count);
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  writer.uint32(
                    /* id 5, wireType 1 =*/
                    41
                  ).double(message.sum);
                if (message.scale != null && Object.hasOwnProperty.call(message, "scale"))
                  writer.uint32(
                    /* id 6, wireType 0 =*/
                    48
                  ).sint32(message.scale);
                if (message.zeroCount != null && Object.hasOwnProperty.call(message, "zeroCount"))
                  writer.uint32(
                    /* id 7, wireType 1 =*/
                    57
                  ).fixed64(message.zeroCount);
                if (message.positive != null && Object.hasOwnProperty.call(message, "positive"))
                  $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.positive, writer.uint32(
                    /* id 8, wireType 2 =*/
                    66
                  ).fork()).ldelim();
                if (message.negative != null && Object.hasOwnProperty.call(message, "negative"))
                  $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.negative, writer.uint32(
                    /* id 9, wireType 2 =*/
                    74
                  ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 10, wireType 0 =*/
                    80
                  ).uint32(message.flags);
                if (message.exemplars != null && message.exemplars.length)
                  for (var i = 0; i < message.exemplars.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(
                      /* id 11, wireType 2 =*/
                      90
                    ).fork()).ldelim();
                if (message.min != null && Object.hasOwnProperty.call(message, "min"))
                  writer.uint32(
                    /* id 12, wireType 1 =*/
                    97
                  ).double(message.min);
                if (message.max != null && Object.hasOwnProperty.call(message, "max"))
                  writer.uint32(
                    /* id 13, wireType 1 =*/
                    105
                  ).double(message.max);
                if (message.zeroThreshold != null && Object.hasOwnProperty.call(message, "zeroThreshold"))
                  writer.uint32(
                    /* id 14, wireType 1 =*/
                    113
                  ).double(message.zeroThreshold);
                return writer;
              }, "encode");
              ExponentialHistogramDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ExponentialHistogramDataPoint.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.count = reader.fixed64();
                      break;
                    }
                    case 5: {
                      message.sum = reader.double();
                      break;
                    }
                    case 6: {
                      message.scale = reader.sint32();
                      break;
                    }
                    case 7: {
                      message.zeroCount = reader.fixed64();
                      break;
                    }
                    case 8: {
                      message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32());
                      break;
                    }
                    case 9: {
                      message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32());
                      break;
                    }
                    case 10: {
                      message.flags = reader.uint32();
                      break;
                    }
                    case 11: {
                      if (!(message.exemplars && message.exemplars.length))
                        message.exemplars = [];
                      message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32()));
                      break;
                    }
                    case 12: {
                      message.min = reader.double();
                      break;
                    }
                    case 13: {
                      message.max = reader.double();
                      break;
                    }
                    case 14: {
                      message.zeroThreshold = reader.double();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ExponentialHistogramDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ExponentialHistogramDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.count != null && message.hasOwnProperty("count")) {
                  if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high)))
                    return "count: integer|Long expected";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  properties._sum = 1;
                  if (typeof message.sum !== "number")
                    return "sum: number expected";
                }
                if (message.scale != null && message.hasOwnProperty("scale")) {
                  if (!$util.isInteger(message.scale))
                    return "scale: integer expected";
                }
                if (message.zeroCount != null && message.hasOwnProperty("zeroCount")) {
                  if (!$util.isInteger(message.zeroCount) && !(message.zeroCount && $util.isInteger(message.zeroCount.low) && $util.isInteger(message.zeroCount.high)))
                    return "zeroCount: integer|Long expected";
                }
                if (message.positive != null && message.hasOwnProperty("positive")) {
                  var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.positive);
                  if (error)
                    return "positive." + error;
                }
                if (message.negative != null && message.hasOwnProperty("negative")) {
                  var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.negative);
                  if (error)
                    return "negative." + error;
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i = 0; i < message.exemplars.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]);
                    if (error)
                      return "exemplars." + error;
                  }
                }
                if (message.min != null && message.hasOwnProperty("min")) {
                  properties._min = 1;
                  if (typeof message.min !== "number")
                    return "min: number expected";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  properties._max = 1;
                  if (typeof message.max !== "number")
                    return "max: number expected";
                }
                if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold")) {
                  if (typeof message.zeroThreshold !== "number")
                    return "zeroThreshold: number expected";
                }
                return null;
              }, "verify");
              ExponentialHistogramDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object.count)).unsigned = false;
                  else if (typeof object.count === "string")
                    message.count = parseInt(object.count, 10);
                  else if (typeof object.count === "number")
                    message.count = object.count;
                  else if (typeof object.count === "object")
                    message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber();
                }
                if (object.sum != null)
                  message.sum = Number(object.sum);
                if (object.scale != null)
                  message.scale = object.scale | 0;
                if (object.zeroCount != null) {
                  if ($util.Long)
                    (message.zeroCount = $util.Long.fromValue(object.zeroCount)).unsigned = false;
                  else if (typeof object.zeroCount === "string")
                    message.zeroCount = parseInt(object.zeroCount, 10);
                  else if (typeof object.zeroCount === "number")
                    message.zeroCount = object.zeroCount;
                  else if (typeof object.zeroCount === "object")
                    message.zeroCount = new $util.LongBits(object.zeroCount.low >>> 0, object.zeroCount.high >>> 0).toNumber();
                }
                if (object.positive != null) {
                  if (typeof object.positive !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.positive: object expected");
                  message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.positive);
                }
                if (object.negative != null) {
                  if (typeof object.negative !== "object")
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.negative: object expected");
                  message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.negative);
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.exemplars) {
                  if (!Array.isArray(object.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i = 0; i < object.exemplars.length; ++i) {
                    if (typeof object.exemplars[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected");
                    message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]);
                  }
                }
                if (object.min != null)
                  message.min = Number(object.min);
                if (object.max != null)
                  message.max = Number(object.max);
                if (object.zeroThreshold != null)
                  message.zeroThreshold = Number(object.zeroThreshold);
                return message;
              }, "fromObject");
              ExponentialHistogramDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults) {
                  object.attributes = [];
                  object.exemplars = [];
                }
                if (options.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.count = options.longs === String ? "0" : 0;
                  object.scale = 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.zeroCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.zeroCount = options.longs === String ? "0" : 0;
                  object.positive = null;
                  object.negative = null;
                  object.flags = 0;
                  object.zeroThreshold = 0;
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.count != null && message.hasOwnProperty("count"))
                  if (typeof message.count === "number")
                    object.count = options.longs === String ? String(message.count) : message.count;
                  else
                    object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count;
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                  if (options.oneofs)
                    object._sum = "sum";
                }
                if (message.scale != null && message.hasOwnProperty("scale"))
                  object.scale = message.scale;
                if (message.zeroCount != null && message.hasOwnProperty("zeroCount"))
                  if (typeof message.zeroCount === "number")
                    object.zeroCount = options.longs === String ? String(message.zeroCount) : message.zeroCount;
                  else
                    object.zeroCount = options.longs === String ? $util.Long.prototype.toString.call(message.zeroCount) : options.longs === Number ? new $util.LongBits(message.zeroCount.low >>> 0, message.zeroCount.high >>> 0).toNumber() : message.zeroCount;
                if (message.positive != null && message.hasOwnProperty("positive"))
                  object.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.positive, options);
                if (message.negative != null && message.hasOwnProperty("negative"))
                  object.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.negative, options);
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                if (message.exemplars && message.exemplars.length) {
                  object.exemplars = [];
                  for (var j = 0; j < message.exemplars.length; ++j)
                    object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options);
                }
                if (message.min != null && message.hasOwnProperty("min")) {
                  object.min = options.json && !isFinite(message.min) ? String(message.min) : message.min;
                  if (options.oneofs)
                    object._min = "min";
                }
                if (message.max != null && message.hasOwnProperty("max")) {
                  object.max = options.json && !isFinite(message.max) ? String(message.max) : message.max;
                  if (options.oneofs)
                    object._max = "max";
                }
                if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold"))
                  object.zeroThreshold = options.json && !isFinite(message.zeroThreshold) ? String(message.zeroThreshold) : message.zeroThreshold;
                return object;
              }, "toObject");
              ExponentialHistogramDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ExponentialHistogramDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint";
              }, "getTypeUrl");
              ExponentialHistogramDataPoint.Buckets = function() {
                function Buckets(properties) {
                  this.bucketCounts = [];
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(Buckets, "Buckets");
                Buckets.prototype.offset = null;
                Buckets.prototype.bucketCounts = $util.emptyArray;
                Buckets.create = /* @__PURE__ */ __name(function create(properties) {
                  return new Buckets(properties);
                }, "create");
                Buckets.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
                    writer.uint32(
                      /* id 1, wireType 0 =*/
                      8
                    ).sint32(message.offset);
                  if (message.bucketCounts != null && message.bucketCounts.length) {
                    writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork();
                    for (var i = 0; i < message.bucketCounts.length; ++i)
                      writer.uint64(message.bucketCounts[i]);
                    writer.ldelim();
                  }
                  return writer;
                }, "encode");
                Buckets.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                Buckets.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.offset = reader.sint32();
                        break;
                      }
                      case 2: {
                        if (!(message.bucketCounts && message.bucketCounts.length))
                          message.bucketCounts = [];
                        if ((tag & 7) === 2) {
                          var end2 = reader.uint32() + reader.pos;
                          while (reader.pos < end2)
                            message.bucketCounts.push(reader.uint64());
                        } else
                          message.bucketCounts.push(reader.uint64());
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                Buckets.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                Buckets.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.offset != null && message.hasOwnProperty("offset")) {
                    if (!$util.isInteger(message.offset))
                      return "offset: integer expected";
                  }
                  if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) {
                    if (!Array.isArray(message.bucketCounts))
                      return "bucketCounts: array expected";
                    for (var i = 0; i < message.bucketCounts.length; ++i)
                      if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high)))
                        return "bucketCounts: integer|Long[] expected";
                  }
                  return null;
                }, "verify");
                Buckets.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets)
                    return object;
                  var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets();
                  if (object.offset != null)
                    message.offset = object.offset | 0;
                  if (object.bucketCounts) {
                    if (!Array.isArray(object.bucketCounts))
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.bucketCounts: array expected");
                    message.bucketCounts = [];
                    for (var i = 0; i < object.bucketCounts.length; ++i)
                      if ($util.Long)
                        (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = true;
                      else if (typeof object.bucketCounts[i] === "string")
                        message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10);
                      else if (typeof object.bucketCounts[i] === "number")
                        message.bucketCounts[i] = object.bucketCounts[i];
                      else if (typeof object.bucketCounts[i] === "object")
                        message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber(true);
                  }
                  return message;
                }, "fromObject");
                Buckets.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.arrays || options.defaults)
                    object.bucketCounts = [];
                  if (options.defaults)
                    object.offset = 0;
                  if (message.offset != null && message.hasOwnProperty("offset"))
                    object.offset = message.offset;
                  if (message.bucketCounts && message.bucketCounts.length) {
                    object.bucketCounts = [];
                    for (var j = 0; j < message.bucketCounts.length; ++j)
                      if (typeof message.bucketCounts[j] === "number")
                        object.bucketCounts[j] = options.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j];
                      else
                        object.bucketCounts[j] = options.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber(true) : message.bucketCounts[j];
                  }
                  return object;
                }, "toObject");
                Buckets.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                Buckets.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets";
                }, "getTypeUrl");
                return Buckets;
              }();
              return ExponentialHistogramDataPoint;
            }();
            v1.SummaryDataPoint = function() {
              function SummaryDataPoint(properties) {
                this.attributes = [];
                this.quantileValues = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(SummaryDataPoint, "SummaryDataPoint");
              SummaryDataPoint.prototype.attributes = $util.emptyArray;
              SummaryDataPoint.prototype.startTimeUnixNano = null;
              SummaryDataPoint.prototype.timeUnixNano = null;
              SummaryDataPoint.prototype.count = null;
              SummaryDataPoint.prototype.sum = null;
              SummaryDataPoint.prototype.quantileValues = $util.emptyArray;
              SummaryDataPoint.prototype.flags = null;
              SummaryDataPoint.create = /* @__PURE__ */ __name(function create(properties) {
                return new SummaryDataPoint(properties);
              }, "create");
              SummaryDataPoint.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.startTimeUnixNano);
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).fixed64(message.timeUnixNano);
                if (message.count != null && Object.hasOwnProperty.call(message, "count"))
                  writer.uint32(
                    /* id 4, wireType 1 =*/
                    33
                  ).fixed64(message.count);
                if (message.sum != null && Object.hasOwnProperty.call(message, "sum"))
                  writer.uint32(
                    /* id 5, wireType 1 =*/
                    41
                  ).double(message.sum);
                if (message.quantileValues != null && message.quantileValues.length)
                  for (var i = 0; i < message.quantileValues.length; ++i)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(message.quantileValues[i], writer.uint32(
                      /* id 6, wireType 2 =*/
                      50
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 7, wireType 2 =*/
                      58
                    ).fork()).ldelim();
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 8, wireType 0 =*/
                    64
                  ).uint32(message.flags);
                return writer;
              }, "encode");
              SummaryDataPoint.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              SummaryDataPoint.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 7: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.startTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 4: {
                      message.count = reader.fixed64();
                      break;
                    }
                    case 5: {
                      message.sum = reader.double();
                      break;
                    }
                    case 6: {
                      if (!(message.quantileValues && message.quantileValues.length))
                        message.quantileValues = [];
                      message.quantileValues.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.decode(reader, reader.uint32()));
                      break;
                    }
                    case 8: {
                      message.flags = reader.uint32();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              SummaryDataPoint.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              SummaryDataPoint.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) {
                  if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high)))
                    return "startTimeUnixNano: integer|Long expected";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.count != null && message.hasOwnProperty("count")) {
                  if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high)))
                    return "count: integer|Long expected";
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  if (typeof message.sum !== "number")
                    return "sum: number expected";
                }
                if (message.quantileValues != null && message.hasOwnProperty("quantileValues")) {
                  if (!Array.isArray(message.quantileValues))
                    return "quantileValues: array expected";
                  for (var i = 0; i < message.quantileValues.length; ++i) {
                    var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(message.quantileValues[i]);
                    if (error)
                      return "quantileValues." + error;
                  }
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                return null;
              }, "verify");
              SummaryDataPoint.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint();
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.startTimeUnixNano != null) {
                  if ($util.Long)
                    (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false;
                  else if (typeof object.startTimeUnixNano === "string")
                    message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10);
                  else if (typeof object.startTimeUnixNano === "number")
                    message.startTimeUnixNano = object.startTimeUnixNano;
                  else if (typeof object.startTimeUnixNano === "object")
                    message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber();
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.count != null) {
                  if ($util.Long)
                    (message.count = $util.Long.fromValue(object.count)).unsigned = false;
                  else if (typeof object.count === "string")
                    message.count = parseInt(object.count, 10);
                  else if (typeof object.count === "number")
                    message.count = object.count;
                  else if (typeof object.count === "object")
                    message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber();
                }
                if (object.sum != null)
                  message.sum = Number(object.sum);
                if (object.quantileValues) {
                  if (!Array.isArray(object.quantileValues))
                    throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: array expected");
                  message.quantileValues = [];
                  for (var i = 0; i < object.quantileValues.length; ++i) {
                    if (typeof object.quantileValues[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected");
                    message.quantileValues[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(object.quantileValues[i]);
                  }
                }
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                return message;
              }, "fromObject");
              SummaryDataPoint.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults) {
                  object.quantileValues = [];
                  object.attributes = [];
                }
                if (options.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.startTimeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options.longs === String ? "0" : 0;
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.count = options.longs === String ? "0" : 0;
                  object.sum = 0;
                  object.flags = 0;
                }
                if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano"))
                  if (typeof message.startTimeUnixNano === "number")
                    object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano;
                  else
                    object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano;
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.count != null && message.hasOwnProperty("count"))
                  if (typeof message.count === "number")
                    object.count = options.longs === String ? String(message.count) : message.count;
                  else
                    object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count;
                if (message.sum != null && message.hasOwnProperty("sum"))
                  object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum;
                if (message.quantileValues && message.quantileValues.length) {
                  object.quantileValues = [];
                  for (var j = 0; j < message.quantileValues.length; ++j)
                    object.quantileValues[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.toObject(message.quantileValues[j], options);
                }
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                return object;
              }, "toObject");
              SummaryDataPoint.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              SummaryDataPoint.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint";
              }, "getTypeUrl");
              SummaryDataPoint.ValueAtQuantile = function() {
                function ValueAtQuantile(properties) {
                  if (properties) {
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                      if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
                  }
                }
                __name(ValueAtQuantile, "ValueAtQuantile");
                ValueAtQuantile.prototype.quantile = null;
                ValueAtQuantile.prototype.value = null;
                ValueAtQuantile.create = /* @__PURE__ */ __name(function create(properties) {
                  return new ValueAtQuantile(properties);
                }, "create");
                ValueAtQuantile.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.quantile != null && Object.hasOwnProperty.call(message, "quantile"))
                    writer.uint32(
                      /* id 1, wireType 1 =*/
                      9
                    ).double(message.quantile);
                  if (message.value != null && Object.hasOwnProperty.call(message, "value"))
                    writer.uint32(
                      /* id 2, wireType 1 =*/
                      17
                    ).double(message.value);
                  return writer;
                }, "encode");
                ValueAtQuantile.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                  return this.encode(message, writer).ldelim();
                }, "encodeDelimited");
                ValueAtQuantile.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                  if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                  var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile();
                  while (reader.pos < end) {
                    var tag = reader.uint32();
                    if (tag === error)
                      break;
                    switch (tag >>> 3) {
                      case 1: {
                        message.quantile = reader.double();
                        break;
                      }
                      case 2: {
                        message.value = reader.double();
                        break;
                      }
                      default:
                        reader.skipType(tag & 7);
                        break;
                    }
                  }
                  return message;
                }, "decode");
                ValueAtQuantile.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                  if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                  return this.decode(reader, reader.uint32());
                }, "decodeDelimited");
                ValueAtQuantile.verify = /* @__PURE__ */ __name(function verify(message) {
                  if (typeof message !== "object" || message === null)
                    return "object expected";
                  if (message.quantile != null && message.hasOwnProperty("quantile")) {
                    if (typeof message.quantile !== "number")
                      return "quantile: number expected";
                  }
                  if (message.value != null && message.hasOwnProperty("value")) {
                    if (typeof message.value !== "number")
                      return "value: number expected";
                  }
                  return null;
                }, "verify");
                ValueAtQuantile.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                  if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile)
                    return object;
                  var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile();
                  if (object.quantile != null)
                    message.quantile = Number(object.quantile);
                  if (object.value != null)
                    message.value = Number(object.value);
                  return message;
                }, "fromObject");
                ValueAtQuantile.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                  if (!options)
                    options = {};
                  var object = {};
                  if (options.defaults) {
                    object.quantile = 0;
                    object.value = 0;
                  }
                  if (message.quantile != null && message.hasOwnProperty("quantile"))
                    object.quantile = options.json && !isFinite(message.quantile) ? String(message.quantile) : message.quantile;
                  if (message.value != null && message.hasOwnProperty("value"))
                    object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value;
                  return object;
                }, "toObject");
                ValueAtQuantile.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
                }, "toJSON");
                ValueAtQuantile.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                  if (typeUrlPrefix === void 0) {
                    typeUrlPrefix = "type.googleapis.com";
                  }
                  return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile";
                }, "getTypeUrl");
                return ValueAtQuantile;
              }();
              return SummaryDataPoint;
            }();
            v1.Exemplar = function() {
              function Exemplar(properties) {
                this.filteredAttributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(Exemplar, "Exemplar");
              Exemplar.prototype.filteredAttributes = $util.emptyArray;
              Exemplar.prototype.timeUnixNano = null;
              Exemplar.prototype.asDouble = null;
              Exemplar.prototype.asInt = null;
              Exemplar.prototype.spanId = null;
              Exemplar.prototype.traceId = null;
              var $oneOfFields;
              Object.defineProperty(Exemplar.prototype, "value", {
                get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]),
                set: $util.oneOfSetter($oneOfFields)
              });
              Exemplar.create = /* @__PURE__ */ __name(function create(properties) {
                return new Exemplar(properties);
              }, "create");
              Exemplar.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 2, wireType 1 =*/
                    17
                  ).fixed64(message.timeUnixNano);
                if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble"))
                  writer.uint32(
                    /* id 3, wireType 1 =*/
                    25
                  ).double(message.asDouble);
                if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                  writer.uint32(
                    /* id 4, wireType 2 =*/
                    34
                  ).bytes(message.spanId);
                if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                  writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).bytes(message.traceId);
                if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt"))
                  writer.uint32(
                    /* id 6, wireType 1 =*/
                    49
                  ).sfixed64(message.asInt);
                if (message.filteredAttributes != null && message.filteredAttributes.length)
                  for (var i = 0; i < message.filteredAttributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.filteredAttributes[i], writer.uint32(
                      /* id 7, wireType 2 =*/
                      58
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              Exemplar.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              Exemplar.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Exemplar();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 7: {
                      if (!(message.filteredAttributes && message.filteredAttributes.length))
                        message.filteredAttributes = [];
                      message.filteredAttributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 2: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 3: {
                      message.asDouble = reader.double();
                      break;
                    }
                    case 6: {
                      message.asInt = reader.sfixed64();
                      break;
                    }
                    case 4: {
                      message.spanId = reader.bytes();
                      break;
                    }
                    case 5: {
                      message.traceId = reader.bytes();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              Exemplar.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              Exemplar.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                var properties = {};
                if (message.filteredAttributes != null && message.hasOwnProperty("filteredAttributes")) {
                  if (!Array.isArray(message.filteredAttributes))
                    return "filteredAttributes: array expected";
                  for (var i = 0; i < message.filteredAttributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.filteredAttributes[i]);
                    if (error)
                      return "filteredAttributes." + error;
                  }
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  properties.value = 1;
                  if (typeof message.asDouble !== "number")
                    return "asDouble: number expected";
                }
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high)))
                    return "asInt: integer|Long expected";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId")) {
                  if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                    return "spanId: buffer expected";
                }
                if (message.traceId != null && message.hasOwnProperty("traceId")) {
                  if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                    return "traceId: buffer expected";
                }
                return null;
              }, "verify");
              Exemplar.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.metrics.v1.Exemplar)
                  return object;
                var message = new $root.opentelemetry.proto.metrics.v1.Exemplar();
                if (object.filteredAttributes) {
                  if (!Array.isArray(object.filteredAttributes))
                    throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: array expected");
                  message.filteredAttributes = [];
                  for (var i = 0; i < object.filteredAttributes.length; ++i) {
                    if (typeof object.filteredAttributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected");
                    message.filteredAttributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.filteredAttributes[i]);
                  }
                }
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.asDouble != null)
                  message.asDouble = Number(object.asDouble);
                if (object.asInt != null) {
                  if ($util.Long)
                    (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false;
                  else if (typeof object.asInt === "string")
                    message.asInt = parseInt(object.asInt, 10);
                  else if (typeof object.asInt === "number")
                    message.asInt = object.asInt;
                  else if (typeof object.asInt === "object")
                    message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber();
                }
                if (object.spanId != null) {
                  if (typeof object.spanId === "string")
                    $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                  else if (object.spanId.length >= 0)
                    message.spanId = object.spanId;
                }
                if (object.traceId != null) {
                  if (typeof object.traceId === "string")
                    $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                  else if (object.traceId.length >= 0)
                    message.traceId = object.traceId;
                }
                return message;
              }, "fromObject");
              Exemplar.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.filteredAttributes = [];
                if (options.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options.longs === String ? "0" : 0;
                  if (options.bytes === String)
                    object.spanId = "";
                  else {
                    object.spanId = [];
                    if (options.bytes !== Array)
                      object.spanId = $util.newBuffer(object.spanId);
                  }
                  if (options.bytes === String)
                    object.traceId = "";
                  else {
                    object.traceId = [];
                    if (options.bytes !== Array)
                      object.traceId = $util.newBuffer(object.traceId);
                  }
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.asDouble != null && message.hasOwnProperty("asDouble")) {
                  object.asDouble = options.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble;
                  if (options.oneofs)
                    object.value = "asDouble";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId"))
                  object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                if (message.asInt != null && message.hasOwnProperty("asInt")) {
                  if (typeof message.asInt === "number")
                    object.asInt = options.longs === String ? String(message.asInt) : message.asInt;
                  else
                    object.asInt = options.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt;
                  if (options.oneofs)
                    object.value = "asInt";
                }
                if (message.filteredAttributes && message.filteredAttributes.length) {
                  object.filteredAttributes = [];
                  for (var j = 0; j < message.filteredAttributes.length; ++j)
                    object.filteredAttributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.filteredAttributes[j], options);
                }
                return object;
              }, "toObject");
              Exemplar.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              Exemplar.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Exemplar";
              }, "getTypeUrl");
              return Exemplar;
            }();
            return v1;
          }();
          return metrics2;
        }();
        proto.logs = function() {
          var logs3 = {};
          logs3.v1 = function() {
            var v1 = {};
            v1.LogsData = function() {
              function LogsData(properties) {
                this.resourceLogs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(LogsData, "LogsData");
              LogsData.prototype.resourceLogs = $util.emptyArray;
              LogsData.create = /* @__PURE__ */ __name(function create(properties) {
                return new LogsData(properties);
              }, "create");
              LogsData.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceLogs != null && message.resourceLogs.length)
                  for (var i = 0; i < message.resourceLogs.length; ++i)
                    $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(
                      /* id 1, wireType 2 =*/
                      10
                    ).fork()).ldelim();
                return writer;
              }, "encode");
              LogsData.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              LogsData.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogsData();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      if (!(message.resourceLogs && message.resourceLogs.length))
                        message.resourceLogs = [];
                      message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32()));
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              LogsData.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              LogsData.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) {
                  if (!Array.isArray(message.resourceLogs))
                    return "resourceLogs: array expected";
                  for (var i = 0; i < message.resourceLogs.length; ++i) {
                    var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]);
                    if (error)
                      return "resourceLogs." + error;
                  }
                }
                return null;
              }, "verify");
              LogsData.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.LogsData)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.LogsData();
                if (object.resourceLogs) {
                  if (!Array.isArray(object.resourceLogs))
                    throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: array expected");
                  message.resourceLogs = [];
                  for (var i = 0; i < object.resourceLogs.length; ++i) {
                    if (typeof object.resourceLogs[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected");
                    message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]);
                  }
                }
                return message;
              }, "fromObject");
              LogsData.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.resourceLogs = [];
                if (message.resourceLogs && message.resourceLogs.length) {
                  object.resourceLogs = [];
                  for (var j = 0; j < message.resourceLogs.length; ++j)
                    object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options);
                }
                return object;
              }, "toObject");
              LogsData.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              LogsData.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogsData";
              }, "getTypeUrl");
              return LogsData;
            }();
            v1.ResourceLogs = function() {
              function ResourceLogs(properties) {
                this.scopeLogs = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ResourceLogs, "ResourceLogs");
              ResourceLogs.prototype.resource = null;
              ResourceLogs.prototype.scopeLogs = $util.emptyArray;
              ResourceLogs.prototype.schemaUrl = null;
              ResourceLogs.create = /* @__PURE__ */ __name(function create(properties) {
                return new ResourceLogs(properties);
              }, "create");
              ResourceLogs.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resource != null && Object.hasOwnProperty.call(message, "resource"))
                  $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.scopeLogs != null && message.scopeLogs.length)
                  for (var i = 0; i < message.scopeLogs.length; ++i)
                    $root.opentelemetry.proto.logs.v1.ScopeLogs.encode(message.scopeLogs[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ResourceLogs.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ResourceLogs.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ResourceLogs();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.scopeLogs && message.scopeLogs.length))
                        message.scopeLogs = [];
                      message.scopeLogs.push($root.opentelemetry.proto.logs.v1.ScopeLogs.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ResourceLogs.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ResourceLogs.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.resource != null && message.hasOwnProperty("resource")) {
                  var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error)
                    return "resource." + error;
                }
                if (message.scopeLogs != null && message.hasOwnProperty("scopeLogs")) {
                  if (!Array.isArray(message.scopeLogs))
                    return "scopeLogs: array expected";
                  for (var i = 0; i < message.scopeLogs.length; ++i) {
                    var error = $root.opentelemetry.proto.logs.v1.ScopeLogs.verify(message.scopeLogs[i]);
                    if (error)
                      return "scopeLogs." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ResourceLogs.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.ResourceLogs)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.ResourceLogs();
                if (object.resource != null) {
                  if (typeof object.resource !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.resource: object expected");
                  message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource);
                }
                if (object.scopeLogs) {
                  if (!Array.isArray(object.scopeLogs))
                    throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: array expected");
                  message.scopeLogs = [];
                  for (var i = 0; i < object.scopeLogs.length; ++i) {
                    if (typeof object.scopeLogs[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected");
                    message.scopeLogs[i] = $root.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(object.scopeLogs[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ResourceLogs.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.scopeLogs = [];
                if (options.defaults) {
                  object.resource = null;
                  object.schemaUrl = "";
                }
                if (message.resource != null && message.hasOwnProperty("resource"))
                  object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options);
                if (message.scopeLogs && message.scopeLogs.length) {
                  object.scopeLogs = [];
                  for (var j = 0; j < message.scopeLogs.length; ++j)
                    object.scopeLogs[j] = $root.opentelemetry.proto.logs.v1.ScopeLogs.toObject(message.scopeLogs[j], options);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ResourceLogs.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ResourceLogs.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ResourceLogs";
              }, "getTypeUrl");
              return ResourceLogs;
            }();
            v1.ScopeLogs = function() {
              function ScopeLogs(properties) {
                this.logRecords = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(ScopeLogs, "ScopeLogs");
              ScopeLogs.prototype.scope = null;
              ScopeLogs.prototype.logRecords = $util.emptyArray;
              ScopeLogs.prototype.schemaUrl = null;
              ScopeLogs.create = /* @__PURE__ */ __name(function create(properties) {
                return new ScopeLogs(properties);
              }, "create");
              ScopeLogs.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.scope != null && Object.hasOwnProperty.call(message, "scope"))
                  $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(
                    /* id 1, wireType 2 =*/
                    10
                  ).fork()).ldelim();
                if (message.logRecords != null && message.logRecords.length)
                  for (var i = 0; i < message.logRecords.length; ++i)
                    $root.opentelemetry.proto.logs.v1.LogRecord.encode(message.logRecords[i], writer.uint32(
                      /* id 2, wireType 2 =*/
                      18
                    ).fork()).ldelim();
                if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.schemaUrl);
                return writer;
              }, "encode");
              ScopeLogs.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              ScopeLogs.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ScopeLogs();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32());
                      break;
                    }
                    case 2: {
                      if (!(message.logRecords && message.logRecords.length))
                        message.logRecords = [];
                      message.logRecords.push($root.opentelemetry.proto.logs.v1.LogRecord.decode(reader, reader.uint32()));
                      break;
                    }
                    case 3: {
                      message.schemaUrl = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              ScopeLogs.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              ScopeLogs.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.scope != null && message.hasOwnProperty("scope")) {
                  var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error)
                    return "scope." + error;
                }
                if (message.logRecords != null && message.hasOwnProperty("logRecords")) {
                  if (!Array.isArray(message.logRecords))
                    return "logRecords: array expected";
                  for (var i = 0; i < message.logRecords.length; ++i) {
                    var error = $root.opentelemetry.proto.logs.v1.LogRecord.verify(message.logRecords[i]);
                    if (error)
                      return "logRecords." + error;
                  }
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) {
                  if (!$util.isString(message.schemaUrl))
                    return "schemaUrl: string expected";
                }
                return null;
              }, "verify");
              ScopeLogs.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.ScopeLogs)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.ScopeLogs();
                if (object.scope != null) {
                  if (typeof object.scope !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.scope: object expected");
                  message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope);
                }
                if (object.logRecords) {
                  if (!Array.isArray(object.logRecords))
                    throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: array expected");
                  message.logRecords = [];
                  for (var i = 0; i < object.logRecords.length; ++i) {
                    if (typeof object.logRecords[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected");
                    message.logRecords[i] = $root.opentelemetry.proto.logs.v1.LogRecord.fromObject(object.logRecords[i]);
                  }
                }
                if (object.schemaUrl != null)
                  message.schemaUrl = String(object.schemaUrl);
                return message;
              }, "fromObject");
              ScopeLogs.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.logRecords = [];
                if (options.defaults) {
                  object.scope = null;
                  object.schemaUrl = "";
                }
                if (message.scope != null && message.hasOwnProperty("scope"))
                  object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options);
                if (message.logRecords && message.logRecords.length) {
                  object.logRecords = [];
                  for (var j = 0; j < message.logRecords.length; ++j)
                    object.logRecords[j] = $root.opentelemetry.proto.logs.v1.LogRecord.toObject(message.logRecords[j], options);
                }
                if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl"))
                  object.schemaUrl = message.schemaUrl;
                return object;
              }, "toObject");
              ScopeLogs.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              ScopeLogs.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ScopeLogs";
              }, "getTypeUrl");
              return ScopeLogs;
            }();
            v1.SeverityNumber = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "SEVERITY_NUMBER_UNSPECIFIED"] = 0;
              values[valuesById[1] = "SEVERITY_NUMBER_TRACE"] = 1;
              values[valuesById[2] = "SEVERITY_NUMBER_TRACE2"] = 2;
              values[valuesById[3] = "SEVERITY_NUMBER_TRACE3"] = 3;
              values[valuesById[4] = "SEVERITY_NUMBER_TRACE4"] = 4;
              values[valuesById[5] = "SEVERITY_NUMBER_DEBUG"] = 5;
              values[valuesById[6] = "SEVERITY_NUMBER_DEBUG2"] = 6;
              values[valuesById[7] = "SEVERITY_NUMBER_DEBUG3"] = 7;
              values[valuesById[8] = "SEVERITY_NUMBER_DEBUG4"] = 8;
              values[valuesById[9] = "SEVERITY_NUMBER_INFO"] = 9;
              values[valuesById[10] = "SEVERITY_NUMBER_INFO2"] = 10;
              values[valuesById[11] = "SEVERITY_NUMBER_INFO3"] = 11;
              values[valuesById[12] = "SEVERITY_NUMBER_INFO4"] = 12;
              values[valuesById[13] = "SEVERITY_NUMBER_WARN"] = 13;
              values[valuesById[14] = "SEVERITY_NUMBER_WARN2"] = 14;
              values[valuesById[15] = "SEVERITY_NUMBER_WARN3"] = 15;
              values[valuesById[16] = "SEVERITY_NUMBER_WARN4"] = 16;
              values[valuesById[17] = "SEVERITY_NUMBER_ERROR"] = 17;
              values[valuesById[18] = "SEVERITY_NUMBER_ERROR2"] = 18;
              values[valuesById[19] = "SEVERITY_NUMBER_ERROR3"] = 19;
              values[valuesById[20] = "SEVERITY_NUMBER_ERROR4"] = 20;
              values[valuesById[21] = "SEVERITY_NUMBER_FATAL"] = 21;
              values[valuesById[22] = "SEVERITY_NUMBER_FATAL2"] = 22;
              values[valuesById[23] = "SEVERITY_NUMBER_FATAL3"] = 23;
              values[valuesById[24] = "SEVERITY_NUMBER_FATAL4"] = 24;
              return values;
            }();
            v1.LogRecordFlags = function() {
              var valuesById = {}, values = Object.create(valuesById);
              values[valuesById[0] = "LOG_RECORD_FLAGS_DO_NOT_USE"] = 0;
              values[valuesById[255] = "LOG_RECORD_FLAGS_TRACE_FLAGS_MASK"] = 255;
              return values;
            }();
            v1.LogRecord = function() {
              function LogRecord(properties) {
                this.attributes = [];
                if (properties) {
                  for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                      this[keys[i]] = properties[keys[i]];
                }
              }
              __name(LogRecord, "LogRecord");
              LogRecord.prototype.timeUnixNano = null;
              LogRecord.prototype.observedTimeUnixNano = null;
              LogRecord.prototype.severityNumber = null;
              LogRecord.prototype.severityText = null;
              LogRecord.prototype.body = null;
              LogRecord.prototype.attributes = $util.emptyArray;
              LogRecord.prototype.droppedAttributesCount = null;
              LogRecord.prototype.flags = null;
              LogRecord.prototype.traceId = null;
              LogRecord.prototype.spanId = null;
              LogRecord.prototype.eventName = null;
              LogRecord.create = /* @__PURE__ */ __name(function create(properties) {
                return new LogRecord(properties);
              }, "create");
              LogRecord.encode = /* @__PURE__ */ __name(function encode(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
                  writer.uint32(
                    /* id 1, wireType 1 =*/
                    9
                  ).fixed64(message.timeUnixNano);
                if (message.severityNumber != null && Object.hasOwnProperty.call(message, "severityNumber"))
                  writer.uint32(
                    /* id 2, wireType 0 =*/
                    16
                  ).int32(message.severityNumber);
                if (message.severityText != null && Object.hasOwnProperty.call(message, "severityText"))
                  writer.uint32(
                    /* id 3, wireType 2 =*/
                    26
                  ).string(message.severityText);
                if (message.body != null && Object.hasOwnProperty.call(message, "body"))
                  $root.opentelemetry.proto.common.v1.AnyValue.encode(message.body, writer.uint32(
                    /* id 5, wireType 2 =*/
                    42
                  ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i = 0; i < message.attributes.length; ++i)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(
                      /* id 6, wireType 2 =*/
                      50
                    ).fork()).ldelim();
                if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount"))
                  writer.uint32(
                    /* id 7, wireType 0 =*/
                    56
                  ).uint32(message.droppedAttributesCount);
                if (message.flags != null && Object.hasOwnProperty.call(message, "flags"))
                  writer.uint32(
                    /* id 8, wireType 5 =*/
                    69
                  ).fixed32(message.flags);
                if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId"))
                  writer.uint32(
                    /* id 9, wireType 2 =*/
                    74
                  ).bytes(message.traceId);
                if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId"))
                  writer.uint32(
                    /* id 10, wireType 2 =*/
                    82
                  ).bytes(message.spanId);
                if (message.observedTimeUnixNano != null && Object.hasOwnProperty.call(message, "observedTimeUnixNano"))
                  writer.uint32(
                    /* id 11, wireType 1 =*/
                    89
                  ).fixed64(message.observedTimeUnixNano);
                if (message.eventName != null && Object.hasOwnProperty.call(message, "eventName"))
                  writer.uint32(
                    /* id 12, wireType 2 =*/
                    98
                  ).string(message.eventName);
                return writer;
              }, "encode");
              LogRecord.encodeDelimited = /* @__PURE__ */ __name(function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
              }, "encodeDelimited");
              LogRecord.decode = /* @__PURE__ */ __name(function decode(reader, length, error) {
                if (!(reader instanceof $Reader))
                  reader = $Reader.create(reader);
                var end = length === void 0 ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogRecord();
                while (reader.pos < end) {
                  var tag = reader.uint32();
                  if (tag === error)
                    break;
                  switch (tag >>> 3) {
                    case 1: {
                      message.timeUnixNano = reader.fixed64();
                      break;
                    }
                    case 11: {
                      message.observedTimeUnixNano = reader.fixed64();
                      break;
                    }
                    case 2: {
                      message.severityNumber = reader.int32();
                      break;
                    }
                    case 3: {
                      message.severityText = reader.string();
                      break;
                    }
                    case 5: {
                      message.body = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32());
                      break;
                    }
                    case 6: {
                      if (!(message.attributes && message.attributes.length))
                        message.attributes = [];
                      message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32()));
                      break;
                    }
                    case 7: {
                      message.droppedAttributesCount = reader.uint32();
                      break;
                    }
                    case 8: {
                      message.flags = reader.fixed32();
                      break;
                    }
                    case 9: {
                      message.traceId = reader.bytes();
                      break;
                    }
                    case 10: {
                      message.spanId = reader.bytes();
                      break;
                    }
                    case 12: {
                      message.eventName = reader.string();
                      break;
                    }
                    default:
                      reader.skipType(tag & 7);
                      break;
                  }
                }
                return message;
              }, "decode");
              LogRecord.decodeDelimited = /* @__PURE__ */ __name(function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                  reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
              }, "decodeDelimited");
              LogRecord.verify = /* @__PURE__ */ __name(function verify(message) {
                if (typeof message !== "object" || message === null)
                  return "object expected";
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
                  if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high)))
                    return "timeUnixNano: integer|Long expected";
                }
                if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano")) {
                  if (!$util.isInteger(message.observedTimeUnixNano) && !(message.observedTimeUnixNano && $util.isInteger(message.observedTimeUnixNano.low) && $util.isInteger(message.observedTimeUnixNano.high)))
                    return "observedTimeUnixNano: integer|Long expected";
                }
                if (message.severityNumber != null && message.hasOwnProperty("severityNumber"))
                  switch (message.severityNumber) {
                    default:
                      return "severityNumber: enum value expected";
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                    case 10:
                    case 11:
                    case 12:
                    case 13:
                    case 14:
                    case 15:
                    case 16:
                    case 17:
                    case 18:
                    case 19:
                    case 20:
                    case 21:
                    case 22:
                    case 23:
                    case 24:
                      break;
                  }
                if (message.severityText != null && message.hasOwnProperty("severityText")) {
                  if (!$util.isString(message.severityText))
                    return "severityText: string expected";
                }
                if (message.body != null && message.hasOwnProperty("body")) {
                  var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.body);
                  if (error)
                    return "body." + error;
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i = 0; i < message.attributes.length; ++i) {
                    var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]);
                    if (error)
                      return "attributes." + error;
                  }
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) {
                  if (!$util.isInteger(message.droppedAttributesCount))
                    return "droppedAttributesCount: integer expected";
                }
                if (message.flags != null && message.hasOwnProperty("flags")) {
                  if (!$util.isInteger(message.flags))
                    return "flags: integer expected";
                }
                if (message.traceId != null && message.hasOwnProperty("traceId")) {
                  if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId)))
                    return "traceId: buffer expected";
                }
                if (message.spanId != null && message.hasOwnProperty("spanId")) {
                  if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId)))
                    return "spanId: buffer expected";
                }
                if (message.eventName != null && message.hasOwnProperty("eventName")) {
                  if (!$util.isString(message.eventName))
                    return "eventName: string expected";
                }
                return null;
              }, "verify");
              LogRecord.fromObject = /* @__PURE__ */ __name(function fromObject(object) {
                if (object instanceof $root.opentelemetry.proto.logs.v1.LogRecord)
                  return object;
                var message = new $root.opentelemetry.proto.logs.v1.LogRecord();
                if (object.timeUnixNano != null) {
                  if ($util.Long)
                    (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false;
                  else if (typeof object.timeUnixNano === "string")
                    message.timeUnixNano = parseInt(object.timeUnixNano, 10);
                  else if (typeof object.timeUnixNano === "number")
                    message.timeUnixNano = object.timeUnixNano;
                  else if (typeof object.timeUnixNano === "object")
                    message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber();
                }
                if (object.observedTimeUnixNano != null) {
                  if ($util.Long)
                    (message.observedTimeUnixNano = $util.Long.fromValue(object.observedTimeUnixNano)).unsigned = false;
                  else if (typeof object.observedTimeUnixNano === "string")
                    message.observedTimeUnixNano = parseInt(object.observedTimeUnixNano, 10);
                  else if (typeof object.observedTimeUnixNano === "number")
                    message.observedTimeUnixNano = object.observedTimeUnixNano;
                  else if (typeof object.observedTimeUnixNano === "object")
                    message.observedTimeUnixNano = new $util.LongBits(object.observedTimeUnixNano.low >>> 0, object.observedTimeUnixNano.high >>> 0).toNumber();
                }
                switch (object.severityNumber) {
                  default:
                    if (typeof object.severityNumber === "number") {
                      message.severityNumber = object.severityNumber;
                      break;
                    }
                    break;
                  case "SEVERITY_NUMBER_UNSPECIFIED":
                  case 0:
                    message.severityNumber = 0;
                    break;
                  case "SEVERITY_NUMBER_TRACE":
                  case 1:
                    message.severityNumber = 1;
                    break;
                  case "SEVERITY_NUMBER_TRACE2":
                  case 2:
                    message.severityNumber = 2;
                    break;
                  case "SEVERITY_NUMBER_TRACE3":
                  case 3:
                    message.severityNumber = 3;
                    break;
                  case "SEVERITY_NUMBER_TRACE4":
                  case 4:
                    message.severityNumber = 4;
                    break;
                  case "SEVERITY_NUMBER_DEBUG":
                  case 5:
                    message.severityNumber = 5;
                    break;
                  case "SEVERITY_NUMBER_DEBUG2":
                  case 6:
                    message.severityNumber = 6;
                    break;
                  case "SEVERITY_NUMBER_DEBUG3":
                  case 7:
                    message.severityNumber = 7;
                    break;
                  case "SEVERITY_NUMBER_DEBUG4":
                  case 8:
                    message.severityNumber = 8;
                    break;
                  case "SEVERITY_NUMBER_INFO":
                  case 9:
                    message.severityNumber = 9;
                    break;
                  case "SEVERITY_NUMBER_INFO2":
                  case 10:
                    message.severityNumber = 10;
                    break;
                  case "SEVERITY_NUMBER_INFO3":
                  case 11:
                    message.severityNumber = 11;
                    break;
                  case "SEVERITY_NUMBER_INFO4":
                  case 12:
                    message.severityNumber = 12;
                    break;
                  case "SEVERITY_NUMBER_WARN":
                  case 13:
                    message.severityNumber = 13;
                    break;
                  case "SEVERITY_NUMBER_WARN2":
                  case 14:
                    message.severityNumber = 14;
                    break;
                  case "SEVERITY_NUMBER_WARN3":
                  case 15:
                    message.severityNumber = 15;
                    break;
                  case "SEVERITY_NUMBER_WARN4":
                  case 16:
                    message.severityNumber = 16;
                    break;
                  case "SEVERITY_NUMBER_ERROR":
                  case 17:
                    message.severityNumber = 17;
                    break;
                  case "SEVERITY_NUMBER_ERROR2":
                  case 18:
                    message.severityNumber = 18;
                    break;
                  case "SEVERITY_NUMBER_ERROR3":
                  case 19:
                    message.severityNumber = 19;
                    break;
                  case "SEVERITY_NUMBER_ERROR4":
                  case 20:
                    message.severityNumber = 20;
                    break;
                  case "SEVERITY_NUMBER_FATAL":
                  case 21:
                    message.severityNumber = 21;
                    break;
                  case "SEVERITY_NUMBER_FATAL2":
                  case 22:
                    message.severityNumber = 22;
                    break;
                  case "SEVERITY_NUMBER_FATAL3":
                  case 23:
                    message.severityNumber = 23;
                    break;
                  case "SEVERITY_NUMBER_FATAL4":
                  case 24:
                    message.severityNumber = 24;
                    break;
                }
                if (object.severityText != null)
                  message.severityText = String(object.severityText);
                if (object.body != null) {
                  if (typeof object.body !== "object")
                    throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.body: object expected");
                  message.body = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.body);
                }
                if (object.attributes) {
                  if (!Array.isArray(object.attributes))
                    throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: array expected");
                  message.attributes = [];
                  for (var i = 0; i < object.attributes.length; ++i) {
                    if (typeof object.attributes[i] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: object expected");
                    message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]);
                  }
                }
                if (object.droppedAttributesCount != null)
                  message.droppedAttributesCount = object.droppedAttributesCount >>> 0;
                if (object.flags != null)
                  message.flags = object.flags >>> 0;
                if (object.traceId != null) {
                  if (typeof object.traceId === "string")
                    $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0);
                  else if (object.traceId.length >= 0)
                    message.traceId = object.traceId;
                }
                if (object.spanId != null) {
                  if (typeof object.spanId === "string")
                    $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0);
                  else if (object.spanId.length >= 0)
                    message.spanId = object.spanId;
                }
                if (object.eventName != null)
                  message.eventName = String(object.eventName);
                return message;
              }, "fromObject");
              LogRecord.toObject = /* @__PURE__ */ __name(function toObject(message, options) {
                if (!options)
                  options = {};
                var object = {};
                if (options.arrays || options.defaults)
                  object.attributes = [];
                if (options.defaults) {
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.timeUnixNano = options.longs === String ? "0" : 0;
                  object.severityNumber = options.enums === String ? "SEVERITY_NUMBER_UNSPECIFIED" : 0;
                  object.severityText = "";
                  object.body = null;
                  object.droppedAttributesCount = 0;
                  object.flags = 0;
                  if (options.bytes === String)
                    object.traceId = "";
                  else {
                    object.traceId = [];
                    if (options.bytes !== Array)
                      object.traceId = $util.newBuffer(object.traceId);
                  }
                  if (options.bytes === String)
                    object.spanId = "";
                  else {
                    object.spanId = [];
                    if (options.bytes !== Array)
                      object.spanId = $util.newBuffer(object.spanId);
                  }
                  if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.observedTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                  } else
                    object.observedTimeUnixNano = options.longs === String ? "0" : 0;
                  object.eventName = "";
                }
                if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano"))
                  if (typeof message.timeUnixNano === "number")
                    object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano;
                  else
                    object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano;
                if (message.severityNumber != null && message.hasOwnProperty("severityNumber"))
                  object.severityNumber = options.enums === String ? $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] === void 0 ? message.severityNumber : $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] : message.severityNumber;
                if (message.severityText != null && message.hasOwnProperty("severityText"))
                  object.severityText = message.severityText;
                if (message.body != null && message.hasOwnProperty("body"))
                  object.body = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.body, options);
                if (message.attributes && message.attributes.length) {
                  object.attributes = [];
                  for (var j = 0; j < message.attributes.length; ++j)
                    object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options);
                }
                if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount"))
                  object.droppedAttributesCount = message.droppedAttributesCount;
                if (message.flags != null && message.hasOwnProperty("flags"))
                  object.flags = message.flags;
                if (message.traceId != null && message.hasOwnProperty("traceId"))
                  object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId;
                if (message.spanId != null && message.hasOwnProperty("spanId"))
                  object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId;
                if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano"))
                  if (typeof message.observedTimeUnixNano === "number")
                    object.observedTimeUnixNano = options.longs === String ? String(message.observedTimeUnixNano) : message.observedTimeUnixNano;
                  else
                    object.observedTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.observedTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.observedTimeUnixNano.low >>> 0, message.observedTimeUnixNano.high >>> 0).toNumber() : message.observedTimeUnixNano;
                if (message.eventName != null && message.hasOwnProperty("eventName"))
                  object.eventName = message.eventName;
                return object;
              }, "toObject");
              LogRecord.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
              }, "toJSON");
              LogRecord.getTypeUrl = /* @__PURE__ */ __name(function getTypeUrl(typeUrlPrefix) {
                if (typeUrlPrefix === void 0) {
                  typeUrlPrefix = "type.googleapis.com";
                }
                return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogRecord";
              }, "getTypeUrl");
              return LogRecord;
            }();
            return v1;
          }();
          return logs3;
        }();
        return proto;
      }();
      return opentelemetry;
    }();
    module.exports = $root;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js
var require_hex_to_binary = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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;
    }
    __name(intValue, "intValue");
    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;
    }
    __name(hexToBinary, "hexToBinary");
    exports.hexToBinary = hexToBinary;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js
var require_utils3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getOtlpEncoder = exports.encodeAsString = exports.encodeAsLongBits = exports.toLongBits = exports.hrTimeToNanos = void 0;
    var core_1 = require_src3();
    var hex_to_binary_1 = require_hex_to_binary();
    function hrTimeToNanos(hrTime) {
      const NANOSECONDS = BigInt(1e9);
      return BigInt(hrTime[0]) * NANOSECONDS + BigInt(hrTime[1]);
    }
    __name(hrTimeToNanos, "hrTimeToNanos");
    exports.hrTimeToNanos = hrTimeToNanos;
    function toLongBits(value) {
      const low = Number(BigInt.asUintN(32, value));
      const high = Number(BigInt.asUintN(32, value >> BigInt(32)));
      return { low, high };
    }
    __name(toLongBits, "toLongBits");
    exports.toLongBits = toLongBits;
    function encodeAsLongBits(hrTime) {
      const nanos = hrTimeToNanos(hrTime);
      return toLongBits(nanos);
    }
    __name(encodeAsLongBits, "encodeAsLongBits");
    exports.encodeAsLongBits = encodeAsLongBits;
    function encodeAsString(hrTime) {
      const nanos = hrTimeToNanos(hrTime);
      return nanos.toString();
    }
    __name(encodeAsString, "encodeAsString");
    exports.encodeAsString = encodeAsString;
    var encodeTimestamp = typeof BigInt !== "undefined" ? encodeAsString : core_1.hrTimeToNanoseconds;
    function identity(value) {
      return value;
    }
    __name(identity, "identity");
    function optionalHexToBinary(str) {
      if (str === void 0)
        return void 0;
      return (0, hex_to_binary_1.hexToBinary)(str);
    }
    __name(optionalHexToBinary, "optionalHexToBinary");
    var DEFAULT_ENCODER = {
      encodeHrTime: encodeAsLongBits,
      encodeSpanContext: hex_to_binary_1.hexToBinary,
      encodeOptionalSpanContext: optionalHexToBinary
    };
    function getOtlpEncoder(options) {
      if (options === void 0) {
        return DEFAULT_ENCODER;
      }
      const useLongBits = options.useLongBits ?? true;
      const useHex = options.useHex ?? false;
      return {
        encodeHrTime: useLongBits ? encodeAsLongBits : encodeTimestamp,
        encodeSpanContext: useHex ? identity : hex_to_binary_1.hexToBinary,
        encodeOptionalSpanContext: useHex ? identity : optionalHexToBinary
      };
    }
    __name(getOtlpEncoder, "getOtlpEncoder");
    exports.getOtlpEncoder = getOtlpEncoder;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js
var require_internal = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toAnyValue = exports.toKeyValue = exports.toAttributes = exports.createInstrumentationScope = exports.createResource = void 0;
    function createResource(resource) {
      return {
        attributes: toAttributes(resource.attributes),
        droppedAttributesCount: 0
      };
    }
    __name(createResource, "createResource");
    exports.createResource = createResource;
    function createInstrumentationScope(scope) {
      return {
        name: scope.name,
        version: scope.version
      };
    }
    __name(createInstrumentationScope, "createInstrumentationScope");
    exports.createInstrumentationScope = createInstrumentationScope;
    function toAttributes(attributes) {
      return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key]));
    }
    __name(toAttributes, "toAttributes");
    exports.toAttributes = toAttributes;
    function toKeyValue(key, value) {
      return {
        key,
        value: toAnyValue(value)
      };
    }
    __name(toKeyValue, "toKeyValue");
    exports.toKeyValue = toKeyValue;
    function toAnyValue(value) {
      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: value };
      if (Array.isArray(value))
        return { arrayValue: { values: value.map(toAnyValue) } };
      if (t === "object" && value != null)
        return {
          kvlistValue: {
            values: Object.entries(value).map(([k, v]) => toKeyValue(k, v))
          }
        };
      return {};
    }
    __name(toAnyValue, "toAnyValue");
    exports.toAnyValue = toAnyValue;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js
var require_internal2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toLogAttributes = exports.createExportLogsServiceRequest = void 0;
    var utils_1 = require_utils3();
    var internal_1 = require_internal();
    function createExportLogsServiceRequest(logRecords, options) {
      const encoder = (0, utils_1.getOtlpEncoder)(options);
      return {
        resourceLogs: logRecordsToResourceLogs(logRecords, encoder)
      };
    }
    __name(createExportLogsServiceRequest, "createExportLogsServiceRequest");
    exports.createExportLogsServiceRequest = createExportLogsServiceRequest;
    function createResourceMap(logRecords) {
      const resourceMap = /* @__PURE__ */ new Map();
      for (const record of logRecords) {
        const { resource, instrumentationScope: { name, version = "", schemaUrl = "" } } = record;
        let ismMap = resourceMap.get(resource);
        if (!ismMap) {
          ismMap = /* @__PURE__ */ new Map();
          resourceMap.set(resource, ismMap);
        }
        const ismKey = `${name}@${version}:${schemaUrl}`;
        let records = ismMap.get(ismKey);
        if (!records) {
          records = [];
          ismMap.set(ismKey, records);
        }
        records.push(record);
      }
      return resourceMap;
    }
    __name(createResourceMap, "createResourceMap");
    function logRecordsToResourceLogs(logRecords, encoder) {
      const resourceMap = createResourceMap(logRecords);
      return Array.from(resourceMap, ([resource, ismMap]) => ({
        resource: (0, internal_1.createResource)(resource),
        scopeLogs: Array.from(ismMap, ([, scopeLogs]) => {
          return {
            scope: (0, internal_1.createInstrumentationScope)(scopeLogs[0].instrumentationScope),
            logRecords: scopeLogs.map((log) => toLogRecord(log, encoder)),
            schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl
          };
        }),
        schemaUrl: void 0
      }));
    }
    __name(logRecordsToResourceLogs, "logRecordsToResourceLogs");
    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),
        eventName: log.eventName,
        attributes: toLogAttributes(log.attributes),
        droppedAttributesCount: log.droppedAttributesCount,
        flags: log.spanContext?.traceFlags,
        traceId: encoder.encodeOptionalSpanContext(log.spanContext?.traceId),
        spanId: encoder.encodeOptionalSpanContext(log.spanContext?.spanId)
      };
    }
    __name(toLogRecord, "toLogRecord");
    function toSeverityNumber(severityNumber) {
      return severityNumber;
    }
    __name(toSeverityNumber, "toSeverityNumber");
    function toLogAttributes(attributes) {
      return Object.keys(attributes).map((key) => (0, internal_1.toKeyValue)(key, attributes[key]));
    }
    __name(toLogAttributes, "toLogAttributes");
    exports.toLogAttributes = toLogAttributes;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js
var require_logs2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProtobufLogsSerializer = void 0;
    var root = require_root2();
    var internal_1 = require_internal2();
    var logsResponseType = root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse;
    var logsRequestType = root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;
    exports.ProtobufLogsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportLogsServiceRequest)(arg);
        return logsRequestType.encode(request4).finish();
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        return logsResponseType.decode(arg);
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js
var require_protobuf = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProtobufLogsSerializer = void 0;
    var logs_1 = require_logs2();
    Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logs_1.ProtobufLogsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js
var require_AggregationTemporality = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AggregationTemporality = void 0;
    var AggregationTemporality2;
    (function(AggregationTemporality3) {
      AggregationTemporality3[AggregationTemporality3["DELTA"] = 0] = "DELTA";
      AggregationTemporality3[AggregationTemporality3["CUMULATIVE"] = 1] = "CUMULATIVE";
    })(AggregationTemporality2 = exports.AggregationTemporality || (exports.AggregationTemporality = {}));
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js
var require_MetricData = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DataPointType = exports.InstrumentType = void 0;
    var InstrumentType;
    (function(InstrumentType2) {
      InstrumentType2["COUNTER"] = "COUNTER";
      InstrumentType2["GAUGE"] = "GAUGE";
      InstrumentType2["HISTOGRAM"] = "HISTOGRAM";
      InstrumentType2["UP_DOWN_COUNTER"] = "UP_DOWN_COUNTER";
      InstrumentType2["OBSERVABLE_COUNTER"] = "OBSERVABLE_COUNTER";
      InstrumentType2["OBSERVABLE_GAUGE"] = "OBSERVABLE_GAUGE";
      InstrumentType2["OBSERVABLE_UP_DOWN_COUNTER"] = "OBSERVABLE_UP_DOWN_COUNTER";
    })(InstrumentType = exports.InstrumentType || (exports.InstrumentType = {}));
    var DataPointType;
    (function(DataPointType2) {
      DataPointType2[DataPointType2["HISTOGRAM"] = 0] = "HISTOGRAM";
      DataPointType2[DataPointType2["EXPONENTIAL_HISTOGRAM"] = 1] = "EXPONENTIAL_HISTOGRAM";
      DataPointType2[DataPointType2["GAUGE"] = 2] = "GAUGE";
      DataPointType2[DataPointType2["SUM"] = 3] = "SUM";
    })(DataPointType = exports.DataPointType || (exports.DataPointType = {}));
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/utils.js
var require_utils4 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.equalsCaseInsensitive = exports.binarySearchUB = exports.setEquals = exports.FlatMap = exports.isPromiseAllSettledRejectionResult = exports.PromiseAllSettled = exports.callWithTimeout = exports.TimeoutError = exports.instrumentationScopeId = exports.hashAttributes = exports.isNotNullish = void 0;
    function isNotNullish(item) {
      return item !== void 0 && item !== null;
    }
    __name(isNotNullish, "isNotNullish");
    exports.isNotNullish = isNotNullish;
    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]]));
    }
    __name(hashAttributes, "hashAttributes");
    exports.hashAttributes = hashAttributes;
    function instrumentationScopeId(instrumentationScope) {
      return `${instrumentationScope.name}:${instrumentationScope.version ?? ""}:${instrumentationScope.schemaUrl ?? ""}`;
    }
    __name(instrumentationScopeId, "instrumentationScopeId");
    exports.instrumentationScopeId = instrumentationScopeId;
    var TimeoutError = class _TimeoutError extends Error {
      static {
        __name(this, "TimeoutError");
      }
      constructor(message) {
        super(message);
        Object.setPrototypeOf(this, _TimeoutError.prototype);
      }
    };
    exports.TimeoutError = TimeoutError;
    function callWithTimeout(promise, timeout) {
      let timeoutHandle;
      const timeoutPromise = new Promise(/* @__PURE__ */ __name(function timeoutFunction(_resolve, reject) {
        timeoutHandle = setTimeout(/* @__PURE__ */ __name(function timeoutHandler() {
          reject(new TimeoutError("Operation timed out."));
        }, "timeoutHandler"), timeout);
      }, "timeoutFunction"));
      return Promise.race([promise, timeoutPromise]).then((result) => {
        clearTimeout(timeoutHandle);
        return result;
      }, (reason) => {
        clearTimeout(timeoutHandle);
        throw reason;
      });
    }
    __name(callWithTimeout, "callWithTimeout");
    exports.callWithTimeout = callWithTimeout;
    async function PromiseAllSettled(promises) {
      return Promise.all(promises.map(async (p) => {
        try {
          const ret = await p;
          return {
            status: "fulfilled",
            value: ret
          };
        } catch (e) {
          return {
            status: "rejected",
            reason: e
          };
        }
      }));
    }
    __name(PromiseAllSettled, "PromiseAllSettled");
    exports.PromiseAllSettled = PromiseAllSettled;
    function isPromiseAllSettledRejectionResult(it) {
      return it.status === "rejected";
    }
    __name(isPromiseAllSettledRejectionResult, "isPromiseAllSettledRejectionResult");
    exports.isPromiseAllSettledRejectionResult = isPromiseAllSettledRejectionResult;
    function FlatMap(arr, fn) {
      const result = [];
      arr.forEach((it) => {
        result.push(...fn(it));
      });
      return result;
    }
    __name(FlatMap, "FlatMap");
    exports.FlatMap = FlatMap;
    function setEquals(lhs, rhs) {
      if (lhs.size !== rhs.size) {
        return false;
      }
      for (const item of lhs) {
        if (!rhs.has(item)) {
          return false;
        }
      }
      return true;
    }
    __name(setEquals, "setEquals");
    exports.setEquals = setEquals;
    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;
    }
    __name(binarySearchUB, "binarySearchUB");
    exports.binarySearchUB = binarySearchUB;
    function equalsCaseInsensitive(lhs, rhs) {
      return lhs.toLowerCase() === rhs.toLowerCase();
    }
    __name(equalsCaseInsensitive, "equalsCaseInsensitive");
    exports.equalsCaseInsensitive = equalsCaseInsensitive;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js
var require_types2 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AggregatorKind = void 0;
    var AggregatorKind;
    (function(AggregatorKind2) {
      AggregatorKind2[AggregatorKind2["DROP"] = 0] = "DROP";
      AggregatorKind2[AggregatorKind2["SUM"] = 1] = "SUM";
      AggregatorKind2[AggregatorKind2["LAST_VALUE"] = 2] = "LAST_VALUE";
      AggregatorKind2[AggregatorKind2["HISTOGRAM"] = 3] = "HISTOGRAM";
      AggregatorKind2[AggregatorKind2["EXPONENTIAL_HISTOGRAM"] = 4] = "EXPONENTIAL_HISTOGRAM";
    })(AggregatorKind = exports.AggregatorKind || (exports.AggregatorKind = {}));
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js
var require_Drop = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DropAggregator = void 0;
    var types_1 = require_types2();
    var DropAggregator = class {
      static {
        __name(this, "DropAggregator");
      }
      kind = types_1.AggregatorKind.DROP;
      createAccumulation() {
        return void 0;
      }
      merge(_previous, _delta) {
        return void 0;
      }
      diff(_previous, _current) {
        return void 0;
      }
      toMetricData(_descriptor, _aggregationTemporality, _accumulationByAttributes, _endTime) {
        return void 0;
      }
    };
    exports.DropAggregator = DropAggregator;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js
var require_Histogram = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HistogramAggregator = exports.HistogramAccumulation = void 0;
    var types_1 = require_types2();
    var MetricData_1 = require_MetricData();
    var utils_1 = require_utils4();
    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
      };
    }
    __name(createNewEmptyCheckpoint, "createNewEmptyCheckpoint");
    var HistogramAccumulation = class {
      static {
        __name(this, "HistogramAccumulation");
      }
      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;
    var HistogramAggregator = class {
      static {
        __name(this, "HistogramAggregator");
      }
      _boundaries;
      _recordMinMax;
      kind = types_1.AggregatorKind.HISTOGRAM;
      /**
       * @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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js
var require_Buckets = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Buckets = void 0;
    var Buckets = class _Buckets {
      static {
        __name(this, "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;
    var BucketsBacking = class _BucketsBacking {
      static {
        __name(this, "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]);
      }
    };
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js
var require_ieee754 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getSignificand = exports.getNormalBase2 = exports.MIN_VALUE = exports.MAX_NORMAL_EXPONENT = exports.MIN_NORMAL_EXPONENT = exports.SIGNIFICAND_WIDTH = void 0;
    exports.SIGNIFICAND_WIDTH = 52;
    var EXPONENT_MASK = 2146435072;
    var SIGNIFICAND_MASK = 1048575;
    var EXPONENT_BIAS = 1023;
    exports.MIN_NORMAL_EXPONENT = -EXPONENT_BIAS + 1;
    exports.MAX_NORMAL_EXPONENT = EXPONENT_BIAS;
    exports.MIN_VALUE = Math.pow(2, -1022);
    function getNormalBase2(value) {
      const dv = new DataView(new ArrayBuffer(8));
      dv.setFloat64(0, value);
      const hiBits = dv.getUint32(0);
      const expBits = (hiBits & EXPONENT_MASK) >> 20;
      return expBits - EXPONENT_BIAS;
    }
    __name(getNormalBase2, "getNormalBase2");
    exports.getNormalBase2 = getNormalBase2;
    function getSignificand(value) {
      const dv = new DataView(new ArrayBuffer(8));
      dv.setFloat64(0, value);
      const hiBits = dv.getUint32(0);
      const loBits = dv.getUint32(4);
      const significandHiBits = (hiBits & SIGNIFICAND_MASK) * Math.pow(2, 32);
      return significandHiBits + loBits;
    }
    __name(getSignificand, "getSignificand");
    exports.getSignificand = getSignificand;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js
var require_util3 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.nextGreaterSquare = exports.ldexp = void 0;
    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);
    }
    __name(ldexp, "ldexp");
    exports.ldexp = ldexp;
    function nextGreaterSquare(v) {
      v--;
      v |= v >> 1;
      v |= v >> 2;
      v |= v >> 4;
      v |= v >> 8;
      v |= v >> 16;
      v++;
      return v;
    }
    __name(nextGreaterSquare, "nextGreaterSquare");
    exports.nextGreaterSquare = nextGreaterSquare;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js
var require_types3 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MappingError = void 0;
    var MappingError = class extends Error {
      static {
        __name(this, "MappingError");
      }
    };
    exports.MappingError = MappingError;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js
var require_ExponentMapping = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExponentMapping = void 0;
    var ieee754 = require_ieee754();
    var util = require_util3();
    var types_1 = require_types3();
    var ExponentMapping = class {
      static {
        __name(this, "ExponentMapping");
      }
      _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();
        }
        const exp = ieee754.getNormalBase2(value);
        const correction = this._rightShift(ieee754.getSignificand(value) - 1, ieee754.SIGNIFICAND_WIDTH);
        return exp + correction >> 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;
      }
      _rightShift(value, shift) {
        return Math.floor(value * Math.pow(2, -shift));
      }
    };
    exports.ExponentMapping = ExponentMapping;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js
var require_LogarithmMapping = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LogarithmMapping = void 0;
    var ieee754 = require_ieee754();
    var util = require_util3();
    var types_1 = require_types3();
    var LogarithmMapping = class {
      static {
        __name(this, "LogarithmMapping");
      }
      _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.getSignificand(value) === 0) {
          const exp = ieee754.getNormalBase2(value);
          return (exp << 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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js
var require_getMapping = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getMapping = void 0;
    var ExponentMapping_1 = require_ExponentMapping();
    var LogarithmMapping_1 = require_LogarithmMapping();
    var types_1 = require_types3();
    var MIN_SCALE = -10;
    var MAX_SCALE = 20;
    var PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => {
      if (i > 10) {
        return new LogarithmMapping_1.LogarithmMapping(i - 10);
      }
      return new ExponentMapping_1.ExponentMapping(i - 10);
    });
    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];
    }
    __name(getMapping, "getMapping");
    exports.getMapping = getMapping;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js
var require_ExponentialHistogram = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = void 0;
    var types_1 = require_types2();
    var MetricData_1 = require_MetricData();
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var Buckets_1 = require_Buckets();
    var getMapping_1 = require_getMapping();
    var util_1 = require_util3();
    var HighLow = class _HighLow {
      static {
        __name(this, "HighLow");
      }
      low;
      high;
      static combine(h1, h2) {
        return new _HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high));
      }
      constructor(low, high) {
        this.low = low;
        this.high = high;
      }
    };
    var MAX_SCALE = 20;
    var DEFAULT_MAX_SIZE = 160;
    var MIN_MAX_SIZE = 2;
    var ExponentialHistogramAccumulation = class _ExponentialHistogramAccumulation {
      static {
        __name(this, "ExponentialHistogramAccumulation");
      }
      startTime;
      _maxSize;
      _recordMinMax;
      _sum;
      _count;
      _zeroCount;
      _min;
      _max;
      _positive;
      _negative;
      _mapping;
      constructor(startTime = 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.isNaN(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++) {
          const ourIndex = theirOffset + i >> theirChange;
          let bucketIndex = ourIndex - ours.indexBase;
          if (bucketIndex < 0) {
            bucketIndex += ours.backing.length;
          }
          ours.decrementBucket(bucketIndex, theirs.at(i));
        }
        ours.trim();
      }
    };
    exports.ExponentialHistogramAccumulation = ExponentialHistogramAccumulation;
    var ExponentialHistogramAggregator = class {
      static {
        __name(this, "ExponentialHistogramAggregator");
      }
      _maxSize;
      _recordMinMax;
      kind = types_1.AggregatorKind.EXPONENTIAL_HISTOGRAM;
      /**
       * @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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js
var require_LastValue = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LastValueAggregator = exports.LastValueAccumulation = void 0;
    var types_1 = require_types2();
    var core_1 = require_src3();
    var MetricData_1 = require_MetricData();
    var LastValueAccumulation = class {
      static {
        __name(this, "LastValueAccumulation");
      }
      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;
    var LastValueAggregator = class {
      static {
        __name(this, "LastValueAggregator");
      }
      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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js
var require_Sum = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SumAggregator = exports.SumAccumulation = void 0;
    var types_1 = require_types2();
    var MetricData_1 = require_MetricData();
    var SumAccumulation = class {
      static {
        __name(this, "SumAccumulation");
      }
      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;
    var SumAggregator = class {
      static {
        __name(this, "SumAggregator");
      }
      monotonic;
      kind = types_1.AggregatorKind.SUM;
      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 (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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js
var require_aggregator = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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: /* @__PURE__ */ __name(function() {
      return Drop_1.DropAggregator;
    }, "get") });
    var Histogram_1 = require_Histogram();
    Object.defineProperty(exports, "HistogramAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Histogram_1.HistogramAccumulation;
    }, "get") });
    Object.defineProperty(exports, "HistogramAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Histogram_1.HistogramAggregator;
    }, "get") });
    var ExponentialHistogram_1 = require_ExponentialHistogram();
    Object.defineProperty(exports, "ExponentialHistogramAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ExponentialHistogram_1.ExponentialHistogramAccumulation;
    }, "get") });
    Object.defineProperty(exports, "ExponentialHistogramAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ExponentialHistogram_1.ExponentialHistogramAggregator;
    }, "get") });
    var LastValue_1 = require_LastValue();
    Object.defineProperty(exports, "LastValueAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LastValue_1.LastValueAccumulation;
    }, "get") });
    Object.defineProperty(exports, "LastValueAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LastValue_1.LastValueAggregator;
    }, "get") });
    var Sum_1 = require_Sum();
    Object.defineProperty(exports, "SumAccumulation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Sum_1.SumAccumulation;
    }, "get") });
    Object.defineProperty(exports, "SumAggregator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Sum_1.SumAggregator;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js
var require_Aggregation = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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;
    var api = (init_esm(), __toCommonJS(esm_exports));
    var aggregator_1 = require_aggregator();
    var MetricData_1 = require_MetricData();
    var DropAggregation = class _DropAggregation {
      static {
        __name(this, "DropAggregation");
      }
      static DEFAULT_INSTANCE = new aggregator_1.DropAggregator();
      createAggregator(_instrument) {
        return _DropAggregation.DEFAULT_INSTANCE;
      }
    };
    exports.DropAggregation = DropAggregation;
    var SumAggregation = class _SumAggregation {
      static {
        __name(this, "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;
    var LastValueAggregation = class _LastValueAggregation {
      static {
        __name(this, "LastValueAggregation");
      }
      static DEFAULT_INSTANCE = new aggregator_1.LastValueAggregator();
      createAggregator(_instrument) {
        return _LastValueAggregation.DEFAULT_INSTANCE;
      }
    };
    exports.LastValueAggregation = LastValueAggregation;
    var HistogramAggregation = class _HistogramAggregation {
      static {
        __name(this, "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;
    var ExplicitBucketHistogramAggregation = class {
      static {
        __name(this, "ExplicitBucketHistogramAggregation");
      }
      _recordMinMax;
      _boundaries;
      /**
       * @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) {
        this._recordMinMax = _recordMinMax;
        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);
      }
      createAggregator(_instrument) {
        return new aggregator_1.HistogramAggregator(this._boundaries, this._recordMinMax);
      }
    };
    exports.ExplicitBucketHistogramAggregation = ExplicitBucketHistogramAggregation;
    var ExponentialHistogramAggregation = class {
      static {
        __name(this, "ExponentialHistogramAggregation");
      }
      _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;
    var DefaultAggregation = class {
      static {
        __name(this, "DefaultAggregation");
      }
      _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();
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js
var require_AggregationOption = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toAggregation = exports.AggregationType = void 0;
    var Aggregation_1 = require_Aggregation();
    var AggregationType;
    (function(AggregationType2) {
      AggregationType2[AggregationType2["DEFAULT"] = 0] = "DEFAULT";
      AggregationType2[AggregationType2["DROP"] = 1] = "DROP";
      AggregationType2[AggregationType2["SUM"] = 2] = "SUM";
      AggregationType2[AggregationType2["LAST_VALUE"] = 3] = "LAST_VALUE";
      AggregationType2[AggregationType2["EXPLICIT_BUCKET_HISTOGRAM"] = 4] = "EXPLICIT_BUCKET_HISTOGRAM";
      AggregationType2[AggregationType2["EXPONENTIAL_HISTOGRAM"] = 5] = "EXPONENTIAL_HISTOGRAM";
    })(AggregationType = exports.AggregationType || (exports.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");
      }
    }
    __name(toAggregation, "toAggregation");
    exports.toAggregation = toAggregation;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js
var require_AggregationSelector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = exports.DEFAULT_AGGREGATION_SELECTOR = void 0;
    var AggregationTemporality_1 = require_AggregationTemporality();
    var AggregationOption_1 = require_AggregationOption();
    var DEFAULT_AGGREGATION_SELECTOR = /* @__PURE__ */ __name((_instrumentType) => {
      return {
        type: AggregationOption_1.AggregationType.DEFAULT
      };
    }, "DEFAULT_AGGREGATION_SELECTOR");
    exports.DEFAULT_AGGREGATION_SELECTOR = DEFAULT_AGGREGATION_SELECTOR;
    var DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = /* @__PURE__ */ __name((_instrumentType) => AggregationTemporality_1.AggregationTemporality.CUMULATIVE, "DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR");
    exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js
var require_MetricReader = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MetricReader = void 0;
    var api = (init_esm(), __toCommonJS(esm_exports));
    var utils_1 = require_utils4();
    var AggregationSelector_1 = require_AggregationSelector();
    var MetricReader = class {
      static {
        __name(this, "MetricReader");
      }
      // Tracks the shutdown state.
      // TODO: use BindOncePromise here once a new version of @opentelemetry/core is available.
      _shutdown = false;
      // Additional MetricProducers which will be combined with the SDK's output
      _metricProducers;
      // MetricProducer used by this instance which produces metrics from the SDK
      _sdkMetricProducer;
      _aggregationTemporalitySelector;
      _aggregationSelector;
      _cardinalitySelector;
      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;
      }
      setMetricProducer(metricProducer) {
        if (this._sdkMetricProducer) {
          throw new Error("MetricReader can not be bound to a MeterProvider again.");
        }
        this._sdkMetricProducer = metricProducer;
        this.onInitialized();
      }
      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 [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([
          this._sdkMetricProducer.collect({
            timeoutMillis: options?.timeoutMillis
          }),
          ...this._metricProducers.map((producer) => producer.collect({
            timeoutMillis: options?.timeoutMillis
          }))
        ]);
        const errors = sdkCollectionResults.errors.concat((0, utils_1.FlatMap)(additionalCollectionResults, (result) => result.errors));
        const resource = sdkCollectionResults.resourceMetrics.resource;
        const scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat((0, utils_1.FlatMap)(additionalCollectionResults, (result) => result.resourceMetrics.scopeMetrics));
        return {
          resourceMetrics: {
            resource,
            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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js
var require_PeriodicExportingMetricReader = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PeriodicExportingMetricReader = void 0;
    var api = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var MetricReader_1 = require_MetricReader();
    var utils_1 = require_utils4();
    var PeriodicExportingMetricReader2 = class extends MetricReader_1.MetricReader {
      static {
        __name(this, "PeriodicExportingMetricReader");
      }
      _interval;
      _exporter;
      _exportInterval;
      _exportTimeout;
      constructor(options) {
        super({
          aggregationSelector: options.exporter.selectAggregation?.bind(options.exporter),
          aggregationTemporalitySelector: options.exporter.selectAggregationTemporality?.bind(options.exporter),
          metricProducers: options.metricProducers
        });
        if (options.exportIntervalMillis !== void 0 && options.exportIntervalMillis <= 0) {
          throw Error("exportIntervalMillis must be greater than 0");
        }
        if (options.exportTimeoutMillis !== void 0 && options.exportTimeoutMillis <= 0) {
          throw Error("exportTimeoutMillis must be greater than 0");
        }
        if (options.exportTimeoutMillis !== void 0 && options.exportIntervalMillis !== void 0 && options.exportIntervalMillis < options.exportTimeoutMillis) {
          throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");
        }
        this._exportInterval = options.exportIntervalMillis ?? 6e4;
        this._exportTimeout = options.exportTimeoutMillis ?? 3e4;
        this._exporter = options.exporter;
      }
      async _runOnce() {
        try {
          await (0, utils_1.callWithTimeout)(this._doRun(), this._exportTimeout);
        } catch (err) {
          if (err instanceof utils_1.TimeoutError) {
            api.diag.error("Export took longer than %s milliseconds and timed out.", this._exportTimeout);
            return;
          }
          (0, core_1.globalErrorHandler)(err);
        }
      }
      async _doRun() {
        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 result = await core_1.internal._export(this._exporter, resourceMetrics);
        if (result.code !== core_1.ExportResultCode.SUCCESS) {
          throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${result.error})`);
        }
      }
      onInitialized() {
        this._interval = setInterval(() => {
          void this._runOnce();
        }, this._exportInterval);
        (0, core_1.unrefTimer)(this._interval);
      }
      async onForceFlush() {
        await this._runOnce();
        await this._exporter.forceFlush();
      }
      async onShutdown() {
        if (this._interval) {
          clearInterval(this._interval);
        }
        await this.onForceFlush();
        await this._exporter.shutdown();
      }
    };
    exports.PeriodicExportingMetricReader = PeriodicExportingMetricReader2;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js
var require_InMemoryMetricExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InMemoryMetricExporter = void 0;
    var core_1 = require_src3();
    var InMemoryMetricExporter = class {
      static {
        __name(this, "InMemoryMetricExporter");
      }
      _shutdown = false;
      _aggregationTemporality;
      _metrics = [];
      constructor(aggregationTemporality) {
        this._aggregationTemporality = aggregationTemporality;
      }
      /**
       * @inheritedDoc
       */
      export(metrics2, resultCallback) {
        if (this._shutdown) {
          setTimeout(() => resultCallback({ code: core_1.ExportResultCode.FAILED }), 0);
          return;
        }
        this._metrics.push(metrics2);
        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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js
var require_ConsoleMetricExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConsoleMetricExporter = void 0;
    var core_1 = require_src3();
    var AggregationSelector_1 = require_AggregationSelector();
    var ConsoleMetricExporter = class _ConsoleMetricExporter {
      static {
        __name(this, "ConsoleMetricExporter");
      }
      _shutdown = false;
      _temporalitySelector;
      constructor(options) {
        this._temporalitySelector = options?.temporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
      }
      export(metrics2, resultCallback) {
        if (this._shutdown) {
          setImmediate(resultCallback, { code: core_1.ExportResultCode.FAILED });
          return;
        }
        return _ConsoleMetricExporter._sendMetrics(metrics2, resultCallback);
      }
      forceFlush() {
        return Promise.resolve();
      }
      selectAggregationTemporality(_instrumentType) {
        return this._temporalitySelector(_instrumentType);
      }
      shutdown() {
        this._shutdown = true;
        return Promise.resolve();
      }
      static _sendMetrics(metrics2, done) {
        for (const scopeMetrics of metrics2.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;
  }
});

// node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js
var require_default_service_name = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultServiceName = void 0;
    function defaultServiceName() {
      return `unknown_service:${process.argv0}`;
    }
    __name(defaultServiceName, "defaultServiceName");
    exports.defaultServiceName = defaultServiceName;
  }
});

// node_modules/@opentelemetry/resources/build/src/platform/node/index.js
var require_node4 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultServiceName = void 0;
    var default_service_name_1 = require_default_service_name();
    Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return default_service_name_1.defaultServiceName;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/platform/index.js
var require_platform3 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultServiceName = void 0;
    var node_1 = require_node4();
    Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.defaultServiceName;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/utils.js
var require_utils5 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.identity = exports.isPromiseLike = void 0;
    var isPromiseLike = /* @__PURE__ */ __name((val) => {
      return val !== null && typeof val === "object" && typeof val.then === "function";
    }, "isPromiseLike");
    exports.isPromiseLike = isPromiseLike;
    function identity(_) {
      return _;
    }
    __name(identity, "identity");
    exports.identity = identity;
  }
});

// node_modules/@opentelemetry/resources/build/src/ResourceImpl.js
var require_ResourceImpl = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/ResourceImpl.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultResource = exports.emptyResource = exports.resourceFromDetectedResource = exports.resourceFromAttributes = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var platform_1 = require_platform3();
    var utils_1 = require_utils5();
    var ResourceImpl = class _ResourceImpl {
      static {
        __name(this, "ResourceImpl");
      }
      _rawAttributes;
      _asyncAttributesPending = false;
      _memoizedAttributes;
      static FromAttributeList(attributes) {
        const res = new _ResourceImpl({});
        res._rawAttributes = guardedRawAttributes(attributes);
        res._asyncAttributesPending = attributes.filter(([_, val]) => (0, utils_1.isPromiseLike)(val)).length > 0;
        return res;
      }
      constructor(resource) {
        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);
      }
      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;
      }
      merge(resource) {
        if (resource == null)
          return this;
        return _ResourceImpl.FromAttributeList([
          ...resource.getRawAttributes(),
          ...this.getRawAttributes()
        ]);
      }
    };
    function resourceFromAttributes3(attributes) {
      return ResourceImpl.FromAttributeList(Object.entries(attributes));
    }
    __name(resourceFromAttributes3, "resourceFromAttributes");
    exports.resourceFromAttributes = resourceFromAttributes3;
    function resourceFromDetectedResource(detectedResource) {
      return new ResourceImpl(detectedResource);
    }
    __name(resourceFromDetectedResource, "resourceFromDetectedResource");
    exports.resourceFromDetectedResource = resourceFromDetectedResource;
    function emptyResource() {
      return resourceFromAttributes3({});
    }
    __name(emptyResource, "emptyResource");
    exports.emptyResource = emptyResource;
    function defaultResource() {
      return resourceFromAttributes3({
        [semantic_conventions_1.ATTR_SERVICE_NAME]: (0, platform_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]
      });
    }
    __name(defaultResource, "defaultResource");
    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 void 0;
            })
          ];
        }
        return [k, v];
      });
    }
    __name(guardedRawAttributes, "guardedRawAttributes");
  }
});

// node_modules/@opentelemetry/resources/build/src/detect-resources.js
var require_detect_resources = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detect-resources.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.detectResources = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var ResourceImpl_1 = require_ResourceImpl();
    var detectResources = /* @__PURE__ */ __name((config = {}) => {
      const resources = (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)();
        }
      });
      return resources.reduce((acc, resource) => acc.merge(resource), (0, ResourceImpl_1.emptyResource)());
    }, "detectResources");
    exports.detectResources = detectResources;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js
var require_EnvDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.envDetector = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src3();
    var EnvDetector = class {
      static {
        __name(this, "EnvDetector");
      }
      // Type, attribute keys, and attribute values should not exceed 256 characters.
      _MAX_LENGTH = 255;
      // OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of attributes.
      _COMMA_SEPARATOR = ",";
      // OTEL_RESOURCE_ATTRIBUTES contains key value pair separated by '='.
      _LABEL_KEY_VALUE_SPLITTER = "=";
      _ERROR_MESSAGE_INVALID_CHARS = "should be a ASCII string with a length greater than 0 and not exceed " + this._MAX_LENGTH + " characters.";
      _ERROR_MESSAGE_INVALID_VALUE = "should be a ASCII string with a length not exceed " + this._MAX_LENGTH + " characters.";
      /**
       * 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.message}`);
          }
        }
        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 describing
       * the source in more detail, e.g. “key1=val1,key2=val2”. Domain names and
       * paths are accepted as attribute keys. Values may be quoted or unquoted in
       * general. If a value contains whitespace, =, or " characters, it must
       * always be quoted.
       *
       * @param rawEnvAttributes The resource attributes as a comma-separated list
       * of key/value pairs.
       * @returns The sanitized resource attributes.
       */
      _parseResourceAttributes(rawEnvAttributes) {
        if (!rawEnvAttributes)
          return {};
        const attributes = {};
        const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR, -1);
        for (const rawAttribute of rawAttributes) {
          const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER, -1);
          if (keyValuePair.length !== 2) {
            continue;
          }
          let [key, value] = keyValuePair;
          key = key.trim();
          value = value.trim().split(/^"|"$/).join("");
          if (!this._isValidAndNotEmpty(key)) {
            throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);
          }
          if (!this._isValid(value)) {
            throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);
          }
          attributes[key] = decodeURIComponent(value);
        }
        return attributes;
      }
      /**
       * Determines whether the given String is a valid printable ASCII string with
       * a length not exceed _MAX_LENGTH characters.
       *
       * @param str The String to be validated.
       * @returns Whether the String is valid.
       */
      _isValid(name) {
        return name.length <= this._MAX_LENGTH && this._isBaggageOctetString(name);
      }
      // https://www.w3.org/TR/baggage/#definition
      _isBaggageOctetString(str) {
        for (let i = 0; i < str.length; i++) {
          const ch = str.charCodeAt(i);
          if (ch < 33 || ch === 44 || ch === 59 || ch === 92 || ch > 126) {
            return false;
          }
        }
        return true;
      }
      /**
       * Determines whether the given String is a valid printable ASCII string with
       * a length greater than 0 and not exceed _MAX_LENGTH characters.
       *
       * @param str The String to be validated.
       * @returns Whether the String is valid and not empty.
       */
      _isValidAndNotEmpty(str) {
        return str.length > 0 && this._isValid(str);
      }
    };
    exports.envDetector = new EnvDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/semconv.js
var require_semconv2 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/semconv.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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;
    exports.ATTR_CLOUD_ACCOUNT_ID = "cloud.account.id";
    exports.ATTR_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone";
    exports.ATTR_CLOUD_PROVIDER = "cloud.provider";
    exports.ATTR_CLOUD_REGION = "cloud.region";
    exports.ATTR_CONTAINER_ID = "container.id";
    exports.ATTR_CONTAINER_IMAGE_NAME = "container.image.name";
    exports.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags";
    exports.ATTR_CONTAINER_NAME = "container.name";
    exports.ATTR_HOST_ARCH = "host.arch";
    exports.ATTR_HOST_ID = "host.id";
    exports.ATTR_HOST_IMAGE_ID = "host.image.id";
    exports.ATTR_HOST_IMAGE_NAME = "host.image.name";
    exports.ATTR_HOST_IMAGE_VERSION = "host.image.version";
    exports.ATTR_HOST_NAME = "host.name";
    exports.ATTR_HOST_TYPE = "host.type";
    exports.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name";
    exports.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name";
    exports.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name";
    exports.ATTR_K8S_POD_NAME = "k8s.pod.name";
    exports.ATTR_OS_TYPE = "os.type";
    exports.ATTR_OS_VERSION = "os.version";
    exports.ATTR_PROCESS_COMMAND = "process.command";
    exports.ATTR_PROCESS_COMMAND_ARGS = "process.command_args";
    exports.ATTR_PROCESS_EXECUTABLE_NAME = "process.executable.name";
    exports.ATTR_PROCESS_EXECUTABLE_PATH = "process.executable.path";
    exports.ATTR_PROCESS_OWNER = "process.owner";
    exports.ATTR_PROCESS_PID = "process.pid";
    exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description";
    exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
    exports.ATTR_PROCESS_RUNTIME_VERSION = "process.runtime.version";
    exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id";
    exports.ATTR_SERVICE_NAMESPACE = "service.namespace";
    exports.ATTR_WEBENGINE_DESCRIPTION = "webengine.description";
    exports.ATTR_WEBENGINE_NAME = "webengine.name";
    exports.ATTR_WEBENGINE_VERSION = "webengine.version";
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js
var require_getMachineId = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getMachineId = void 0;
    var process2 = __require("process");
    var getMachineIdImpl;
    async function getMachineId() {
      if (!getMachineIdImpl) {
        switch (process2.platform) {
          case "darwin":
            getMachineIdImpl = (await import("./getMachineId-darwin-HPQPEMZR.js")).getMachineId;
            break;
          case "linux":
            getMachineIdImpl = (await import("./getMachineId-linux-AUARKYHL.js")).getMachineId;
            break;
          case "freebsd":
            getMachineIdImpl = (await import("./getMachineId-bsd-4CASPIU4.js")).getMachineId;
            break;
          case "win32":
            getMachineIdImpl = (await import("./getMachineId-win-4EFLHYIJ.js")).getMachineId;
            break;
          default:
            getMachineIdImpl = (await import("./getMachineId-unsupported-S32ZDA2T.js")).getMachineId;
            break;
        }
      }
      return getMachineIdImpl();
    }
    __name(getMachineId, "getMachineId");
    exports.getMachineId = getMachineId;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js
var require_utils6 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalizeType = exports.normalizeArch = void 0;
    var normalizeArch = /* @__PURE__ */ __name((nodeArchString) => {
      switch (nodeArchString) {
        case "arm":
          return "arm32";
        case "ppc":
          return "ppc32";
        case "x64":
          return "amd64";
        default:
          return nodeArchString;
      }
    }, "normalizeArch");
    exports.normalizeArch = normalizeArch;
    var normalizeType = /* @__PURE__ */ __name((nodePlatform) => {
      switch (nodePlatform) {
        case "sunos":
          return "solaris";
        case "win32":
          return "windows";
        default:
          return nodePlatform;
      }
    }, "normalizeType");
    exports.normalizeType = normalizeType;
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js
var require_HostDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.hostDetector = void 0;
    var semconv_1 = require_semconv2();
    var os_1 = __require("os");
    var getMachineId_1 = require_getMachineId();
    var utils_1 = require_utils6();
    var HostDetector = class {
      static {
        __name(this, "HostDetector");
      }
      detect(_config) {
        const attributes = {
          [semconv_1.ATTR_HOST_NAME]: (0, os_1.hostname)(),
          [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()),
          [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)()
        };
        return { attributes };
      }
    };
    exports.hostDetector = new HostDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js
var require_OSDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.osDetector = void 0;
    var semconv_1 = require_semconv2();
    var os_1 = __require("os");
    var utils_1 = require_utils6();
    var OSDetector = class {
      static {
        __name(this, "OSDetector");
      }
      detect(_config) {
        const attributes = {
          [semconv_1.ATTR_OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()),
          [semconv_1.ATTR_OS_VERSION]: (0, os_1.release)()
        };
        return { attributes };
      }
    };
    exports.osDetector = new OSDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js
var require_ProcessDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.processDetector = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var semconv_1 = require_semconv2();
    var os4 = __require("os");
    var ProcessDetector = class {
      static {
        __name(this, "ProcessDetector");
      }
      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 = os4.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();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js
var require_ServiceInstanceIdDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.serviceInstanceIdDetector = void 0;
    var semconv_1 = require_semconv2();
    var crypto_1 = __require("crypto");
    var ServiceInstanceIdDetector = class {
      static {
        __name(this, "ServiceInstanceIdDetector");
      }
      detect(_config) {
        return {
          attributes: {
            [semconv_1.ATTR_SERVICE_INSTANCE_ID]: (0, crypto_1.randomUUID)()
          }
        };
      }
    };
    exports.serviceInstanceIdDetector = new ServiceInstanceIdDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js
var require_node5 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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: /* @__PURE__ */ __name(function() {
      return HostDetector_1.hostDetector;
    }, "get") });
    var OSDetector_1 = require_OSDetector();
    Object.defineProperty(exports, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OSDetector_1.osDetector;
    }, "get") });
    var ProcessDetector_1 = require_ProcessDetector();
    Object.defineProperty(exports, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ProcessDetector_1.processDetector;
    }, "get") });
    var ServiceInstanceIdDetector_1 = require_ServiceInstanceIdDetector();
    Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ServiceInstanceIdDetector_1.serviceInstanceIdDetector;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js
var require_platform4 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0;
    var node_1 = require_node5();
    Object.defineProperty(exports, "hostDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.hostDetector;
    }, "get") });
    Object.defineProperty(exports, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.osDetector;
    }, "get") });
    Object.defineProperty(exports, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.processDetector;
    }, "get") });
    Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.serviceInstanceIdDetector;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js
var require_NoopDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.noopDetector = exports.NoopDetector = void 0;
    var NoopDetector = class {
      static {
        __name(this, "NoopDetector");
      }
      detect() {
        return {
          attributes: {}
        };
      }
    };
    exports.NoopDetector = NoopDetector;
    exports.noopDetector = new NoopDetector();
  }
});

// node_modules/@opentelemetry/resources/build/src/detectors/index.js
var require_detectors = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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: /* @__PURE__ */ __name(function() {
      return EnvDetector_1.envDetector;
    }, "get") });
    var platform_1 = require_platform4();
    Object.defineProperty(exports, "hostDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.hostDetector;
    }, "get") });
    Object.defineProperty(exports, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.osDetector;
    }, "get") });
    Object.defineProperty(exports, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.processDetector;
    }, "get") });
    Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.serviceInstanceIdDetector;
    }, "get") });
    var NoopDetector_1 = require_NoopDetector();
    Object.defineProperty(exports, "noopDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopDetector_1.noopDetector;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/index.js
var require_src8 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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: /* @__PURE__ */ __name(function() {
      return detect_resources_1.detectResources;
    }, "get") });
    var detectors_1 = require_detectors();
    Object.defineProperty(exports, "envDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.envDetector;
    }, "get") });
    Object.defineProperty(exports, "hostDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.hostDetector;
    }, "get") });
    Object.defineProperty(exports, "osDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.osDetector;
    }, "get") });
    Object.defineProperty(exports, "processDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.processDetector;
    }, "get") });
    Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return detectors_1.serviceInstanceIdDetector;
    }, "get") });
    var ResourceImpl_1 = require_ResourceImpl();
    Object.defineProperty(exports, "resourceFromAttributes", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ResourceImpl_1.resourceFromAttributes;
    }, "get") });
    Object.defineProperty(exports, "defaultResource", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ResourceImpl_1.defaultResource;
    }, "get") });
    Object.defineProperty(exports, "emptyResource", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ResourceImpl_1.emptyResource;
    }, "get") });
    var platform_1 = require_platform3();
    Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.defaultServiceName;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js
var require_ViewRegistry = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewRegistry = void 0;
    var ViewRegistry = class {
      static {
        __name(this, "ViewRegistry");
      }
      _registeredViews = [];
      addView(view) {
        this._registeredViews.push(view);
      }
      findViews(instrument, meter) {
        const views = this._registeredViews.filter((registeredView) => {
          return this._matchInstrument(registeredView.instrumentSelector, instrument) && this._matchMeter(registeredView.meterSelector, meter);
        });
        return views;
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js
var require_InstrumentDescriptor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isValidName = exports.isDescriptorCompatibleWith = exports.createInstrumentDescriptorWithView = exports.createInstrumentDescriptor = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var utils_1 = require_utils4();
    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 ?? {}
      };
    }
    __name(createInstrumentDescriptor, "createInstrumentDescriptor");
    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
      };
    }
    __name(createInstrumentDescriptorWithView, "createInstrumentDescriptorWithView");
    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;
    }
    __name(isDescriptorCompatibleWith, "isDescriptorCompatibleWith");
    exports.isDescriptorCompatibleWith = isDescriptorCompatibleWith;
    var NAME_REGEXP = /^[a-z][a-z0-9_.\-/]{0,254}$/i;
    function isValidName(name) {
      return name.match(NAME_REGEXP) != null;
    }
    __name(isValidName, "isValidName");
    exports.isValidName = isValidName;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js
var require_Instruments = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var SyncInstrument = class {
      static {
        __name(this, "SyncInstrument");
      }
      _writableMetricStorage;
      _descriptor;
      constructor(_writableMetricStorage, _descriptor) {
        this._writableMetricStorage = _writableMetricStorage;
        this._descriptor = _descriptor;
      }
      _record(value, attributes = {}, context2 = api_1.context.active()) {
        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, context2, (0, core_1.millisToHrTime)(Date.now()));
      }
    };
    exports.SyncInstrument = SyncInstrument;
    var UpDownCounterInstrument = class extends SyncInstrument {
      static {
        __name(this, "UpDownCounterInstrument");
      }
      /**
       * Increment value of counter by the input. Inputs may be negative.
       */
      add(value, attributes, ctx) {
        this._record(value, attributes, ctx);
      }
    };
    exports.UpDownCounterInstrument = UpDownCounterInstrument;
    var CounterInstrument = class extends SyncInstrument {
      static {
        __name(this, "CounterInstrument");
      }
      /**
       * 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;
    var GaugeInstrument = class extends SyncInstrument {
      static {
        __name(this, "GaugeInstrument");
      }
      /**
       * Records a measurement.
       */
      record(value, attributes, ctx) {
        this._record(value, attributes, ctx);
      }
    };
    exports.GaugeInstrument = GaugeInstrument;
    var HistogramInstrument = class extends SyncInstrument {
      static {
        __name(this, "HistogramInstrument");
      }
      /**
       * 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 {
      static {
        __name(this, "ObservableInstrument");
      }
      _observableRegistry;
      /** @internal */
      _metricStorages;
      /** @internal */
      _descriptor;
      constructor(descriptor, metricStorages, _observableRegistry) {
        this._observableRegistry = _observableRegistry;
        this._descriptor = descriptor;
        this._metricStorages = metricStorages;
      }
      /**
       * @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 {
      static {
        __name(this, "ObservableCounterInstrument");
      }
    };
    exports.ObservableCounterInstrument = ObservableCounterInstrument;
    var ObservableGaugeInstrument = class extends ObservableInstrument {
      static {
        __name(this, "ObservableGaugeInstrument");
      }
    };
    exports.ObservableGaugeInstrument = ObservableGaugeInstrument;
    var ObservableUpDownCounterInstrument = class extends ObservableInstrument {
      static {
        __name(this, "ObservableUpDownCounterInstrument");
      }
    };
    exports.ObservableUpDownCounterInstrument = ObservableUpDownCounterInstrument;
    function isObservableInstrument(it) {
      return it instanceof ObservableInstrument;
    }
    __name(isObservableInstrument, "isObservableInstrument");
    exports.isObservableInstrument = isObservableInstrument;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js
var require_Meter = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Meter = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var Instruments_1 = require_Instruments();
    var MetricData_1 = require_MetricData();
    var Meter = class {
      static {
        __name(this, "Meter");
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js
var require_MetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MetricStorage = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var MetricStorage = class {
      static {
        __name(this, "MetricStorage");
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js
var require_HashMap = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AttributeHashMap = exports.HashMap = void 0;
    var utils_1 = require_utils4();
    var HashMap = class {
      static {
        __name(this, "HashMap");
      }
      _hash;
      _valueMap = /* @__PURE__ */ new Map();
      _keyMap = /* @__PURE__ */ new Map();
      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 {
      static {
        __name(this, "AttributeHashMap");
      }
      constructor() {
        super(utils_1.hashAttributes);
      }
    };
    exports.AttributeHashMap = AttributeHashMap;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js
var require_DeltaMetricProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeltaMetricProcessor = void 0;
    var utils_1 = require_utils4();
    var HashMap_1 = require_HashMap();
    var DeltaMetricProcessor = class {
      static {
        __name(this, "DeltaMetricProcessor");
      }
      _aggregator;
      _activeCollectionStorage = new HashMap_1.AttributeHashMap();
      // TODO: find a reasonable mean to clean the memo;
      // https://github.com/open-telemetry/opentelemetry-specification/pull/2208
      _cumulativeMemoStorage = new HashMap_1.AttributeHashMap();
      _cardinalityLimit;
      _overflowAttributes = { "otel.metric.overflow": true };
      _overflowHashCode;
      constructor(_aggregator, aggregationCardinalityLimit) {
        this._aggregator = _aggregator;
        this._cardinalityLimit = (aggregationCardinalityLimit ?? 2e3) - 1;
        this._overflowHashCode = (0, utils_1.hashAttributes)(this._overflowAttributes);
      }
      record(value, attributes, _context, collectionTime) {
        let accumulation = this._activeCollectionStorage.get(attributes);
        if (!accumulation) {
          if (this._activeCollectionStorage.size >= this._cardinalityLimit) {
            const overflowAccumulation = this._activeCollectionStorage.getOrDefault(this._overflowAttributes, () => this._aggregator.createAccumulation(collectionTime));
            overflowAccumulation?.record(value);
            return;
          }
          accumulation = this._aggregator.createAccumulation(collectionTime);
          this._activeCollectionStorage.set(attributes, accumulation);
        }
        accumulation?.record(value);
      }
      batchCumulate(measurements, collectionTime) {
        Array.from(measurements.entries()).forEach(([attributes, value, hashCode]) => {
          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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js
var require_TemporalMetricProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TemporalMetricProcessor = void 0;
    var AggregationTemporality_1 = require_AggregationTemporality();
    var HashMap_1 = require_HashMap();
    var TemporalMetricProcessor = class _TemporalMetricProcessor {
      static {
        __name(this, "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 void 0;
        }
        return this._aggregator.toMetricData(
          instrumentDescriptor,
          aggregationTemporality,
          accumulationRecords,
          /* endTime */
          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()) {
          const currentAccumulation = current.get(key, hash);
          currentAccumulation?.setStartTime(lastCollectionTime);
        }
        return current;
      }
    };
    exports.TemporalMetricProcessor = TemporalMetricProcessor;
    function AttributesMapToAccumulationRecords(map) {
      return Array.from(map.entries());
    }
    __name(AttributesMapToAccumulationRecords, "AttributesMapToAccumulationRecords");
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js
var require_AsyncMetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AsyncMetricStorage = void 0;
    var MetricStorage_1 = require_MetricStorage();
    var DeltaMetricProcessor_1 = require_DeltaMetricProcessor();
    var TemporalMetricProcessor_1 = require_TemporalMetricProcessor();
    var HashMap_1 = require_HashMap();
    var AsyncMetricStorage = class extends MetricStorage_1.MetricStorage {
      static {
        __name(this, "AsyncMetricStorage");
      }
      _attributesProcessor;
      _aggregationCardinalityLimit;
      _deltaMetricStorage;
      _temporalMetricStorage;
      constructor(_instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) {
        super(_instrumentDescriptor);
        this._attributesProcessor = _attributesProcessor;
        this._aggregationCardinalityLimit = _aggregationCardinalityLimit;
        this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit);
        this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles);
      }
      record(measurements, observationTime) {
        const processed = new HashMap_1.AttributeHashMap();
        Array.from(measurements.entries()).forEach(([attributes, value]) => {
          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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js
var require_RegistrationConflicts = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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 += `	- Unit '${existing.unit}' does not match '${otherDescriptor.unit}'
`;
      }
      if (existing.type !== otherDescriptor.type) {
        incompatibility += `	- Type '${existing.type}' does not match '${otherDescriptor.type}'
`;
      }
      if (existing.valueType !== otherDescriptor.valueType) {
        incompatibility += `	- Value Type '${existing.valueType}' does not match '${otherDescriptor.valueType}'
`;
      }
      if (existing.description !== otherDescriptor.description) {
        incompatibility += `	- Description '${existing.description}' does not match '${otherDescriptor.description}'
`;
      }
      return incompatibility;
    }
    __name(getIncompatibilityDetails, "getIncompatibilityDetails");
    exports.getIncompatibilityDetails = getIncompatibilityDetails;
    function getValueTypeConflictResolutionRecipe(existing, otherDescriptor) {
      return `	- use valueType '${existing.valueType}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`;
    }
    __name(getValueTypeConflictResolutionRecipe, "getValueTypeConflictResolutionRecipe");
    exports.getValueTypeConflictResolutionRecipe = getValueTypeConflictResolutionRecipe;
    function getUnitConflictResolutionRecipe(existing, otherDescriptor) {
      return `	- use unit '${existing.unit}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`;
    }
    __name(getUnitConflictResolutionRecipe, "getUnitConflictResolutionRecipe");
    exports.getUnitConflictResolutionRecipe = getUnitConflictResolutionRecipe;
    function getTypeConflictResolutionRecipe(existing, otherDescriptor) {
      const selector = {
        name: otherDescriptor.name,
        type: otherDescriptor.type,
        unit: otherDescriptor.unit
      };
      const selectorString = JSON.stringify(selector);
      return `	- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'`;
    }
    __name(getTypeConflictResolutionRecipe, "getTypeConflictResolutionRecipe");
    exports.getTypeConflictResolutionRecipe = getTypeConflictResolutionRecipe;
    function getDescriptionResolutionRecipe(existing, otherDescriptor) {
      const selector = {
        name: otherDescriptor.name,
        type: otherDescriptor.type,
        unit: otherDescriptor.unit
      };
      const selectorString = JSON.stringify(selector);
      return `	- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'
    	- OR - create a new view with the name ${existing.name} and description '${existing.description}' and InstrumentSelector ${selectorString}
    	- OR - create a new view with the name ${otherDescriptor.name} and description '${existing.description}' and InstrumentSelector ${selectorString}`;
    }
    __name(getDescriptionResolutionRecipe, "getDescriptionResolutionRecipe");
    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 "";
    }
    __name(getConflictResolutionRecipe, "getConflictResolutionRecipe");
    exports.getConflictResolutionRecipe = getConflictResolutionRecipe;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js
var require_MetricStorageRegistry = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MetricStorageRegistry = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var api = (init_esm(), __toCommonJS(esm_exports));
    var RegistrationConflicts_1 = require_RegistrationConflicts();
    var MetricStorageRegistry = class _MetricStorageRegistry {
      static {
        __name(this, "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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js
var require_MultiWritableMetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MultiMetricStorage = void 0;
    var MultiMetricStorage = class {
      static {
        __name(this, "MultiMetricStorage");
      }
      _backingStorages;
      constructor(_backingStorages) {
        this._backingStorages = _backingStorages;
      }
      record(value, attributes, context2, recordTime) {
        this._backingStorages.forEach((it) => {
          it.record(value, attributes, context2, recordTime);
        });
      }
    };
    exports.MultiMetricStorage = MultiMetricStorage;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js
var require_ObservableResult = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchObservableResultImpl = exports.ObservableResultImpl = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var HashMap_1 = require_HashMap();
    var Instruments_1 = require_Instruments();
    var ObservableResultImpl = class {
      static {
        __name(this, "ObservableResultImpl");
      }
      _instrumentName;
      _valueType;
      /**
       * @internal
       */
      _buffer = new HashMap_1.AttributeHashMap();
      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;
    var BatchObservableResultImpl = class {
      static {
        __name(this, "BatchObservableResultImpl");
      }
      /**
       * @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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js
var require_ObservableRegistry = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ObservableRegistry = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var Instruments_1 = require_Instruments();
    var ObservableResult_1 = require_ObservableResult();
    var utils_1 = require_utils4();
    var ObservableRegistry = class {
      static {
        __name(this, "ObservableRegistry");
      }
      _callbacks = [];
      _batchCallbacks = [];
      addCallback(callback, instrument) {
        const idx = this._findCallback(callback, instrument);
        if (idx >= 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;
        }
        const idx = this._findBatchCallback(callback, observableInstruments);
        if (idx >= 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);
        const results = await (0, utils_1.PromiseAllSettled)([
          ...callbackFutures,
          ...batchCallbackFutures
        ]);
        const rejections = results.filter(utils_1.isPromiseAllSettledRejectionResult).map((it) => it.reason);
        return rejections;
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js
var require_SyncMetricStorage = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SyncMetricStorage = void 0;
    var MetricStorage_1 = require_MetricStorage();
    var DeltaMetricProcessor_1 = require_DeltaMetricProcessor();
    var TemporalMetricProcessor_1 = require_TemporalMetricProcessor();
    var SyncMetricStorage = class extends MetricStorage_1.MetricStorage {
      static {
        __name(this, "SyncMetricStorage");
      }
      _attributesProcessor;
      _aggregationCardinalityLimit;
      _deltaMetricStorage;
      _temporalMetricStorage;
      constructor(instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) {
        super(instrumentDescriptor);
        this._attributesProcessor = _attributesProcessor;
        this._aggregationCardinalityLimit = _aggregationCardinalityLimit;
        this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit);
        this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles);
      }
      record(value, attributes, context2, recordTime) {
        attributes = this._attributesProcessor.process(attributes, context2);
        this._deltaMetricStorage.record(value, attributes, context2, 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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js
var require_AttributesProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.createMultiAttributesProcessor = exports.createNoopAttributesProcessor = void 0;
    var NoopAttributesProcessor = class {
      static {
        __name(this, "NoopAttributesProcessor");
      }
      process(incoming, _context) {
        return incoming;
      }
    };
    var MultiAttributesProcessor = class {
      static {
        __name(this, "MultiAttributesProcessor");
      }
      _processors;
      constructor(_processors) {
        this._processors = _processors;
      }
      process(incoming, context2) {
        let filteredAttributes = incoming;
        for (const processor of this._processors) {
          filteredAttributes = processor.process(filteredAttributes, context2);
        }
        return filteredAttributes;
      }
    };
    var AllowListProcessor = class {
      static {
        __name(this, "AllowListProcessor");
      }
      _allowedAttributeNames;
      constructor(_allowedAttributeNames) {
        this._allowedAttributeNames = _allowedAttributeNames;
      }
      process(incoming, _context) {
        const filteredAttributes = {};
        Object.keys(incoming).filter((attributeName) => this._allowedAttributeNames.includes(attributeName)).forEach((attributeName) => filteredAttributes[attributeName] = incoming[attributeName]);
        return filteredAttributes;
      }
    };
    var DenyListProcessor = class {
      static {
        __name(this, "DenyListProcessor");
      }
      _deniedAttributeNames;
      constructor(_deniedAttributeNames) {
        this._deniedAttributeNames = _deniedAttributeNames;
      }
      process(incoming, _context) {
        const filteredAttributes = {};
        Object.keys(incoming).filter((attributeName) => !this._deniedAttributeNames.includes(attributeName)).forEach((attributeName) => filteredAttributes[attributeName] = incoming[attributeName]);
        return filteredAttributes;
      }
    };
    function createNoopAttributesProcessor() {
      return NOOP;
    }
    __name(createNoopAttributesProcessor, "createNoopAttributesProcessor");
    exports.createNoopAttributesProcessor = createNoopAttributesProcessor;
    function createMultiAttributesProcessor(processors) {
      return new MultiAttributesProcessor(processors);
    }
    __name(createMultiAttributesProcessor, "createMultiAttributesProcessor");
    exports.createMultiAttributesProcessor = createMultiAttributesProcessor;
    function createAllowListAttributesProcessor(attributeAllowList) {
      return new AllowListProcessor(attributeAllowList);
    }
    __name(createAllowListAttributesProcessor, "createAllowListAttributesProcessor");
    exports.createAllowListAttributesProcessor = createAllowListAttributesProcessor;
    function createDenyListAttributesProcessor(attributeDenyList) {
      return new DenyListProcessor(attributeDenyList);
    }
    __name(createDenyListAttributesProcessor, "createDenyListAttributesProcessor");
    exports.createDenyListAttributesProcessor = createDenyListAttributesProcessor;
    var NOOP = new NoopAttributesProcessor();
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js
var require_MeterSharedState = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MeterSharedState = void 0;
    var InstrumentDescriptor_1 = require_InstrumentDescriptor();
    var Meter_1 = require_Meter();
    var utils_1 = require_utils4();
    var AsyncMetricStorage_1 = require_AsyncMetricStorage();
    var MetricStorageRegistry_1 = require_MetricStorageRegistry();
    var MultiWritableMetricStorage_1 = require_MultiWritableMetricStorage();
    var ObservableRegistry_1 = require_ObservableRegistry();
    var SyncMetricStorage_1 = require_SyncMetricStorage();
    var AttributesProcessor_1 = require_AttributesProcessor();
    var MeterSharedState = class {
      static {
        __name(this, "MeterSharedState");
      }
      _meterProviderSharedState;
      _instrumentationScope;
      metricStorageRegistry = new MetricStorageRegistry_1.MetricStorageRegistry();
      observableRegistry = new ObservableRegistry_1.ObservableRegistry();
      meter;
      constructor(_meterProviderSharedState, _instrumentationScope) {
        this._meterProviderSharedState = _meterProviderSharedState;
        this._instrumentationScope = _instrumentationScope;
        this.meter = new Meter_1.Meter(this);
      }
      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) {
        const storages = this._registerMetricStorage(descriptor, AsyncMetricStorage_1.AsyncMetricStorage);
        return storages;
      }
      /**
       * @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) {
        const errors = await this.observableRegistry.observe(collectionTime, options?.timeoutMillis);
        const storages = this.metricStorageRegistry.getStorages(collector);
        if (storages.length === 0) {
          return null;
        }
        const metricDataList = storages.map((metricStorage) => {
          return metricStorage.collect(collector, collectionTime);
        }).filter(utils_1.isNotNullish);
        if (metricDataList.length === 0) {
          return { errors };
        }
        return {
          scopeMetrics: {
            scope: this._instrumentationScope,
            metrics: metricDataList
          },
          errors
        };
      }
      _registerMetricStorage(descriptor, MetricStorageType) {
        const views = this._meterProviderSharedState.viewRegistry.findViews(descriptor, this._instrumentationScope);
        let storages = views.map((view) => {
          const viewDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptorWithView)(view, descriptor);
          const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor);
          if (compatibleStorage != null) {
            return compatibleStorage;
          }
          const aggregator = view.aggregation.createAggregator(viewDescriptor);
          const viewStorage = new MetricStorageType(viewDescriptor, aggregator, view.attributesProcessor, this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit);
          this.metricStorageRegistry.register(viewStorage);
          return viewStorage;
        });
        if (storages.length === 0) {
          const perCollectorAggregations = this._meterProviderSharedState.selectAggregations(descriptor.type);
          const collectorStorages = perCollectorAggregations.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, (0, AttributesProcessor_1.createNoopAttributesProcessor)(), [collector], cardinalityLimit);
            this.metricStorageRegistry.registerForCollector(collector, storage);
            return storage;
          });
          storages = storages.concat(collectorStorages);
        }
        return storages;
      }
    };
    exports.MeterSharedState = MeterSharedState;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js
var require_MeterProviderSharedState = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MeterProviderSharedState = void 0;
    var utils_1 = require_utils4();
    var ViewRegistry_1 = require_ViewRegistry();
    var MeterSharedState_1 = require_MeterSharedState();
    var AggregationOption_1 = require_AggregationOption();
    var MeterProviderSharedState = class {
      static {
        __name(this, "MeterProviderSharedState");
      }
      resource;
      viewRegistry = new ViewRegistry_1.ViewRegistry();
      metricCollectors = [];
      meterSharedStates = /* @__PURE__ */ new Map();
      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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js
var require_MetricCollector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MetricCollector = void 0;
    var core_1 = require_src3();
    var MetricCollector = class {
      static {
        __name(this, "MetricCollector");
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js
var require_Predicate = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExactPredicate = exports.PatternPredicate = void 0;
    var ESCAPE = /[\^$\\.+?()[\]{}|]/g;
    var PatternPredicate = class _PatternPredicate {
      static {
        __name(this, "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 {
      static {
        __name(this, "ExactPredicate");
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js
var require_InstrumentSelector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InstrumentSelector = void 0;
    var Predicate_1 = require_Predicate();
    var InstrumentSelector = class {
      static {
        __name(this, "InstrumentSelector");
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js
var require_MeterSelector = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MeterSelector = void 0;
    var Predicate_1 = require_Predicate();
    var MeterSelector = class {
      static {
        __name(this, "MeterSelector");
      }
      _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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js
var require_View = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.View = void 0;
    var Predicate_1 = require_Predicate();
    var AttributesProcessor_1 = require_AttributesProcessor();
    var InstrumentSelector_1 = require_InstrumentSelector();
    var MeterSelector_1 = require_MeterSelector();
    var 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;
    }
    __name(isSelectorNotProvided, "isSelectorNotProvided");
    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.");
      }
    }
    __name(validateViewOptions, "validateViewOptions");
    var View = class {
      static {
        __name(this, "View");
      }
      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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js
var require_MeterProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MeterProvider = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var resources_1 = require_src8();
    var MeterProviderSharedState_1 = require_MeterProviderSharedState();
    var MetricCollector_1 = require_MetricCollector();
    var View_1 = require_View();
    var MeterProvider = class {
      static {
        __name(this, "MeterProvider");
      }
      _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);
          }
        }
      }
      /**
       * 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;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/index.js
var require_src9 = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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: /* @__PURE__ */ __name(function() {
      return AggregationTemporality_1.AggregationTemporality;
    }, "get") });
    var MetricData_1 = require_MetricData();
    Object.defineProperty(exports, "DataPointType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MetricData_1.DataPointType;
    }, "get") });
    Object.defineProperty(exports, "InstrumentType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MetricData_1.InstrumentType;
    }, "get") });
    var MetricReader_1 = require_MetricReader();
    Object.defineProperty(exports, "MetricReader", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MetricReader_1.MetricReader;
    }, "get") });
    var PeriodicExportingMetricReader_1 = require_PeriodicExportingMetricReader();
    Object.defineProperty(exports, "PeriodicExportingMetricReader", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return PeriodicExportingMetricReader_1.PeriodicExportingMetricReader;
    }, "get") });
    var InMemoryMetricExporter_1 = require_InMemoryMetricExporter();
    Object.defineProperty(exports, "InMemoryMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return InMemoryMetricExporter_1.InMemoryMetricExporter;
    }, "get") });
    var ConsoleMetricExporter_1 = require_ConsoleMetricExporter();
    Object.defineProperty(exports, "ConsoleMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ConsoleMetricExporter_1.ConsoleMetricExporter;
    }, "get") });
    var MeterProvider_1 = require_MeterProvider();
    Object.defineProperty(exports, "MeterProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return MeterProvider_1.MeterProvider;
    }, "get") });
    var AggregationOption_1 = require_AggregationOption();
    Object.defineProperty(exports, "AggregationType", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AggregationOption_1.AggregationType;
    }, "get") });
    var AttributesProcessor_1 = require_AttributesProcessor();
    Object.defineProperty(exports, "createAllowListAttributesProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AttributesProcessor_1.createAllowListAttributesProcessor;
    }, "get") });
    Object.defineProperty(exports, "createDenyListAttributesProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AttributesProcessor_1.createDenyListAttributesProcessor;
    }, "get") });
    var utils_1 = require_utils4();
    Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.TimeoutError;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js
var require_internal_types = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EAggregationTemporality = void 0;
    var EAggregationTemporality;
    (function(EAggregationTemporality2) {
      EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED";
      EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_DELTA"] = 1] = "AGGREGATION_TEMPORALITY_DELTA";
      EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2] = "AGGREGATION_TEMPORALITY_CUMULATIVE";
    })(EAggregationTemporality = exports.EAggregationTemporality || (exports.EAggregationTemporality = {}));
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js
var require_internal3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createExportMetricsServiceRequest = exports.toMetric = exports.toScopeMetrics = exports.toResourceMetrics = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var sdk_metrics_1 = require_src9();
    var internal_types_1 = require_internal_types();
    var utils_1 = require_utils3();
    var internal_1 = require_internal();
    function toResourceMetrics(resourceMetrics, options) {
      const encoder = (0, utils_1.getOtlpEncoder)(options);
      return {
        resource: (0, internal_1.createResource)(resourceMetrics.resource),
        schemaUrl: void 0,
        scopeMetrics: toScopeMetrics(resourceMetrics.scopeMetrics, encoder)
      };
    }
    __name(toResourceMetrics, "toResourceMetrics");
    exports.toResourceMetrics = toResourceMetrics;
    function toScopeMetrics(scopeMetrics, encoder) {
      return Array.from(scopeMetrics.map((metrics2) => ({
        scope: (0, internal_1.createInstrumentationScope)(metrics2.scope),
        metrics: metrics2.metrics.map((metricData) => toMetric(metricData, encoder)),
        schemaUrl: metrics2.scope.schemaUrl
      })));
    }
    __name(toScopeMetrics, "toScopeMetrics");
    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)
          };
          break;
      }
      return out;
    }
    __name(toMetric, "toMetric");
    exports.toMetric = toMetric;
    function toSingularDataPoint(dataPoint, valueType, encoder) {
      const out = {
        attributes: (0, internal_1.toAttributes)(dataPoint.attributes),
        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;
          break;
      }
      return out;
    }
    __name(toSingularDataPoint, "toSingularDataPoint");
    function toSingularDataPoints(metricData, encoder) {
      return metricData.dataPoints.map((dataPoint) => {
        return toSingularDataPoint(dataPoint, metricData.descriptor.valueType, encoder);
      });
    }
    __name(toSingularDataPoints, "toSingularDataPoints");
    function toHistogramDataPoints(metricData, encoder) {
      return metricData.dataPoints.map((dataPoint) => {
        const histogram = dataPoint.value;
        return {
          attributes: (0, internal_1.toAttributes)(dataPoint.attributes),
          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)
        };
      });
    }
    __name(toHistogramDataPoints, "toHistogramDataPoints");
    function toExponentialHistogramDataPoints(metricData, encoder) {
      return metricData.dataPoints.map((dataPoint) => {
        const histogram = dataPoint.value;
        return {
          attributes: (0, internal_1.toAttributes)(dataPoint.attributes),
          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)
        };
      });
    }
    __name(toExponentialHistogramDataPoints, "toExponentialHistogramDataPoints");
    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;
      }
    }
    __name(toAggregationTemporality, "toAggregationTemporality");
    function createExportMetricsServiceRequest(resourceMetrics, options) {
      return {
        resourceMetrics: resourceMetrics.map((metrics2) => toResourceMetrics(metrics2, options))
      };
    }
    __name(createExportMetricsServiceRequest, "createExportMetricsServiceRequest");
    exports.createExportMetricsServiceRequest = createExportMetricsServiceRequest;
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js
var require_metrics = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProtobufMetricsSerializer = void 0;
    var root = require_root2();
    var internal_1 = require_internal3();
    var metricsResponseType = root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse;
    var metricsRequestType = root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;
    exports.ProtobufMetricsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportMetricsServiceRequest)([arg]);
        return metricsRequestType.encode(request4).finish();
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        return metricsResponseType.decode(arg);
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js
var require_protobuf2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProtobufMetricsSerializer = void 0;
    var metrics_1 = require_metrics();
    Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return metrics_1.ProtobufMetricsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js
var require_internal4 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createExportTraceServiceRequest = exports.toOtlpSpanEvent = exports.toOtlpLink = exports.sdkSpanToOtlpSpan = void 0;
    var internal_1 = require_internal();
    var utils_1 = require_utils3();
    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,
        // Span kind is offset by 1 because the API does not define a value for unset
        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),
        droppedAttributesCount: span.droppedAttributesCount,
        events: span.events.map((event) => toOtlpSpanEvent(event, encoder)),
        droppedEventsCount: span.droppedEventsCount,
        status: {
          // API and proto enums share the same values
          code: status.code,
          message: status.message
        },
        links: span.links.map((link) => toOtlpLink(link, encoder)),
        droppedLinksCount: span.droppedLinksCount
      };
    }
    __name(sdkSpanToOtlpSpan, "sdkSpanToOtlpSpan");
    exports.sdkSpanToOtlpSpan = sdkSpanToOtlpSpan;
    function toOtlpLink(link, encoder) {
      return {
        attributes: link.attributes ? (0, internal_1.toAttributes)(link.attributes) : [],
        spanId: encoder.encodeSpanContext(link.context.spanId),
        traceId: encoder.encodeSpanContext(link.context.traceId),
        traceState: link.context.traceState?.serialize(),
        droppedAttributesCount: link.droppedAttributesCount || 0
      };
    }
    __name(toOtlpLink, "toOtlpLink");
    exports.toOtlpLink = toOtlpLink;
    function toOtlpSpanEvent(timedEvent, encoder) {
      return {
        attributes: timedEvent.attributes ? (0, internal_1.toAttributes)(timedEvent.attributes) : [],
        name: timedEvent.name,
        timeUnixNano: encoder.encodeHrTime(timedEvent.time),
        droppedAttributesCount: timedEvent.droppedAttributesCount || 0
      };
    }
    __name(toOtlpSpanEvent, "toOtlpSpanEvent");
    exports.toOtlpSpanEvent = toOtlpSpanEvent;
    function createExportTraceServiceRequest(spans, options) {
      const encoder = (0, utils_1.getOtlpEncoder)(options);
      return {
        resourceSpans: spanRecordsToResourceSpans(spans, encoder)
      };
    }
    __name(createExportTraceServiceRequest, "createExportTraceServiceRequest");
    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;
    }
    __name(createResourceMap, "createResourceMap");
    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),
              spans,
              schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl
            });
          }
          ilmEntry = ilmIterator.next();
        }
        const transformedSpans = {
          resource: (0, internal_1.createResource)(resource),
          scopeSpans: scopeResourceSpans,
          schemaUrl: void 0
        };
        out.push(transformedSpans);
        entry = entryIterator.next();
      }
      return out;
    }
    __name(spanRecordsToResourceSpans, "spanRecordsToResourceSpans");
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js
var require_trace = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProtobufTraceSerializer = void 0;
    var root = require_root2();
    var internal_1 = require_internal4();
    var traceResponseType = root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse;
    var traceRequestType = root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;
    exports.ProtobufTraceSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportTraceServiceRequest)(arg);
        return traceRequestType.encode(request4).finish();
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        return traceResponseType.decode(arg);
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js
var require_protobuf3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProtobufTraceSerializer = void 0;
    var trace_1 = require_trace();
    Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return trace_1.ProtobufTraceSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js
var require_logs3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonLogsSerializer = void 0;
    var internal_1 = require_internal2();
    exports.JsonLogsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportLogsServiceRequest)(arg, {
          useHex: true,
          useLongBits: false
        });
        const encoder = new TextEncoder();
        return encoder.encode(JSON.stringify(request4));
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        if (arg.length === 0) {
          return {};
        }
        const decoder = new TextDecoder();
        return JSON.parse(decoder.decode(arg));
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js
var require_json = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonLogsSerializer = void 0;
    var logs_1 = require_logs3();
    Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return logs_1.JsonLogsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js
var require_metrics2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonMetricsSerializer = void 0;
    var internal_1 = require_internal3();
    exports.JsonMetricsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportMetricsServiceRequest)([arg], {
          useLongBits: false
        });
        const encoder = new TextEncoder();
        return encoder.encode(JSON.stringify(request4));
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        if (arg.length === 0) {
          return {};
        }
        const decoder = new TextDecoder();
        return JSON.parse(decoder.decode(arg));
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js
var require_json2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonMetricsSerializer = void 0;
    var metrics_1 = require_metrics2();
    Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return metrics_1.JsonMetricsSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js
var require_trace2 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonTraceSerializer = void 0;
    var internal_1 = require_internal4();
    exports.JsonTraceSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportTraceServiceRequest)(arg, {
          useHex: true,
          useLongBits: false
        });
        const encoder = new TextEncoder();
        return encoder.encode(JSON.stringify(request4));
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        if (arg.length === 0) {
          return {};
        }
        const decoder = new TextDecoder();
        return JSON.parse(decoder.decode(arg));
      }, "deserializeResponse")
    };
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js
var require_json3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonTraceSerializer = void 0;
    var trace_1 = require_trace2();
    Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return trace_1.JsonTraceSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/otlp-transformer/build/src/index.js
var require_src10 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonTraceSerializer = exports.JsonMetricsSerializer = exports.JsonLogsSerializer = exports.ProtobufTraceSerializer = exports.ProtobufMetricsSerializer = exports.ProtobufLogsSerializer = void 0;
    var protobuf_1 = require_protobuf();
    Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return protobuf_1.ProtobufLogsSerializer;
    }, "get") });
    var protobuf_2 = require_protobuf2();
    Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return protobuf_2.ProtobufMetricsSerializer;
    }, "get") });
    var protobuf_3 = require_protobuf3();
    Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return protobuf_3.ProtobufTraceSerializer;
    }, "get") });
    var json_1 = require_json();
    Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return json_1.JsonLogsSerializer;
    }, "get") });
    var json_2 = require_json2();
    Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return json_2.JsonMetricsSerializer;
    }, "get") });
    var json_3 = require_json3();
    Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return json_3.JsonTraceSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js
var require_OTLPTraceExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var otlp_grpc_exporter_base_1 = require_src7();
    var otlp_transformer_1 = require_src10();
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var OTLPTraceExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPTraceExporter");
      }
      constructor(config = {}) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, "TRACES"), otlp_transformer_1.ProtobufTraceSerializer, "TraceExportService", "/opentelemetry.proto.collector.trace.v1.TraceService/Export"));
      }
    };
    exports.OTLPTraceExporter = OTLPTraceExporter2;
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js
var require_src11 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var OTLPTraceExporter_1 = require_OTLPTraceExporter();
    Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPTraceExporter_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js
var require_OTLPLogExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var otlp_grpc_exporter_base_1 = require_src7();
    var otlp_transformer_1 = require_src10();
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var OTLPLogExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPLogExporter");
      }
      constructor(config = {}) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, "LOGS"), otlp_transformer_1.ProtobufLogsSerializer, "LogsExportService", "/opentelemetry.proto.collector.logs.v1.LogsService/Export"));
      }
    };
    exports.OTLPLogExporter = OTLPLogExporter2;
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js
var require_src12 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var OTLPLogExporter_1 = require_OTLPLogExporter();
    Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPLogExporter_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js
var require_OTLPMetricExporterOptions = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AggregationTemporalityPreference = void 0;
    var AggregationTemporalityPreference;
    (function(AggregationTemporalityPreference2) {
      AggregationTemporalityPreference2[AggregationTemporalityPreference2["DELTA"] = 0] = "DELTA";
      AggregationTemporalityPreference2[AggregationTemporalityPreference2["CUMULATIVE"] = 1] = "CUMULATIVE";
      AggregationTemporalityPreference2[AggregationTemporalityPreference2["LOWMEMORY"] = 2] = "LOWMEMORY";
    })(AggregationTemporalityPreference = exports.AggregationTemporalityPreference || (exports.AggregationTemporalityPreference = {}));
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js
var require_OTLPMetricExporterBase = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = void 0;
    var core_1 = require_src3();
    var sdk_metrics_1 = require_src9();
    var OTLPMetricExporterOptions_1 = require_OTLPMetricExporterOptions();
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var CumulativeTemporalitySelector = /* @__PURE__ */ __name(() => sdk_metrics_1.AggregationTemporality.CUMULATIVE, "CumulativeTemporalitySelector");
    exports.CumulativeTemporalitySelector = CumulativeTemporalitySelector;
    var DeltaTemporalitySelector = /* @__PURE__ */ __name((instrumentType) => {
      switch (instrumentType) {
        case sdk_metrics_1.InstrumentType.COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER:
        case sdk_metrics_1.InstrumentType.GAUGE:
        case sdk_metrics_1.InstrumentType.HISTOGRAM:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE:
          return sdk_metrics_1.AggregationTemporality.DELTA;
        case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:
          return sdk_metrics_1.AggregationTemporality.CUMULATIVE;
      }
    }, "DeltaTemporalitySelector");
    exports.DeltaTemporalitySelector = DeltaTemporalitySelector;
    var LowMemoryTemporalitySelector = /* @__PURE__ */ __name((instrumentType) => {
      switch (instrumentType) {
        case sdk_metrics_1.InstrumentType.COUNTER:
        case sdk_metrics_1.InstrumentType.HISTOGRAM:
          return sdk_metrics_1.AggregationTemporality.DELTA;
        case sdk_metrics_1.InstrumentType.GAUGE:
        case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER:
        case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE:
          return sdk_metrics_1.AggregationTemporality.CUMULATIVE;
      }
    }, "LowMemoryTemporalitySelector");
    exports.LowMemoryTemporalitySelector = LowMemoryTemporalitySelector;
    function chooseTemporalitySelectorFromEnvironment() {
      const configuredTemporality = ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE") ?? "cumulative").toLowerCase();
      if (configuredTemporality === "cumulative") {
        return exports.CumulativeTemporalitySelector;
      }
      if (configuredTemporality === "delta") {
        return exports.DeltaTemporalitySelector;
      }
      if (configuredTemporality === "lowmemory") {
        return exports.LowMemoryTemporalitySelector;
      }
      api_1.diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${configuredTemporality}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);
      return exports.CumulativeTemporalitySelector;
    }
    __name(chooseTemporalitySelectorFromEnvironment, "chooseTemporalitySelectorFromEnvironment");
    function chooseTemporalitySelector(temporalityPreference) {
      if (temporalityPreference != null) {
        if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.DELTA) {
          return exports.DeltaTemporalitySelector;
        } else if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.LOWMEMORY) {
          return exports.LowMemoryTemporalitySelector;
        }
        return exports.CumulativeTemporalitySelector;
      }
      return chooseTemporalitySelectorFromEnvironment();
    }
    __name(chooseTemporalitySelector, "chooseTemporalitySelector");
    var DEFAULT_AGGREGATION = Object.freeze({
      type: sdk_metrics_1.AggregationType.DEFAULT
    });
    function chooseAggregationSelector(config) {
      return config?.aggregationPreference ?? (() => DEFAULT_AGGREGATION);
    }
    __name(chooseAggregationSelector, "chooseAggregationSelector");
    var OTLPMetricExporterBase = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPMetricExporterBase");
      }
      _aggregationTemporalitySelector;
      _aggregationSelector;
      constructor(delegate, config) {
        super(delegate);
        this._aggregationSelector = chooseAggregationSelector(config);
        this._aggregationTemporalitySelector = chooseTemporalitySelector(config?.temporalityPreference);
      }
      selectAggregation(instrumentType) {
        return this._aggregationSelector(instrumentType);
      }
      selectAggregationTemporality(instrumentType) {
        return this._aggregationTemporalitySelector(instrumentType);
      }
    };
    exports.OTLPMetricExporterBase = OTLPMetricExporterBase;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/version.js
var require_version3 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js
var require_OTLPMetricExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var OTLPMetricExporterBase_1 = require_OTLPMetricExporterBase();
    var otlp_transformer_1 = require_src10();
    var version_1 = require_version3();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var USER_AGENT = {
      "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`
    };
    var OTLPMetricExporter2 = class extends OTLPMetricExporterBase_1.OTLPMetricExporterBase {
      static {
        __name(this, "OTLPMetricExporter");
      }
      constructor(config) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, "METRICS", "v1/metrics", {
          ...USER_AGENT,
          "Content-Type": "application/json"
        }), otlp_transformer_1.JsonMetricsSerializer), config);
      }
    };
    exports.OTLPMetricExporter = OTLPMetricExporter2;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js
var require_node6 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var OTLPMetricExporter_1 = require_OTLPMetricExporter();
    Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporter_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js
var require_platform5 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var node_1 = require_node6();
    Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js
var require_src13 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = exports.AggregationTemporalityPreference = exports.OTLPMetricExporter = void 0;
    var platform_1 = require_platform5();
    Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPMetricExporter;
    }, "get") });
    var OTLPMetricExporterOptions_1 = require_OTLPMetricExporterOptions();
    Object.defineProperty(exports, "AggregationTemporalityPreference", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterOptions_1.AggregationTemporalityPreference;
    }, "get") });
    var OTLPMetricExporterBase_1 = require_OTLPMetricExporterBase();
    Object.defineProperty(exports, "CumulativeTemporalitySelector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.CumulativeTemporalitySelector;
    }, "get") });
    Object.defineProperty(exports, "DeltaTemporalitySelector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.DeltaTemporalitySelector;
    }, "get") });
    Object.defineProperty(exports, "LowMemoryTemporalitySelector", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.LowMemoryTemporalitySelector;
    }, "get") });
    Object.defineProperty(exports, "OTLPMetricExporterBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporterBase_1.OTLPMetricExporterBase;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js
var require_OTLPMetricExporter2 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var exporter_metrics_otlp_http_1 = require_src13();
    var otlp_grpc_exporter_base_1 = require_src7();
    var otlp_transformer_1 = require_src10();
    var OTLPMetricExporter2 = class extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase {
      static {
        __name(this, "OTLPMetricExporter");
      }
      constructor(config) {
        super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config ?? {}, "METRICS"), otlp_transformer_1.ProtobufMetricsSerializer, "MetricsExportService", "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export"), config);
      }
    };
    exports.OTLPMetricExporter = OTLPMetricExporter2;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js
var require_src14 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var OTLPMetricExporter_1 = require_OTLPMetricExporter2();
    Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporter_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/version.js
var require_version4 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js
var require_OTLPTraceExporter2 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var version_1 = require_version4();
    var otlp_transformer_1 = require_src10();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPTraceExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPTraceExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "TRACES", "v1/traces", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/json"
        }), otlp_transformer_1.JsonTraceSerializer));
      }
    };
    exports.OTLPTraceExporter = OTLPTraceExporter2;
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js
var require_node7 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var OTLPTraceExporter_1 = require_OTLPTraceExporter2();
    Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPTraceExporter_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js
var require_platform6 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var node_1 = require_node7();
    Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js
var require_src15 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var platform_1 = require_platform6();
    Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/version.js
var require_version5 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js
var require_OTLPLogExporter2 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var otlp_transformer_1 = require_src10();
    var version_1 = require_version5();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPLogExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPLogExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "LOGS", "v1/logs", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/json"
        }), otlp_transformer_1.JsonLogsSerializer));
      }
    };
    exports.OTLPLogExporter = OTLPLogExporter2;
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js
var require_node8 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var OTLPLogExporter_1 = require_OTLPLogExporter2();
    Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPLogExporter_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js
var require_platform7 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var node_1 = require_node8();
    Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js
var require_src16 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var platform_1 = require_platform7();
    Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js
var require_LogRecordImpl = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LogRecordImpl = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var api = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var LogRecordImpl = class {
      static {
        __name(this, "LogRecordImpl");
      }
      hrTime;
      hrTimeObserved;
      spanContext;
      resource;
      instrumentationScope;
      attributes = {};
      _severityText;
      _severityNumber;
      _body;
      _eventName;
      totalAttributesCount = 0;
      _isReadonly = false;
      _logRecordLimits;
      set severityText(severityText) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._severityText = severityText;
      }
      get severityText() {
        return this._severityText;
      }
      set severityNumber(severityNumber) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._severityNumber = severityNumber;
      }
      get severityNumber() {
        return this._severityNumber;
      }
      set body(body) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._body = body;
      }
      get body() {
        return this._body;
      }
      get eventName() {
        return this._eventName;
      }
      set eventName(eventName) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._eventName = eventName;
      }
      get droppedAttributesCount() {
        return this.totalAttributesCount - Object.keys(this.attributes).length;
      }
      constructor(_sharedState, instrumentationScope, logRecord) {
        const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, context: context2 } = logRecord;
        const now = Date.now();
        this.hrTime = (0, core_1.timeInputToHrTime)(timestamp ?? now);
        this.hrTimeObserved = (0, core_1.timeInputToHrTime)(observedTimestamp ?? now);
        if (context2) {
          const spanContext = api.trace.getSpanContext(context2);
          if (spanContext && api.isSpanContextValid(spanContext)) {
            this.spanContext = spanContext;
          }
        }
        this.severityNumber = severityNumber;
        this.severityText = severityText;
        this.body = body;
        this.resource = _sharedState.resource;
        this.instrumentationScope = instrumentationScope;
        this._logRecordLimits = _sharedState.logRecordLimits;
        this._eventName = eventName;
        this.setAttributes(attributes);
      }
      setAttribute(key, value) {
        if (this._isLogRecordReadonly()) {
          return this;
        }
        if (value === null) {
          return this;
        }
        if (key.length === 0) {
          api.diag.warn(`Invalid attribute key: ${key}`);
          return this;
        }
        if (!(0, core_1.isAttributeValue)(value) && !(typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0)) {
          api.diag.warn(`Invalid attribute value set for key: ${key}`);
          return this;
        }
        this.totalAttributesCount += 1;
        if (Object.keys(this.attributes).length >= this._logRecordLimits.attributeCountLimit && !Object.prototype.hasOwnProperty.call(this.attributes, key)) {
          if (this.droppedAttributesCount === 1) {
            api.diag.warn("Dropping extra attributes.");
          }
          return this;
        }
        if ((0, core_1.isAttributeValue)(value)) {
          this.attributes[key] = this._truncateToSize(value);
        } else {
          this.attributes[key] = value;
        }
        return this;
      }
      setAttributes(attributes) {
        for (const [k, v] of Object.entries(attributes)) {
          this.setAttribute(k, v);
        }
        return this;
      }
      setBody(body) {
        this.body = body;
        return this;
      }
      setEventName(eventName) {
        this.eventName = eventName;
        return this;
      }
      setSeverityNumber(severityNumber) {
        this.severityNumber = severityNumber;
        return this;
      }
      setSeverityText(severityText) {
        this.severityText = severityText;
        return this;
      }
      /**
       * @internal
       * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
       * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
       */
      _makeReadonly() {
        this._isReadonly = true;
      }
      _truncateToSize(value) {
        const limit = this._logRecordLimits.attributeValueLengthLimit;
        if (limit <= 0) {
          api.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;
      }
      _truncateToLimitUtil(value, limit) {
        if (value.length <= limit) {
          return value;
        }
        return value.substring(0, limit);
      }
      _isLogRecordReadonly() {
        if (this._isReadonly) {
          api_1.diag.warn("Can not execute the operation on emitted log record");
        }
        return this._isReadonly;
      }
    };
    exports.LogRecordImpl = LogRecordImpl;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/Logger.js
var require_Logger = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/Logger.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Logger = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var LogRecordImpl_1 = require_LogRecordImpl();
    var Logger = class {
      static {
        __name(this, "Logger");
      }
      instrumentationScope;
      _sharedState;
      constructor(instrumentationScope, _sharedState) {
        this.instrumentationScope = instrumentationScope;
        this._sharedState = _sharedState;
      }
      emit(logRecord) {
        const currentContext = logRecord.context || api_1.context.active();
        const logRecordInstance = new LogRecordImpl_1.LogRecordImpl(this._sharedState, this.instrumentationScope, {
          context: currentContext,
          ...logRecord
        });
        this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext);
        logRecordInstance._makeReadonly();
      }
    };
    exports.Logger = Logger;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/config.js
var require_config = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/config.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.reconfigureLimits = exports.loadDefaultConfig = void 0;
    var core_1 = require_src3();
    function loadDefaultConfig() {
      return {
        forceFlushTimeoutMillis: 3e4,
        logRecordLimits: {
          attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
          attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT") ?? 128
        },
        includeTraceContext: true
      };
    }
    __name(loadDefaultConfig, "loadDefaultConfig");
    exports.loadDefaultConfig = loadDefaultConfig;
    function reconfigureLimits(logRecordLimits) {
      return {
        /**
         * Reassign log record attribute count limit to use first non null value defined by user or use default value
         */
        attributeCountLimit: logRecordLimits.attributeCountLimit ?? (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128,
        /**
         * Reassign log record attribute value length limit to use first non null value defined by user or use default value
         */
        attributeValueLengthLimit: logRecordLimits.attributeValueLengthLimit ?? (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity
      };
    }
    __name(reconfigureLimits, "reconfigureLimits");
    exports.reconfigureLimits = reconfigureLimits;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js
var require_NoopLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NoopLogRecordProcessor = void 0;
    var NoopLogRecordProcessor = class {
      static {
        __name(this, "NoopLogRecordProcessor");
      }
      forceFlush() {
        return Promise.resolve();
      }
      onEmit(_logRecord, _context) {
      }
      shutdown() {
        return Promise.resolve();
      }
    };
    exports.NoopLogRecordProcessor = NoopLogRecordProcessor;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js
var require_MultiLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MultiLogRecordProcessor = void 0;
    var core_1 = require_src3();
    var MultiLogRecordProcessor = class {
      static {
        __name(this, "MultiLogRecordProcessor");
      }
      processors;
      forceFlushTimeoutMillis;
      constructor(processors, forceFlushTimeoutMillis) {
        this.processors = processors;
        this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
      }
      async forceFlush() {
        const timeout = this.forceFlushTimeoutMillis;
        await Promise.all(this.processors.map((processor) => (0, core_1.callWithTimeout)(processor.forceFlush(), timeout)));
      }
      onEmit(logRecord, context2) {
        this.processors.forEach((processors) => processors.onEmit(logRecord, context2));
      }
      async shutdown() {
        await Promise.all(this.processors.map((processor) => processor.shutdown()));
      }
    };
    exports.MultiLogRecordProcessor = MultiLogRecordProcessor;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js
var require_LoggerProviderSharedState = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LoggerProviderSharedState = void 0;
    var NoopLogRecordProcessor_1 = require_NoopLogRecordProcessor();
    var MultiLogRecordProcessor_1 = require_MultiLogRecordProcessor();
    var LoggerProviderSharedState = class {
      static {
        __name(this, "LoggerProviderSharedState");
      }
      resource;
      forceFlushTimeoutMillis;
      logRecordLimits;
      processors;
      loggers = /* @__PURE__ */ new Map();
      activeProcessor;
      registeredLogRecordProcessors = [];
      constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors) {
        this.resource = resource;
        this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
        this.logRecordLimits = logRecordLimits;
        this.processors = processors;
        if (processors.length > 0) {
          this.registeredLogRecordProcessors = processors;
          this.activeProcessor = new MultiLogRecordProcessor_1.MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis);
        } else {
          this.activeProcessor = new NoopLogRecordProcessor_1.NoopLogRecordProcessor();
        }
      }
    };
    exports.LoggerProviderSharedState = LoggerProviderSharedState;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js
var require_LoggerProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LoggerProvider = exports.DEFAULT_LOGGER_NAME = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var api_logs_1 = require_src2();
    var resources_1 = require_src8();
    var core_1 = require_src3();
    var Logger_1 = require_Logger();
    var config_1 = require_config();
    var LoggerProviderSharedState_1 = require_LoggerProviderSharedState();
    exports.DEFAULT_LOGGER_NAME = "unknown";
    var LoggerProvider = class {
      static {
        __name(this, "LoggerProvider");
      }
      _shutdownOnce;
      _sharedState;
      constructor(config = {}) {
        const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), config);
        const resource = config.resource ?? (0, resources_1.defaultResource)();
        this._sharedState = new LoggerProviderSharedState_1.LoggerProviderSharedState(resource, mergedConfig.forceFlushTimeoutMillis, (0, config_1.reconfigureLimits)(mergedConfig.logRecordLimits), config?.processors ?? []);
        this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
      }
      /**
       * Get a logger with the configuration of the LoggerProvider.
       */
      getLogger(name, version, options) {
        if (this._shutdownOnce.isCalled) {
          api_1.diag.warn("A shutdown LoggerProvider cannot provide a Logger");
          return api_logs_1.NOOP_LOGGER;
        }
        if (!name) {
          api_1.diag.warn("Logger requested without instrumentation scope name.");
        }
        const loggerName = name || exports.DEFAULT_LOGGER_NAME;
        const key = `${loggerName}@${version || ""}:${options?.schemaUrl || ""}`;
        if (!this._sharedState.loggers.has(key)) {
          this._sharedState.loggers.set(key, new Logger_1.Logger({ name: loggerName, version, schemaUrl: options?.schemaUrl }, this._sharedState));
        }
        return this._sharedState.loggers.get(key);
      }
      /**
       * Notifies all registered LogRecordProcessor to flush any buffered data.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      forceFlush() {
        if (this._shutdownOnce.isCalled) {
          api_1.diag.warn("invalid attempt to force flush after LoggerProvider shutdown");
          return this._shutdownOnce.promise;
        }
        return this._sharedState.activeProcessor.forceFlush();
      }
      /**
       * Flush all buffered data and shut down the LoggerProvider and all registered
       * LogRecordProcessor.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      shutdown() {
        if (this._shutdownOnce.isCalled) {
          api_1.diag.warn("shutdown may only be called once per LoggerProvider");
          return this._shutdownOnce.promise;
        }
        return this._shutdownOnce.call();
      }
      _shutdown() {
        return this._sharedState.activeProcessor.shutdown();
      }
    };
    exports.LoggerProvider = LoggerProvider;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js
var require_ConsoleLogRecordExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConsoleLogRecordExporter = void 0;
    var core_1 = require_src3();
    var core_2 = require_src3();
    var ConsoleLogRecordExporter = class {
      static {
        __name(this, "ConsoleLogRecordExporter");
      }
      /**
       * Export logs.
       * @param logs
       * @param resultCallback
       */
      export(logs3, resultCallback) {
        this._sendLogRecords(logs3, resultCallback);
      }
      /**
       * Shutdown the exporter.
       */
      shutdown() {
        return Promise.resolve();
      }
      /**
       * converts logRecord info into more readable format
       * @param logRecord
       */
      _exportInfo(logRecord) {
        return {
          resource: {
            attributes: logRecord.resource.attributes
          },
          instrumentationScope: logRecord.instrumentationScope,
          timestamp: (0, core_1.hrTimeToMicroseconds)(logRecord.hrTime),
          traceId: logRecord.spanContext?.traceId,
          spanId: logRecord.spanContext?.spanId,
          traceFlags: logRecord.spanContext?.traceFlags,
          severityText: logRecord.severityText,
          severityNumber: logRecord.severityNumber,
          body: logRecord.body,
          attributes: logRecord.attributes
        };
      }
      /**
       * Showing logs  in console
       * @param logRecords
       * @param done
       */
      _sendLogRecords(logRecords, done) {
        for (const logRecord of logRecords) {
          console.dir(this._exportInfo(logRecord), { depth: 3 });
        }
        done?.({ code: core_2.ExportResultCode.SUCCESS });
      }
    };
    exports.ConsoleLogRecordExporter = ConsoleLogRecordExporter;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js
var require_SimpleLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SimpleLogRecordProcessor = void 0;
    var core_1 = require_src3();
    var SimpleLogRecordProcessor = class {
      static {
        __name(this, "SimpleLogRecordProcessor");
      }
      _exporter;
      _shutdownOnce;
      _unresolvedExports;
      constructor(_exporter) {
        this._exporter = _exporter;
        this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
        this._unresolvedExports = /* @__PURE__ */ new Set();
      }
      onEmit(logRecord) {
        if (this._shutdownOnce.isCalled) {
          return;
        }
        const doExport = /* @__PURE__ */ __name(() => core_1.internal._export(this._exporter, [logRecord]).then((result) => {
          if (result.code !== core_1.ExportResultCode.SUCCESS) {
            (0, core_1.globalErrorHandler)(result.error ?? new Error(`SimpleLogRecordProcessor: log record export failed (status ${result})`));
          }
        }).catch(core_1.globalErrorHandler), "doExport");
        if (logRecord.resource.asyncAttributesPending) {
          const exportPromise = logRecord.resource.waitForAsyncAttributes?.().then(() => {
            this._unresolvedExports.delete(exportPromise);
            return doExport();
          }, core_1.globalErrorHandler);
          if (exportPromise != null) {
            this._unresolvedExports.add(exportPromise);
          }
        } else {
          void doExport();
        }
      }
      async forceFlush() {
        await Promise.all(Array.from(this._unresolvedExports));
      }
      shutdown() {
        return this._shutdownOnce.call();
      }
      _shutdown() {
        return this._exporter.shutdown();
      }
    };
    exports.SimpleLogRecordProcessor = SimpleLogRecordProcessor;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js
var require_InMemoryLogRecordExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InMemoryLogRecordExporter = void 0;
    var core_1 = require_src3();
    var InMemoryLogRecordExporter = class {
      static {
        __name(this, "InMemoryLogRecordExporter");
      }
      _finishedLogRecords = [];
      /**
       * Indicates if the exporter has been "shutdown."
       * When false, exported log records will not be stored in-memory.
       */
      _stopped = false;
      export(logs3, resultCallback) {
        if (this._stopped) {
          return resultCallback({
            code: core_1.ExportResultCode.FAILED,
            error: new Error("Exporter has been stopped")
          });
        }
        this._finishedLogRecords.push(...logs3);
        resultCallback({ code: core_1.ExportResultCode.SUCCESS });
      }
      shutdown() {
        this._stopped = true;
        this.reset();
        return Promise.resolve();
      }
      getFinishedLogRecords() {
        return this._finishedLogRecords;
      }
      reset() {
        this._finishedLogRecords = [];
      }
    };
    exports.InMemoryLogRecordExporter = InMemoryLogRecordExporter;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js
var require_BatchLogRecordProcessorBase = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchLogRecordProcessorBase = void 0;
    var core_1 = require_src3();
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_2 = require_src3();
    var BatchLogRecordProcessorBase = class {
      static {
        __name(this, "BatchLogRecordProcessorBase");
      }
      _exporter;
      _maxExportBatchSize;
      _maxQueueSize;
      _scheduledDelayMillis;
      _exportTimeoutMillis;
      _finishedLogRecords = [];
      _timer;
      _shutdownOnce;
      constructor(_exporter, config) {
        this._exporter = _exporter;
        this._maxExportBatchSize = config?.maxExportBatchSize ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE") ?? 512;
        this._maxQueueSize = config?.maxQueueSize ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE") ?? 2048;
        this._scheduledDelayMillis = config?.scheduledDelayMillis ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY") ?? 5e3;
        this._exportTimeoutMillis = config?.exportTimeoutMillis ?? (0, core_1.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT") ?? 3e4;
        this._shutdownOnce = new core_2.BindOnceFuture(this._shutdown, this);
        if (this._maxExportBatchSize > this._maxQueueSize) {
          api_1.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
          this._maxExportBatchSize = this._maxQueueSize;
        }
      }
      onEmit(logRecord) {
        if (this._shutdownOnce.isCalled) {
          return;
        }
        this._addToBuffer(logRecord);
      }
      forceFlush() {
        if (this._shutdownOnce.isCalled) {
          return this._shutdownOnce.promise;
        }
        return this._flushAll();
      }
      shutdown() {
        return this._shutdownOnce.call();
      }
      async _shutdown() {
        this.onShutdown();
        await this._flushAll();
        await this._exporter.shutdown();
      }
      /** Add a LogRecord in the buffer. */
      _addToBuffer(logRecord) {
        if (this._finishedLogRecords.length >= this._maxQueueSize) {
          return;
        }
        this._finishedLogRecords.push(logRecord);
        this._maybeStartTimer();
      }
      /**
       * Send all LogRecords 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((resolve2, reject) => {
          const promises = [];
          const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
          for (let i = 0; i < batchCount; i++) {
            promises.push(this._flushOneBatch());
          }
          Promise.all(promises).then(() => {
            resolve2();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedLogRecords.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve2, reject) => {
          (0, core_2.callWithTimeout)(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis).then(() => resolve2()).catch(reject);
        });
      }
      _maybeStartTimer() {
        if (this._timer !== void 0) {
          return;
        }
        this._timer = setTimeout(() => {
          this._flushOneBatch().then(() => {
            if (this._finishedLogRecords.length > 0) {
              this._clearTimer();
              this._maybeStartTimer();
            }
          }).catch((e) => {
            (0, core_2.globalErrorHandler)(e);
          });
        }, this._scheduledDelayMillis);
        (0, core_2.unrefTimer)(this._timer);
      }
      _clearTimer() {
        if (this._timer !== void 0) {
          clearTimeout(this._timer);
          this._timer = void 0;
        }
      }
      _export(logRecords) {
        const doExport = /* @__PURE__ */ __name(() => core_2.internal._export(this._exporter, logRecords).then((result) => {
          if (result.code !== core_2.ExportResultCode.SUCCESS) {
            (0, core_2.globalErrorHandler)(result.error ?? new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`));
          }
        }).catch(core_2.globalErrorHandler), "doExport");
        const pendingResources = logRecords.map((logRecord) => logRecord.resource).filter((resource) => resource.asyncAttributesPending);
        if (pendingResources.length === 0) {
          return doExport();
        } else {
          return Promise.all(pendingResources.map((resource) => resource.waitForAsyncAttributes?.())).then(doExport, core_2.globalErrorHandler);
        }
      }
    };
    exports.BatchLogRecordProcessorBase = BatchLogRecordProcessorBase;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js
var require_BatchLogRecordProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchLogRecordProcessor = void 0;
    var BatchLogRecordProcessorBase_1 = require_BatchLogRecordProcessorBase();
    var BatchLogRecordProcessor2 = class extends BatchLogRecordProcessorBase_1.BatchLogRecordProcessorBase {
      static {
        __name(this, "BatchLogRecordProcessor");
      }
      onShutdown() {
      }
    };
    exports.BatchLogRecordProcessor = BatchLogRecordProcessor2;
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js
var require_node9 = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchLogRecordProcessor = void 0;
    var BatchLogRecordProcessor_1 = require_BatchLogRecordProcessor();
    Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return BatchLogRecordProcessor_1.BatchLogRecordProcessor;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js
var require_platform8 = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchLogRecordProcessor = void 0;
    var node_1 = require_node9();
    Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.BatchLogRecordProcessor;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-logs/build/src/index.js
var require_src17 = __commonJS({
  "node_modules/@opentelemetry/sdk-logs/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchLogRecordProcessor = exports.InMemoryLogRecordExporter = exports.SimpleLogRecordProcessor = exports.ConsoleLogRecordExporter = exports.NoopLogRecordProcessor = exports.LoggerProvider = void 0;
    var LoggerProvider_1 = require_LoggerProvider();
    Object.defineProperty(exports, "LoggerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return LoggerProvider_1.LoggerProvider;
    }, "get") });
    var NoopLogRecordProcessor_1 = require_NoopLogRecordProcessor();
    Object.defineProperty(exports, "NoopLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopLogRecordProcessor_1.NoopLogRecordProcessor;
    }, "get") });
    var ConsoleLogRecordExporter_1 = require_ConsoleLogRecordExporter();
    Object.defineProperty(exports, "ConsoleLogRecordExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ConsoleLogRecordExporter_1.ConsoleLogRecordExporter;
    }, "get") });
    var SimpleLogRecordProcessor_1 = require_SimpleLogRecordProcessor();
    Object.defineProperty(exports, "SimpleLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return SimpleLogRecordProcessor_1.SimpleLogRecordProcessor;
    }, "get") });
    var InMemoryLogRecordExporter_1 = require_InMemoryLogRecordExporter();
    Object.defineProperty(exports, "InMemoryLogRecordExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return InMemoryLogRecordExporter_1.InMemoryLogRecordExporter;
    }, "get") });
    var platform_1 = require_platform8();
    Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.BatchLogRecordProcessor;
    }, "get") });
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/AbstractAsyncHooksContextManager.js
var require_AbstractAsyncHooksContextManager = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/AbstractAsyncHooksContextManager.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractAsyncHooksContextManager = void 0;
    var events_1 = __require("events");
    var ADD_LISTENER_METHODS = [
      "addListener",
      "on",
      "once",
      "prependListener",
      "prependOnceListener"
    ];
    var AbstractAsyncHooksContextManager = class {
      static {
        __name(this, "AbstractAsyncHooksContextManager");
      }
      /**
       * 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(context2, target) {
        if (target instanceof events_1.EventEmitter) {
          return this._bindEventEmitter(context2, target);
        }
        if (typeof target === "function") {
          return this._bindFunction(context2, target);
        }
        return target;
      }
      _bindFunction(context2, target) {
        const manager = this;
        const contextWrapper = /* @__PURE__ */ __name(function(...args) {
          return manager.with(context2, () => target.apply(this, args));
        }, "contextWrapper");
        Object.defineProperty(contextWrapper, "length", {
          enumerable: false,
          configurable: true,
          writable: false,
          value: target.length
        });
        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(context2, ee) {
        const map = this._getPatchMap(ee);
        if (map !== 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], context2);
        });
        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, context2) {
        const contextManager = this;
        return function(event, listener) {
          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(context2, listener);
          listeners.set(listener, patchedListener);
          contextManager._wrapped = true;
          try {
            return original.call(this, event, patchedListener);
          } finally {
            contextManager._wrapped = false;
          }
        };
      }
      _createPatchMap(ee) {
        const map = /* @__PURE__ */ Object.create(null);
        ee[this._kOtListeners] = map;
        return map;
      }
      _getPatchMap(ee) {
        return ee[this._kOtListeners];
      }
      _kOtListeners = Symbol("OtListeners");
      _wrapped = false;
    };
    exports.AbstractAsyncHooksContextManager = AbstractAsyncHooksContextManager;
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/AsyncHooksContextManager.js
var require_AsyncHooksContextManager = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/AsyncHooksContextManager.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AsyncHooksContextManager = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var asyncHooks = __require("async_hooks");
    var AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager();
    var AsyncHooksContextManager = class extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager {
      static {
        __name(this, "AsyncHooksContextManager");
      }
      _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(context2, fn, thisArg, ...args) {
        this._enterContext(context2);
        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 context2 = this._stack[this._stack.length - 1];
        if (context2 !== void 0) {
          this._contexts.set(uid, context2);
        }
      }
      /**
       * 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 context2 = this._contexts.get(uid);
        if (context2 !== void 0) {
          this._enterContext(context2);
        }
      }
      /**
       * After hook is called just after completing the execution of a async context.
       */
      _after() {
        this._exitContext();
      }
      /**
       * Set the given context as active
       */
      _enterContext(context2) {
        this._stack.push(context2);
      }
      /**
       * Remove the context at the root of the stack
       */
      _exitContext() {
        this._stack.pop();
      }
    };
    exports.AsyncHooksContextManager = AsyncHooksContextManager;
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/AsyncLocalStorageContextManager.js
var require_AsyncLocalStorageContextManager = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/AsyncLocalStorageContextManager.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AsyncLocalStorageContextManager = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var async_hooks_1 = __require("async_hooks");
    var AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager();
    var AsyncLocalStorageContextManager = class extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager {
      static {
        __name(this, "AsyncLocalStorageContextManager");
      }
      _asyncLocalStorage;
      constructor() {
        super();
        this._asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
      }
      active() {
        return this._asyncLocalStorage.getStore() ?? api_1.ROOT_CONTEXT;
      }
      with(context2, fn, thisArg, ...args) {
        const cb = thisArg == null ? fn : fn.bind(thisArg);
        return this._asyncLocalStorage.run(context2, cb, ...args);
      }
      enable() {
        return this;
      }
      disable() {
        this._asyncLocalStorage.disable();
        return this;
      }
    };
    exports.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager;
  }
});

// node_modules/@opentelemetry/context-async-hooks/build/src/index.js
var require_src18 = __commonJS({
  "node_modules/@opentelemetry/context-async-hooks/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AsyncLocalStorageContextManager = exports.AsyncHooksContextManager = void 0;
    var AsyncHooksContextManager_1 = require_AsyncHooksContextManager();
    Object.defineProperty(exports, "AsyncHooksContextManager", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AsyncHooksContextManager_1.AsyncHooksContextManager;
    }, "get") });
    var AsyncLocalStorageContextManager_1 = require_AsyncLocalStorageContextManager();
    Object.defineProperty(exports, "AsyncLocalStorageContextManager", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AsyncLocalStorageContextManager_1.AsyncLocalStorageContextManager;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js
var require_enums = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExceptionEventName = void 0;
    exports.ExceptionEventName = "exception";
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js
var require_Span = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SpanImpl = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var enums_1 = require_enums();
    var SpanImpl = class {
      static {
        __name(this, "SpanImpl");
      }
      // Below properties are included to implement ReadableSpan for export
      // purposes but are not intended to be written-to directly.
      _spanContext;
      kind;
      parentSpanContext;
      attributes = {};
      links = [];
      events = [];
      startTime;
      resource;
      instrumentationScope;
      _droppedAttributesCount = 0;
      _droppedEventsCount = 0;
      _droppedLinksCount = 0;
      name;
      status = {
        code: api_1.SpanStatusCode.UNSET
      };
      endTime = [0, 0];
      _ended = false;
      _duration = [-1, -1];
      _spanProcessor;
      _spanLimits;
      _attributeValueLengthLimit;
      _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 + (0, core_1.getTimeOrigin)());
        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;
        this.links = opts.links || [];
        this.startTime = this._getTime(opts.startTime ?? now);
        this.resource = opts.resource;
        this.instrumentationScope = opts.scope;
        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;
        if (attributeCountLimit !== void 0 && Object.keys(this.attributes).length >= attributeCountLimit && !Object.prototype.hasOwnProperty.call(this.attributes, key)) {
          this._droppedAttributesCount++;
          return this;
        }
        this.attributes[key] = this._truncateToSize(value);
        return this;
      }
      setAttributes(attributes) {
        for (const [k, v] of Object.entries(attributes)) {
          this.setAttribute(k, v);
        }
        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 attributes = (0, core_1.sanitizeAttributes)(attributesOrStartTime);
        this.events.push({
          name,
          attributes,
          time: this._getTime(timeStamp),
          droppedAttributesCount: 0
        });
        return this;
      }
      addLink(link) {
        this.links.push(link);
        return this;
      }
      addLinks(links) {
        this.links.push(...links);
        return this;
      }
      setStatus(status) {
        if (this._isSpanEnded())
          return this;
        this.status = { ...status };
        if (this.status.message != null && typeof status.message !== "string") {
          api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
          delete this.status.message;
        }
        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._ended = true;
        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`);
        }
        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 = 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;
      }
      // Utility function to truncate given value within size
      // for value type of string, will truncate to given limit
      // for type of non-string, will return same value
      _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;
      }
    };
    exports.SpanImpl = SpanImpl;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js
var require_Sampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SamplingDecision = void 0;
    var SamplingDecision;
    (function(SamplingDecision2) {
      SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD";
      SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD";
      SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
    })(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js
var require_AlwaysOffSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AlwaysOffSampler = void 0;
    var Sampler_1 = require_Sampler();
    var AlwaysOffSampler = class {
      static {
        __name(this, "AlwaysOffSampler");
      }
      shouldSample() {
        return {
          decision: Sampler_1.SamplingDecision.NOT_RECORD
        };
      }
      toString() {
        return "AlwaysOffSampler";
      }
    };
    exports.AlwaysOffSampler = AlwaysOffSampler;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js
var require_AlwaysOnSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AlwaysOnSampler = void 0;
    var Sampler_1 = require_Sampler();
    var AlwaysOnSampler = class {
      static {
        __name(this, "AlwaysOnSampler");
      }
      shouldSample() {
        return {
          decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED
        };
      }
      toString() {
        return "AlwaysOnSampler";
      }
    };
    exports.AlwaysOnSampler = AlwaysOnSampler;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js
var require_ParentBasedSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ParentBasedSampler = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var AlwaysOffSampler_1 = require_AlwaysOffSampler();
    var AlwaysOnSampler_1 = require_AlwaysOnSampler();
    var ParentBasedSampler = class {
      static {
        __name(this, "ParentBasedSampler");
      }
      _root;
      _remoteParentSampled;
      _remoteParentNotSampled;
      _localParentSampled;
      _localParentNotSampled;
      constructor(config) {
        this._root = config.root;
        if (!this._root) {
          (0, core_1.globalErrorHandler)(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(context2, traceId, spanName, spanKind, attributes, links) {
        const parentContext = api_1.trace.getSpanContext(context2);
        if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) {
          return this._root.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
        }
        if (parentContext.isRemote) {
          if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
            return this._remoteParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
          }
          return this._remoteParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
        }
        if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
          return this._localParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
        }
        return this._localParentNotSampled.shouldSample(context2, 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;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js
var require_TraceIdRatioBasedSampler = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TraceIdRatioBasedSampler = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var Sampler_1 = require_Sampler();
    var TraceIdRatioBasedSampler = class {
      static {
        __name(this, "TraceIdRatioBasedSampler");
      }
      _ratio;
      _upperBound;
      constructor(_ratio = 0) {
        this._ratio = _ratio;
        this._ratio = this._normalize(_ratio);
        this._upperBound = Math.floor(this._ratio * 4294967295);
      }
      shouldSample(context2, 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 < traceId.length / 8; i++) {
          const pos = i * 8;
          const part = parseInt(traceId.slice(pos, pos + 8), 16);
          accumulation = (accumulation ^ part) >>> 0;
        }
        return accumulation;
      }
    };
    exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/config.js
var require_config2 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/config.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.buildSamplerFromEnv = exports.loadDefaultConfig = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var AlwaysOffSampler_1 = require_AlwaysOffSampler();
    var AlwaysOnSampler_1 = require_AlwaysOnSampler();
    var ParentBasedSampler_1 = require_ParentBasedSampler();
    var TraceIdRatioBasedSampler_1 = require_TraceIdRatioBasedSampler();
    var DEFAULT_RATIO = 1;
    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
        }
      };
    }
    __name(loadDefaultConfig, "loadDefaultConfig");
    exports.loadDefaultConfig = loadDefaultConfig;
    function buildSamplerFromEnv() {
      const sampler = (0, core_1.getStringFromEnv)("OTEL_TRACES_SAMPLER") ?? "parentbased_always_on";
      switch (sampler) {
        case "always_on":
          return new AlwaysOnSampler_1.AlwaysOnSampler();
        case "always_off":
          return new AlwaysOffSampler_1.AlwaysOffSampler();
        case "parentbased_always_on":
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new AlwaysOnSampler_1.AlwaysOnSampler()
          });
        case "parentbased_always_off":
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new AlwaysOffSampler_1.AlwaysOffSampler()
          });
        case "traceidratio":
          return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
        case "parentbased_traceidratio":
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())
          });
        default:
          api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${"parentbased_always_on"}".`);
          return new ParentBasedSampler_1.ParentBasedSampler({
            root: new AlwaysOnSampler_1.AlwaysOnSampler()
          });
      }
    }
    __name(buildSamplerFromEnv, "buildSamplerFromEnv");
    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;
    }
    __name(getSamplerProbabilityFromEnv, "getSamplerProbabilityFromEnv");
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js
var require_utility = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.reconfigureLimits = exports.mergeConfig = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0;
    var config_1 = require_config2();
    var core_1 = require_src3();
    exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
    exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;
    function mergeConfig(userConfig) {
      const perInstanceDefaults = {
        sampler: (0, config_1.buildSamplerFromEnv)()
      };
      const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)();
      const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
      target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
      target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
      return target;
    }
    __name(mergeConfig, "mergeConfig");
    exports.mergeConfig = mergeConfig;
    function reconfigureLimits(userConfig) {
      const spanLimits = Object.assign({}, userConfig.spanLimits);
      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;
      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 });
    }
    __name(reconfigureLimits, "reconfigureLimits");
    exports.reconfigureLimits = reconfigureLimits;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js
var require_BatchSpanProcessorBase = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchSpanProcessorBase = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var BatchSpanProcessorBase = class {
      static {
        __name(this, "BatchSpanProcessorBase");
      }
      _exporter;
      _maxExportBatchSize;
      _maxQueueSize;
      _scheduledDelayMillis;
      _exportTimeoutMillis;
      _isExporting = false;
      _finishedSpans = [];
      _timer;
      _shutdownOnce;
      _droppedSpansCount = 0;
      constructor(_exporter, config) {
        this._exporter = _exporter;
        this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512;
        this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048;
        this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : (0, core_1.getNumberFromEnv)("OTEL_BSP_SCHEDULE_DELAY") ?? 5e3;
        this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : (0, core_1.getNumberFromEnv)("OTEL_BSP_EXPORT_TIMEOUT") ?? 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;
        }
      }
      forceFlush() {
        if (this._shutdownOnce.isCalled) {
          return this._shutdownOnce.promise;
        }
        return this._flushAll();
      }
      // does nothing.
      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(() => {
          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++;
          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((resolve2, 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(() => {
            resolve2();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedSpans.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve2, reject) => {
          const timer = setTimeout(() => {
            reject(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 = /* @__PURE__ */ __name(() => this._exporter.export(spans, (result) => {
              clearTimeout(timer);
              if (result.code === core_1.ExportResultCode.SUCCESS) {
                resolve2();
              } else {
                reject(result.error ?? new Error("BatchSpanProcessor: span export failed"));
              }
            }), "doExport");
            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 = /* @__PURE__ */ __name(() => {
          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);
          });
        }, "flush");
        if (this._finishedSpans.length >= this._maxExportBatchSize) {
          return flush();
        }
        if (this._timer !== void 0)
          return;
        this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
        (0, core_1.unrefTimer)(this._timer);
      }
      _clearTimer() {
        if (this._timer !== void 0) {
          clearTimeout(this._timer);
          this._timer = void 0;
        }
      }
    };
    exports.BatchSpanProcessorBase = BatchSpanProcessorBase;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js
var require_BatchSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BatchSpanProcessor = void 0;
    var BatchSpanProcessorBase_1 = require_BatchSpanProcessorBase();
    var BatchSpanProcessor2 = class extends BatchSpanProcessorBase_1.BatchSpanProcessorBase {
      static {
        __name(this, "BatchSpanProcessor");
      }
      onShutdown() {
      }
    };
    exports.BatchSpanProcessor = BatchSpanProcessor2;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js
var require_RandomIdGenerator = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RandomIdGenerator = void 0;
    var SPAN_ID_BYTES = 8;
    var TRACE_ID_BYTES = 16;
    var RandomIdGenerator = class {
      static {
        __name(this, "RandomIdGenerator");
      }
      /**
       * 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;
    var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
    function getIdGenerator(bytes) {
      return /* @__PURE__ */ __name(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);
      }, "generateId");
    }
    __name(getIdGenerator, "getIdGenerator");
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js
var require_node10 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0;
    var BatchSpanProcessor_1 = require_BatchSpanProcessor();
    Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return BatchSpanProcessor_1.BatchSpanProcessor;
    }, "get") });
    var RandomIdGenerator_1 = require_RandomIdGenerator();
    Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return RandomIdGenerator_1.RandomIdGenerator;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js
var require_platform9 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0;
    var node_1 = require_node10();
    Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.BatchSpanProcessor;
    }, "get") });
    Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.RandomIdGenerator;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js
var require_Tracer = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Tracer = void 0;
    var api = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var Span_1 = require_Span();
    var utility_1 = require_utility();
    var platform_1 = require_platform9();
    var Tracer = class {
      static {
        __name(this, "Tracer");
      }
      _sampler;
      _generalLimits;
      _spanLimits;
      _idGenerator;
      instrumentationScope;
      _resource;
      _spanProcessor;
      /**
       * Constructs a new Tracer instance.
       */
      constructor(instrumentationScope, config, resource, spanProcessor) {
        const localConfig = (0, utility_1.mergeConfig)(config);
        this._sampler = localConfig.sampler;
        this._generalLimits = localConfig.generalLimits;
        this._spanLimits = localConfig.spanLimits;
        this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator();
        this._resource = resource;
        this._spanProcessor = spanProcessor;
        this.instrumentationScope = instrumentationScope;
      }
      /**
       * Starts a new Span or returns the default NoopSpan based on the sampling
       * decision.
       */
      startSpan(name, options = {}, context2 = api.context.active()) {
        if (options.root) {
          context2 = api.trace.deleteSpan(context2);
        }
        const parentSpan = api.trace.getSpan(context2);
        if ((0, core_1.isTracingSuppressed)(context2)) {
          api.diag.debug("Instrumentation suppressed, returning Noop Span");
          const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);
          return nonRecordingSpan;
        }
        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(context2, traceId, name, spanKind, attributes, links);
        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");
          const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);
          return nonRecordingSpan;
        }
        const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes));
        const span = new Span_1.SpanImpl({
          resource: this._resource,
          scope: this.instrumentationScope,
          context: context2,
          spanContext,
          name,
          kind: spanKind,
          links,
          parentSpanContext: validParentSpanContext,
          attributes: initAttributes,
          startTime: options.startTime,
          spanProcessor: this._spanProcessor,
          spanLimits: this._spanLimits
        });
        return span;
      }
      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);
      }
      /** Returns the active {@link GeneralLimits}. */
      getGeneralLimits() {
        return this._generalLimits;
      }
      /** Returns the active {@link SpanLimits}. */
      getSpanLimits() {
        return this._spanLimits;
      }
    };
    exports.Tracer = Tracer;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js
var require_MultiSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MultiSpanProcessor = void 0;
    var core_1 = require_src3();
    var MultiSpanProcessor = class {
      static {
        __name(this, "MultiSpanProcessor");
      }
      _spanProcessors;
      constructor(_spanProcessors) {
        this._spanProcessors = _spanProcessors;
      }
      forceFlush() {
        const promises = [];
        for (const spanProcessor of this._spanProcessors) {
          promises.push(spanProcessor.forceFlush());
        }
        return new Promise((resolve2) => {
          Promise.all(promises).then(() => {
            resolve2();
          }).catch((error) => {
            (0, core_1.globalErrorHandler)(error || new Error("MultiSpanProcessor: forceFlush failed"));
            resolve2();
          });
        });
      }
      onStart(span, context2) {
        for (const spanProcessor of this._spanProcessors) {
          spanProcessor.onStart(span, context2);
        }
      }
      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((resolve2, reject) => {
          Promise.all(promises).then(() => {
            resolve2();
          }, reject);
        });
      }
    };
    exports.MultiSpanProcessor = MultiSpanProcessor;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js
var require_BasicTracerProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BasicTracerProvider = exports.ForceFlushState = void 0;
    var core_1 = require_src3();
    var resources_1 = require_src8();
    var Tracer_1 = require_Tracer();
    var config_1 = require_config2();
    var MultiSpanProcessor_1 = require_MultiSpanProcessor();
    var utility_1 = require_utility();
    var ForceFlushState;
    (function(ForceFlushState2) {
      ForceFlushState2[ForceFlushState2["resolved"] = 0] = "resolved";
      ForceFlushState2[ForceFlushState2["timeout"] = 1] = "timeout";
      ForceFlushState2[ForceFlushState2["error"] = 2] = "error";
      ForceFlushState2[ForceFlushState2["unresolved"] = 3] = "unresolved";
    })(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {}));
    var BasicTracerProvider = class {
      static {
        __name(this, "BasicTracerProvider");
      }
      _config;
      _tracers = /* @__PURE__ */ new Map();
      _resource;
      _activeSpanProcessor;
      constructor(config = {}) {
        const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config));
        this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)();
        this._config = Object.assign({}, mergedConfig, {
          resource: this._resource
        });
        const spanProcessors = [];
        if (config.spanProcessors?.length) {
          spanProcessors.push(...config.spanProcessors);
        }
        this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors);
      }
      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._config, this._resource, this._activeSpanProcessor));
        }
        return this._tracers.get(key);
      }
      forceFlush() {
        const timeout = this._config.forceFlushTimeoutMillis;
        const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
          return new Promise((resolve2) => {
            let state;
            const timeoutInterval = setTimeout(() => {
              resolve2(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;
                resolve2(state);
              }
            }).catch((error) => {
              clearTimeout(timeoutInterval);
              state = ForceFlushState.error;
              resolve2(error);
            });
          });
        });
        return new Promise((resolve2, reject) => {
          Promise.all(promises).then((results) => {
            const errors = results.filter((result) => result !== ForceFlushState.resolved);
            if (errors.length > 0) {
              reject(errors);
            } else {
              resolve2();
            }
          }).catch((error) => reject([error]));
        });
      }
      shutdown() {
        return this._activeSpanProcessor.shutdown();
      }
    };
    exports.BasicTracerProvider = BasicTracerProvider;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js
var require_ConsoleSpanExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConsoleSpanExporter = void 0;
    var core_1 = require_src3();
    var ConsoleSpanExporter = class {
      static {
        __name(this, "ConsoleSpanExporter");
      }
      /**
       * 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;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js
var require_InMemorySpanExporter = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InMemorySpanExporter = void 0;
    var core_1 = require_src3();
    var InMemorySpanExporter = class {
      static {
        __name(this, "InMemorySpanExporter");
      }
      _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: 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;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js
var require_SimpleSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SimpleSpanProcessor = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var SimpleSpanProcessor = class {
      static {
        __name(this, "SimpleSpanProcessor");
      }
      _exporter;
      _shutdownOnce;
      _pendingExports;
      constructor(_exporter) {
        this._exporter = _exporter;
        this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
        this._pendingExports = /* @__PURE__ */ new Set();
      }
      async forceFlush() {
        await Promise.all(Array.from(this._pendingExports));
        if (this._exporter.forceFlush) {
          await this._exporter.forceFlush();
        }
      }
      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).catch((err) => (0, core_1.globalErrorHandler)(err));
        this._pendingExports.add(pendingExport);
        pendingExport.finally(() => 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]);
        if (result.code !== core_1.ExportResultCode.SUCCESS) {
          throw result.error ?? new Error(`SimpleSpanProcessor: span export failed (status ${result})`);
        }
      }
      shutdown() {
        return this._shutdownOnce.call();
      }
      _shutdown() {
        return this._exporter.shutdown();
      }
    };
    exports.SimpleSpanProcessor = SimpleSpanProcessor;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js
var require_NoopSpanProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NoopSpanProcessor = void 0;
    var NoopSpanProcessor = class {
      static {
        __name(this, "NoopSpanProcessor");
      }
      onStart(_span, _context) {
      }
      onEnd(_span) {
      }
      shutdown() {
        return Promise.resolve();
      }
      forceFlush() {
        return Promise.resolve();
      }
    };
    exports.NoopSpanProcessor = NoopSpanProcessor;
  }
});

// node_modules/@opentelemetry/sdk-trace-base/build/src/index.js
var require_src19 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-base/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.SimpleSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.RandomIdGenerator = exports.BatchSpanProcessor = exports.BasicTracerProvider = void 0;
    var BasicTracerProvider_1 = require_BasicTracerProvider();
    Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return BasicTracerProvider_1.BasicTracerProvider;
    }, "get") });
    var platform_1 = require_platform9();
    Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.BatchSpanProcessor;
    }, "get") });
    Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.RandomIdGenerator;
    }, "get") });
    var ConsoleSpanExporter_1 = require_ConsoleSpanExporter();
    Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ConsoleSpanExporter_1.ConsoleSpanExporter;
    }, "get") });
    var InMemorySpanExporter_1 = require_InMemorySpanExporter();
    Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return InMemorySpanExporter_1.InMemorySpanExporter;
    }, "get") });
    var SimpleSpanProcessor_1 = require_SimpleSpanProcessor();
    Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return SimpleSpanProcessor_1.SimpleSpanProcessor;
    }, "get") });
    var NoopSpanProcessor_1 = require_NoopSpanProcessor();
    Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return NoopSpanProcessor_1.NoopSpanProcessor;
    }, "get") });
    var AlwaysOffSampler_1 = require_AlwaysOffSampler();
    Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AlwaysOffSampler_1.AlwaysOffSampler;
    }, "get") });
    var AlwaysOnSampler_1 = require_AlwaysOnSampler();
    Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return AlwaysOnSampler_1.AlwaysOnSampler;
    }, "get") });
    var ParentBasedSampler_1 = require_ParentBasedSampler();
    Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return ParentBasedSampler_1.ParentBasedSampler;
    }, "get") });
    var TraceIdRatioBasedSampler_1 = require_TraceIdRatioBasedSampler();
    Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler;
    }, "get") });
    var Sampler_1 = require_Sampler();
    Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return Sampler_1.SamplingDecision;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-trace-node/build/src/NodeTracerProvider.js
var require_NodeTracerProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-node/build/src/NodeTracerProvider.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodeTracerProvider = void 0;
    var context_async_hooks_1 = require_src18();
    var sdk_trace_base_1 = require_src19();
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    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);
    }
    __name(setupContextManager, "setupContextManager");
    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);
    }
    __name(setupPropagator, "setupPropagator");
    var NodeTracerProvider = class extends sdk_trace_base_1.BasicTracerProvider {
      static {
        __name(this, "NodeTracerProvider");
      }
      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;
  }
});

// node_modules/@opentelemetry/sdk-trace-node/build/src/index.js
var require_src20 = __commonJS({
  "node_modules/@opentelemetry/sdk-trace-node/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    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: /* @__PURE__ */ __name(function() {
      return NodeTracerProvider_1.NodeTracerProvider;
    }, "get") });
    var sdk_trace_base_1 = require_src19();
    Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.AlwaysOffSampler;
    }, "get") });
    Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.AlwaysOnSampler;
    }, "get") });
    Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.BasicTracerProvider;
    }, "get") });
    Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.BatchSpanProcessor;
    }, "get") });
    Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.ConsoleSpanExporter;
    }, "get") });
    Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.InMemorySpanExporter;
    }, "get") });
    Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.NoopSpanProcessor;
    }, "get") });
    Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.ParentBasedSampler;
    }, "get") });
    Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.RandomIdGenerator;
    }, "get") });
    Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.SamplingDecision;
    }, "get") });
    Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.SimpleSpanProcessor;
    }, "get") });
    Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_trace_base_1.TraceIdRatioBasedSampler;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/autoLoaderUtils.js
var require_autoLoaderUtils = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/autoLoaderUtils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.disableInstrumentations = exports.enableInstrumentations = void 0;
    function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) {
      for (let i = 0, j = instrumentations.length; i < j; i++) {
        const instrumentation = instrumentations[i];
        if (tracerProvider) {
          instrumentation.setTracerProvider(tracerProvider);
        }
        if (meterProvider) {
          instrumentation.setMeterProvider(meterProvider);
        }
        if (loggerProvider && instrumentation.setLoggerProvider) {
          instrumentation.setLoggerProvider(loggerProvider);
        }
        if (!instrumentation.getConfig().enabled) {
          instrumentation.enable();
        }
      }
    }
    __name(enableInstrumentations, "enableInstrumentations");
    exports.enableInstrumentations = enableInstrumentations;
    function disableInstrumentations(instrumentations) {
      instrumentations.forEach((instrumentation) => instrumentation.disable());
    }
    __name(disableInstrumentations, "disableInstrumentations");
    exports.disableInstrumentations = disableInstrumentations;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/autoLoader.js
var require_autoLoader = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/autoLoader.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.registerInstrumentations = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var api_logs_1 = require_src2();
    var autoLoaderUtils_1 = require_autoLoaderUtils();
    function registerInstrumentations(options) {
      const tracerProvider = options.tracerProvider || api_1.trace.getTracerProvider();
      const meterProvider = options.meterProvider || api_1.metrics.getMeterProvider();
      const loggerProvider = options.loggerProvider || api_logs_1.logs.getLoggerProvider();
      const instrumentations = options.instrumentations?.flat() ?? [];
      (0, autoLoaderUtils_1.enableInstrumentations)(instrumentations, tracerProvider, meterProvider, loggerProvider);
      return () => {
        (0, autoLoaderUtils_1.disableInstrumentations)(instrumentations);
      };
    }
    __name(registerInstrumentations, "registerInstrumentations");
    exports.registerInstrumentations = registerInstrumentations;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/semver.js
var require_semver = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/semver.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.satisfies = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var VERSION_REGEXP = /^(?:v)?(?<version>(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*))(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
    var RANGE_REGEXP = /^(?<op><|>|=|==|<=|>=|~|\^|~>)?\s*(?:v)?(?<version>(?<major>x|X|\*|0|[1-9]\d*)(?:\.(?<minor>x|X|\*|0|[1-9]\d*))?(?:\.(?<patch>x|X|\*|0|[1-9]\d*))?)(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
    var operatorResMap = {
      ">": [1],
      ">=": [0, 1],
      "=": [0],
      "<=": [-1, 0],
      "<": [-1],
      "!=": [-1, 1]
    };
    function satisfies(version, range, options) {
      if (!_validateVersion(version)) {
        api_1.diag.error(`Invalid version: ${version}`);
        return false;
      }
      if (!range) {
        return true;
      }
      range = range.replace(/([<>=~^]+)\s+/g, "$1");
      const parsedVersion = _parseVersion(version);
      if (!parsedVersion) {
        return false;
      }
      const allParsedRanges = [];
      const checkResult = _doSatisfies(parsedVersion, range, allParsedRanges, options);
      if (checkResult && !options?.includePrerelease) {
        return _doPreleaseCheck(parsedVersion, allParsedRanges);
      }
      return checkResult;
    }
    __name(satisfies, "satisfies");
    exports.satisfies = satisfies;
    function _validateVersion(version) {
      return typeof version === "string" && VERSION_REGEXP.test(version);
    }
    __name(_validateVersion, "_validateVersion");
    function _doSatisfies(parsedVersion, range, allParsedRanges, options) {
      if (range.includes("||")) {
        const ranges = range.trim().split("||");
        for (const r of ranges) {
          if (_checkRange(parsedVersion, r, allParsedRanges, options)) {
            return true;
          }
        }
        return false;
      } else if (range.includes(" - ")) {
        range = replaceHyphen(range, options);
      } else if (range.includes(" ")) {
        const ranges = range.trim().replace(/\s{2,}/g, " ").split(" ");
        for (const r of ranges) {
          if (!_checkRange(parsedVersion, r, allParsedRanges, options)) {
            return false;
          }
        }
        return true;
      }
      return _checkRange(parsedVersion, range, allParsedRanges, options);
    }
    __name(_doSatisfies, "_doSatisfies");
    function _checkRange(parsedVersion, range, allParsedRanges, options) {
      range = _normalizeRange(range, options);
      if (range.includes(" ")) {
        return _doSatisfies(parsedVersion, range, allParsedRanges, options);
      } else {
        const parsedRange = _parseRange(range);
        allParsedRanges.push(parsedRange);
        return _satisfies(parsedVersion, parsedRange);
      }
    }
    __name(_checkRange, "_checkRange");
    function _satisfies(parsedVersion, parsedRange) {
      if (parsedRange.invalid) {
        return false;
      }
      if (!parsedRange.version || _isWildcard(parsedRange.version)) {
        return true;
      }
      let comparisonResult = _compareVersionSegments(parsedVersion.versionSegments || [], parsedRange.versionSegments || []);
      if (comparisonResult === 0) {
        const versionPrereleaseSegments = parsedVersion.prereleaseSegments || [];
        const rangePrereleaseSegments = parsedRange.prereleaseSegments || [];
        if (!versionPrereleaseSegments.length && !rangePrereleaseSegments.length) {
          comparisonResult = 0;
        } else if (!versionPrereleaseSegments.length && rangePrereleaseSegments.length) {
          comparisonResult = 1;
        } else if (versionPrereleaseSegments.length && !rangePrereleaseSegments.length) {
          comparisonResult = -1;
        } else {
          comparisonResult = _compareVersionSegments(versionPrereleaseSegments, rangePrereleaseSegments);
        }
      }
      return operatorResMap[parsedRange.op]?.includes(comparisonResult);
    }
    __name(_satisfies, "_satisfies");
    function _doPreleaseCheck(parsedVersion, allParsedRanges) {
      if (parsedVersion.prerelease) {
        return allParsedRanges.some((r) => r.prerelease && r.version === parsedVersion.version);
      }
      return true;
    }
    __name(_doPreleaseCheck, "_doPreleaseCheck");
    function _normalizeRange(range, options) {
      range = range.trim();
      range = replaceCaret(range, options);
      range = replaceTilde(range);
      range = replaceXRange(range, options);
      range = range.trim();
      return range;
    }
    __name(_normalizeRange, "_normalizeRange");
    function isX(id) {
      return !id || id.toLowerCase() === "x" || id === "*";
    }
    __name(isX, "isX");
    function _parseVersion(versionString) {
      const match = versionString.match(VERSION_REGEXP);
      if (!match) {
        api_1.diag.error(`Invalid version: ${versionString}`);
        return void 0;
      }
      const version = match.groups.version;
      const prerelease = match.groups.prerelease;
      const build = match.groups.build;
      const versionSegments = version.split(".");
      const prereleaseSegments = prerelease?.split(".");
      return {
        op: void 0,
        version,
        versionSegments,
        versionSegmentCount: versionSegments.length,
        prerelease,
        prereleaseSegments,
        prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
        build
      };
    }
    __name(_parseVersion, "_parseVersion");
    function _parseRange(rangeString) {
      if (!rangeString) {
        return {};
      }
      const match = rangeString.match(RANGE_REGEXP);
      if (!match) {
        api_1.diag.error(`Invalid range: ${rangeString}`);
        return {
          invalid: true
        };
      }
      let op = match.groups.op;
      const version = match.groups.version;
      const prerelease = match.groups.prerelease;
      const build = match.groups.build;
      const versionSegments = version.split(".");
      const prereleaseSegments = prerelease?.split(".");
      if (op === "==") {
        op = "=";
      }
      return {
        op: op || "=",
        version,
        versionSegments,
        versionSegmentCount: versionSegments.length,
        prerelease,
        prereleaseSegments,
        prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
        build
      };
    }
    __name(_parseRange, "_parseRange");
    function _isWildcard(s) {
      return s === "*" || s === "x" || s === "X";
    }
    __name(_isWildcard, "_isWildcard");
    function _parseVersionString(v) {
      const n = parseInt(v, 10);
      return isNaN(n) ? v : n;
    }
    __name(_parseVersionString, "_parseVersionString");
    function _normalizeVersionType(a, b) {
      if (typeof a === typeof b) {
        if (typeof a === "number") {
          return [a, b];
        } else if (typeof a === "string") {
          return [a, b];
        } else {
          throw new Error("Version segments can only be strings or numbers");
        }
      } else {
        return [String(a), String(b)];
      }
    }
    __name(_normalizeVersionType, "_normalizeVersionType");
    function _compareVersionStrings(v1, v2) {
      if (_isWildcard(v1) || _isWildcard(v2)) {
        return 0;
      }
      const [parsedV1, parsedV2] = _normalizeVersionType(_parseVersionString(v1), _parseVersionString(v2));
      if (parsedV1 > parsedV2) {
        return 1;
      } else if (parsedV1 < parsedV2) {
        return -1;
      }
      return 0;
    }
    __name(_compareVersionStrings, "_compareVersionStrings");
    function _compareVersionSegments(v1, v2) {
      for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
        const res = _compareVersionStrings(v1[i] || "0", v2[i] || "0");
        if (res !== 0) {
          return res;
        }
      }
      return 0;
    }
    __name(_compareVersionSegments, "_compareVersionSegments");
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var NUMERICIDENTIFIER = "0|[1-9]\\d*";
    var NONNUMERICIDENTIFIER = `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`;
    var GTLT = "((?:<|>)?=?)";
    var PRERELEASEIDENTIFIER = `(?:${NUMERICIDENTIFIER}|${NONNUMERICIDENTIFIER})`;
    var PRERELEASE = `(?:-(${PRERELEASEIDENTIFIER}(?:\\.${PRERELEASEIDENTIFIER})*))`;
    var BUILDIDENTIFIER = `${LETTERDASHNUMBER}+`;
    var BUILD = `(?:\\+(${BUILDIDENTIFIER}(?:\\.${BUILDIDENTIFIER})*))`;
    var XRANGEIDENTIFIER = `${NUMERICIDENTIFIER}|x|X|\\*`;
    var XRANGEPLAIN = `[v=\\s]*(${XRANGEIDENTIFIER})(?:\\.(${XRANGEIDENTIFIER})(?:\\.(${XRANGEIDENTIFIER})(?:${PRERELEASE})?${BUILD}?)?)?`;
    var XRANGE = `^${GTLT}\\s*${XRANGEPLAIN}$`;
    var XRANGE_REGEXP = new RegExp(XRANGE);
    var HYPHENRANGE = `^\\s*(${XRANGEPLAIN})\\s+-\\s+(${XRANGEPLAIN})\\s*$`;
    var HYPHENRANGE_REGEXP = new RegExp(HYPHENRANGE);
    var LONETILDE = "(?:~>?)";
    var TILDE = `^${LONETILDE}${XRANGEPLAIN}$`;
    var TILDE_REGEXP = new RegExp(TILDE);
    var LONECARET = "(?:\\^)";
    var CARET = `^${LONECARET}${XRANGEPLAIN}$`;
    var CARET_REGEXP = new RegExp(CARET);
    function replaceTilde(comp) {
      const r = TILDE_REGEXP;
      return comp.replace(r, (_, M, m, p, pr) => {
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
        } else if (pr) {
          ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
        } else {
          ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
        }
        return ret;
      });
    }
    __name(replaceTilde, "replaceTilde");
    function replaceCaret(comp, options) {
      const r = CARET_REGEXP;
      const z = options?.includePrerelease ? "-0" : "";
      return comp.replace(r, (_, M, m, p, pr) => {
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          if (M === "0") {
            ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
          } else {
            ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          if (M === "0") {
            if (m === "0") {
              ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
          }
        }
        return ret;
      });
    }
    __name(replaceCaret, "replaceCaret");
    function replaceXRange(comp, options) {
      const r = XRANGE_REGEXP;
      return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
        const xM = isX(M);
        const xm = xM || isX(m);
        const xp = xm || isX(p);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options?.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m = 0;
              p = 0;
            } else {
              m = +m + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m = +m + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m}.${p}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
        }
        return ret;
      });
    }
    __name(replaceXRange, "replaceXRange");
    function replaceHyphen(comp, options) {
      const r = HYPHENRANGE_REGEXP;
      return comp.replace(r, (_, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
        if (isX(fM)) {
          from = "";
        } else if (isX(fm)) {
          from = `>=${fM}.0.0${options?.includePrerelease ? "-0" : ""}`;
        } else if (isX(fp)) {
          from = `>=${fM}.${fm}.0${options?.includePrerelease ? "-0" : ""}`;
        } else if (fpr) {
          from = `>=${from}`;
        } else {
          from = `>=${from}${options?.includePrerelease ? "-0" : ""}`;
        }
        if (isX(tM)) {
          to = "";
        } else if (isX(tm)) {
          to = `<${+tM + 1}.0.0-0`;
        } else if (isX(tp)) {
          to = `<${tM}.${+tm + 1}.0-0`;
        } else if (tpr) {
          to = `<=${tM}.${tm}.${tp}-${tpr}`;
        } else if (options?.includePrerelease) {
          to = `<${tM}.${tm}.${+tp + 1}-0`;
        } else {
          to = `<=${to}`;
        }
        return `${from} ${to}`.trim();
      });
    }
    __name(replaceHyphen, "replaceHyphen");
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/shimmer.js
var require_shimmer = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/shimmer.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.massUnwrap = exports.unwrap = exports.massWrap = exports.wrap = void 0;
    var logger = console.error.bind(console);
    function defineProperty(obj, name, value) {
      const enumerable = !!obj[name] && Object.prototype.propertyIsEnumerable.call(obj, name);
      Object.defineProperty(obj, name, {
        configurable: true,
        enumerable,
        writable: true,
        value
      });
    }
    __name(defineProperty, "defineProperty");
    var wrap = /* @__PURE__ */ __name((nodule, name, wrapper) => {
      if (!nodule || !nodule[name]) {
        logger("no original function " + String(name) + " to wrap");
        return;
      }
      if (!wrapper) {
        logger("no wrapper function");
        logger(new Error().stack);
        return;
      }
      const original = nodule[name];
      if (typeof original !== "function" || typeof wrapper !== "function") {
        logger("original object and wrapper must be functions");
        return;
      }
      const wrapped = wrapper(original, name);
      defineProperty(wrapped, "__original", original);
      defineProperty(wrapped, "__unwrap", () => {
        if (nodule[name] === wrapped) {
          defineProperty(nodule, name, original);
        }
      });
      defineProperty(wrapped, "__wrapped", true);
      defineProperty(nodule, name, wrapped);
      return wrapped;
    }, "wrap");
    exports.wrap = wrap;
    var massWrap = /* @__PURE__ */ __name((nodules, names, wrapper) => {
      if (!nodules) {
        logger("must provide one or more modules to patch");
        logger(new Error().stack);
        return;
      } else if (!Array.isArray(nodules)) {
        nodules = [nodules];
      }
      if (!(names && Array.isArray(names))) {
        logger("must provide one or more functions to wrap on modules");
        return;
      }
      nodules.forEach((nodule) => {
        names.forEach((name) => {
          (0, exports.wrap)(nodule, name, wrapper);
        });
      });
    }, "massWrap");
    exports.massWrap = massWrap;
    var unwrap = /* @__PURE__ */ __name((nodule, name) => {
      if (!nodule || !nodule[name]) {
        logger("no function to unwrap.");
        logger(new Error().stack);
        return;
      }
      const wrapped = nodule[name];
      if (!wrapped.__unwrap) {
        logger("no original to unwrap to -- has " + String(name) + " already been unwrapped?");
      } else {
        wrapped.__unwrap();
        return;
      }
    }, "unwrap");
    exports.unwrap = unwrap;
    var massUnwrap = /* @__PURE__ */ __name((nodules, names) => {
      if (!nodules) {
        logger("must provide one or more modules to patch");
        logger(new Error().stack);
        return;
      } else if (!Array.isArray(nodules)) {
        nodules = [nodules];
      }
      if (!(names && Array.isArray(names))) {
        logger("must provide one or more functions to unwrap on modules");
        return;
      }
      nodules.forEach((nodule) => {
        names.forEach((name) => {
          (0, exports.unwrap)(nodule, name);
        });
      });
    }, "massUnwrap");
    exports.massUnwrap = massUnwrap;
    function shimmer(options) {
      if (options && options.logger) {
        if (typeof options.logger !== "function") {
          logger("new logger isn't a function, not replacing");
        } else {
          logger = options.logger;
        }
      }
    }
    __name(shimmer, "shimmer");
    exports.default = shimmer;
    shimmer.wrap = exports.wrap;
    shimmer.massWrap = exports.massWrap;
    shimmer.unwrap = exports.unwrap;
    shimmer.massUnwrap = exports.massUnwrap;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/instrumentation.js
var require_instrumentation = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/instrumentation.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InstrumentationAbstract = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var api_logs_1 = require_src2();
    var shimmer = require_shimmer();
    var InstrumentationAbstract = class {
      static {
        __name(this, "InstrumentationAbstract");
      }
      instrumentationName;
      instrumentationVersion;
      _config = {};
      _tracer;
      _meter;
      _logger;
      _diag;
      constructor(instrumentationName, instrumentationVersion, config) {
        this.instrumentationName = instrumentationName;
        this.instrumentationVersion = instrumentationVersion;
        this.setConfig(config);
        this._diag = api_1.diag.createComponentLogger({
          namespace: instrumentationName
        });
        this._tracer = api_1.trace.getTracer(instrumentationName, instrumentationVersion);
        this._meter = api_1.metrics.getMeter(instrumentationName, instrumentationVersion);
        this._logger = api_logs_1.logs.getLogger(instrumentationName, instrumentationVersion);
        this._updateMetricInstruments();
      }
      /* Api to wrap instrumented method */
      _wrap = shimmer.wrap;
      /* Api to unwrap instrumented methods */
      _unwrap = shimmer.unwrap;
      /* Api to mass wrap instrumented method */
      _massWrap = shimmer.massWrap;
      /* Api to mass unwrap instrumented methods */
      _massUnwrap = shimmer.massUnwrap;
      /* Returns meter */
      get meter() {
        return this._meter;
      }
      /**
       * Sets MeterProvider to this plugin
       * @param meterProvider
       */
      setMeterProvider(meterProvider) {
        this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion);
        this._updateMetricInstruments();
      }
      /* Returns logger */
      get logger() {
        return this._logger;
      }
      /**
       * Sets LoggerProvider to this plugin
       * @param loggerProvider
       */
      setLoggerProvider(loggerProvider) {
        this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion);
      }
      /**
       * @experimental
       *
       * Get module definitions defined by {@link init}.
       * This can be used for experimental compile-time instrumentation.
       *
       * @returns an array of {@link InstrumentationModuleDefinition}
       */
      getModuleDefinitions() {
        const initResult = this.init() ?? [];
        if (!Array.isArray(initResult)) {
          return [initResult];
        }
        return initResult;
      }
      /**
       * Sets the new metric instruments with the current Meter.
       */
      _updateMetricInstruments() {
        return;
      }
      /* Returns InstrumentationConfig */
      getConfig() {
        return this._config;
      }
      /**
       * Sets InstrumentationConfig to this plugin
       * @param config
       */
      setConfig(config) {
        this._config = {
          enabled: true,
          ...config
        };
      }
      /**
       * Sets TraceProvider to this plugin
       * @param tracerProvider
       */
      setTracerProvider(tracerProvider) {
        this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
      }
      /* Returns tracer */
      get tracer() {
        return this._tracer;
      }
      /**
       * Execute span customization hook, if configured, and log any errors.
       * Any semantics of the trigger and info are defined by the specific instrumentation.
       * @param hookHandler The optional hook handler which the user has configured via instrumentation config
       * @param triggerName The name of the trigger for executing the hook for logging purposes
       * @param span The span to which the hook should be applied
       * @param info The info object to be passed to the hook, with useful data the hook may use
       */
      _runSpanCustomizationHook(hookHandler, triggerName, span, info) {
        if (!hookHandler) {
          return;
        }
        try {
          hookHandler(span, info);
        } catch (e) {
          this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e);
        }
      }
    };
    exports.InstrumentationAbstract = InstrumentationAbstract;
  }
});

// node_modules/module-details-from-path/index.js
var require_module_details_from_path = __commonJS({
  "node_modules/module-details-from-path/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var sep = __require("path").sep;
    module.exports = function(file) {
      var segments = file.split(sep);
      var index = segments.lastIndexOf("node_modules");
      if (index === -1) return;
      if (!segments[index + 1]) return;
      var scoped = segments[index + 1][0] === "@";
      var name = scoped ? segments[index + 1] + "/" + segments[index + 2] : segments[index + 1];
      var offset = scoped ? 3 : 2;
      var basedir = "";
      var lastBaseDirSegmentIndex = index + offset - 1;
      for (var i = 0; i <= lastBaseDirSegmentIndex; i++) {
        if (i === lastBaseDirSegmentIndex) {
          basedir += segments[i];
        } else {
          basedir += segments[i] + sep;
        }
      }
      var path11 = "";
      var lastSegmentIndex = segments.length - 1;
      for (var i2 = index + offset; i2 <= lastSegmentIndex; i2++) {
        if (i2 === lastSegmentIndex) {
          path11 += segments[i2];
        } else {
          path11 += segments[i2] + sep;
        }
      }
      return {
        name,
        basedir,
        path: path11
      };
    };
  }
});

// node_modules/resolve/lib/homedir.js
var require_homedir = __commonJS({
  "node_modules/resolve/lib/homedir.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var os4 = __require("os");
    module.exports = os4.homedir || /* @__PURE__ */ __name(function homedir3() {
      var home = process.env.HOME;
      var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
      if (process.platform === "win32") {
        return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;
      }
      if (process.platform === "darwin") {
        return home || (user ? "/Users/" + user : null);
      }
      if (process.platform === "linux") {
        return home || (process.getuid() === 0 ? "/root" : user ? "/home/" + user : null);
      }
      return home || null;
    }, "homedir");
  }
});

// node_modules/resolve/lib/caller.js
var require_caller = __commonJS({
  "node_modules/resolve/lib/caller.js"(exports, module) {
    init_esbuild_shims();
    module.exports = function() {
      var origPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = function(_, stack2) {
        return stack2;
      };
      var stack = new Error().stack;
      Error.prepareStackTrace = origPrepareStackTrace;
      return stack[2].getFileName();
    };
  }
});

// node_modules/path-parse/index.js
var require_path_parse = __commonJS({
  "node_modules/path-parse/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var isWindows = process.platform === "win32";
    var splitWindowsRe = /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
    var win32 = {};
    function win32SplitPath(filename) {
      return splitWindowsRe.exec(filename).slice(1);
    }
    __name(win32SplitPath, "win32SplitPath");
    win32.parse = function(pathString) {
      if (typeof pathString !== "string") {
        throw new TypeError(
          "Parameter 'pathString' must be a string, not " + typeof pathString
        );
      }
      var allParts = win32SplitPath(pathString);
      if (!allParts || allParts.length !== 5) {
        throw new TypeError("Invalid path '" + pathString + "'");
      }
      return {
        root: allParts[1],
        dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
        base: allParts[2],
        ext: allParts[4],
        name: allParts[3]
      };
    };
    var splitPathRe = /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
    var posix = {};
    function posixSplitPath(filename) {
      return splitPathRe.exec(filename).slice(1);
    }
    __name(posixSplitPath, "posixSplitPath");
    posix.parse = function(pathString) {
      if (typeof pathString !== "string") {
        throw new TypeError(
          "Parameter 'pathString' must be a string, not " + typeof pathString
        );
      }
      var allParts = posixSplitPath(pathString);
      if (!allParts || allParts.length !== 5) {
        throw new TypeError("Invalid path '" + pathString + "'");
      }
      return {
        root: allParts[1],
        dir: allParts[0].slice(0, -1),
        base: allParts[2],
        ext: allParts[4],
        name: allParts[3]
      };
    };
    if (isWindows)
      module.exports = win32.parse;
    else
      module.exports = posix.parse;
    module.exports.posix = posix.parse;
    module.exports.win32 = win32.parse;
  }
});

// node_modules/resolve/lib/node-modules-paths.js
var require_node_modules_paths = __commonJS({
  "node_modules/resolve/lib/node-modules-paths.js"(exports, module) {
    init_esbuild_shims();
    var path11 = __require("path");
    var parse = path11.parse || require_path_parse();
    var getNodeModulesDirs = /* @__PURE__ */ __name(function getNodeModulesDirs2(absoluteStart, modules) {
      var prefix = "/";
      if (/^([A-Za-z]:)/.test(absoluteStart)) {
        prefix = "";
      } else if (/^\\\\/.test(absoluteStart)) {
        prefix = "\\\\";
      }
      var paths = [absoluteStart];
      var parsed = parse(absoluteStart);
      while (parsed.dir !== paths[paths.length - 1]) {
        paths.push(parsed.dir);
        parsed = parse(parsed.dir);
      }
      return paths.reduce(function(dirs, aPath) {
        return dirs.concat(modules.map(function(moduleDir) {
          return path11.resolve(prefix, aPath, moduleDir);
        }));
      }, []);
    }, "getNodeModulesDirs");
    module.exports = /* @__PURE__ */ __name(function nodeModulesPaths(start, opts, request4) {
      var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ["node_modules"];
      if (opts && typeof opts.paths === "function") {
        return opts.paths(
          request4,
          start,
          function() {
            return getNodeModulesDirs(start, modules);
          },
          opts
        );
      }
      var dirs = getNodeModulesDirs(start, modules);
      return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
    }, "nodeModulesPaths");
  }
});

// node_modules/resolve/lib/normalize-options.js
var require_normalize_options = __commonJS({
  "node_modules/resolve/lib/normalize-options.js"(exports, module) {
    init_esbuild_shims();
    module.exports = function(x, opts) {
      return opts || {};
    };
  }
});

// node_modules/is-core-module/core.json
var require_core = __commonJS({
  "node_modules/is-core-module/core.json"(exports, module) {
    module.exports = {
      assert: true,
      "node:assert": [">= 14.18 && < 15", ">= 16"],
      "assert/strict": ">= 15",
      "node:assert/strict": ">= 16",
      async_hooks: ">= 8",
      "node:async_hooks": [">= 14.18 && < 15", ">= 16"],
      buffer_ieee754: ">= 0.5 && < 0.9.7",
      buffer: true,
      "node:buffer": [">= 14.18 && < 15", ">= 16"],
      child_process: true,
      "node:child_process": [">= 14.18 && < 15", ">= 16"],
      cluster: ">= 0.5",
      "node:cluster": [">= 14.18 && < 15", ">= 16"],
      console: true,
      "node:console": [">= 14.18 && < 15", ">= 16"],
      constants: true,
      "node:constants": [">= 14.18 && < 15", ">= 16"],
      crypto: true,
      "node:crypto": [">= 14.18 && < 15", ">= 16"],
      _debug_agent: ">= 1 && < 8",
      _debugger: "< 8",
      dgram: true,
      "node:dgram": [">= 14.18 && < 15", ">= 16"],
      diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
      "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
      dns: true,
      "node:dns": [">= 14.18 && < 15", ">= 16"],
      "dns/promises": ">= 15",
      "node:dns/promises": ">= 16",
      domain: ">= 0.7.12",
      "node:domain": [">= 14.18 && < 15", ">= 16"],
      events: true,
      "node:events": [">= 14.18 && < 15", ">= 16"],
      freelist: "< 6",
      fs: true,
      "node:fs": [">= 14.18 && < 15", ">= 16"],
      "fs/promises": [">= 10 && < 10.1", ">= 14"],
      "node:fs/promises": [">= 14.18 && < 15", ">= 16"],
      _http_agent: ">= 0.11.1",
      "node:_http_agent": [">= 14.18 && < 15", ">= 16"],
      _http_client: ">= 0.11.1",
      "node:_http_client": [">= 14.18 && < 15", ">= 16"],
      _http_common: ">= 0.11.1",
      "node:_http_common": [">= 14.18 && < 15", ">= 16"],
      _http_incoming: ">= 0.11.1",
      "node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
      _http_outgoing: ">= 0.11.1",
      "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
      _http_server: ">= 0.11.1",
      "node:_http_server": [">= 14.18 && < 15", ">= 16"],
      http: true,
      "node:http": [">= 14.18 && < 15", ">= 16"],
      http2: ">= 8.8",
      "node:http2": [">= 14.18 && < 15", ">= 16"],
      https: true,
      "node:https": [">= 14.18 && < 15", ">= 16"],
      inspector: ">= 8",
      "node:inspector": [">= 14.18 && < 15", ">= 16"],
      "inspector/promises": [">= 19"],
      "node:inspector/promises": [">= 19"],
      _linklist: "< 8",
      module: true,
      "node:module": [">= 14.18 && < 15", ">= 16"],
      net: true,
      "node:net": [">= 14.18 && < 15", ">= 16"],
      "node-inspect/lib/_inspect": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
      os: true,
      "node:os": [">= 14.18 && < 15", ">= 16"],
      path: true,
      "node:path": [">= 14.18 && < 15", ">= 16"],
      "path/posix": ">= 15.3",
      "node:path/posix": ">= 16",
      "path/win32": ">= 15.3",
      "node:path/win32": ">= 16",
      perf_hooks: ">= 8.5",
      "node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
      process: ">= 1",
      "node:process": [">= 14.18 && < 15", ">= 16"],
      punycode: ">= 0.5",
      "node:punycode": [">= 14.18 && < 15", ">= 16"],
      querystring: true,
      "node:querystring": [">= 14.18 && < 15", ">= 16"],
      readline: true,
      "node:readline": [">= 14.18 && < 15", ">= 16"],
      "readline/promises": ">= 17",
      "node:readline/promises": ">= 17",
      repl: true,
      "node:repl": [">= 14.18 && < 15", ">= 16"],
      "node:sea": [">= 20.12 && < 21", ">= 21.7"],
      smalloc: ">= 0.11.5 && < 3",
      "node:sqlite": [">= 22.13 && < 23", ">= 23.4"],
      _stream_duplex: ">= 0.9.4",
      "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
      _stream_transform: ">= 0.9.4",
      "node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
      _stream_wrap: ">= 1.4.1",
      "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
      _stream_passthrough: ">= 0.9.4",
      "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
      _stream_readable: ">= 0.9.4",
      "node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
      _stream_writable: ">= 0.9.4",
      "node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
      stream: true,
      "node:stream": [">= 14.18 && < 15", ">= 16"],
      "stream/consumers": ">= 16.7",
      "node:stream/consumers": ">= 16.7",
      "stream/promises": ">= 15",
      "node:stream/promises": ">= 16",
      "stream/web": ">= 16.5",
      "node:stream/web": ">= 16.5",
      string_decoder: true,
      "node:string_decoder": [">= 14.18 && < 15", ">= 16"],
      sys: [">= 0.4 && < 0.7", ">= 0.8"],
      "node:sys": [">= 14.18 && < 15", ">= 16"],
      "test/reporters": ">= 19.9 && < 20.2",
      "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
      "test/mock_loader": ">= 22.3 && < 22.7",
      "node:test/mock_loader": ">= 22.3 && < 22.7",
      "node:test": [">= 16.17 && < 17", ">= 18"],
      timers: true,
      "node:timers": [">= 14.18 && < 15", ">= 16"],
      "timers/promises": ">= 15",
      "node:timers/promises": ">= 16",
      _tls_common: ">= 0.11.13",
      "node:_tls_common": [">= 14.18 && < 15", ">= 16"],
      _tls_legacy: ">= 0.11.3 && < 10",
      _tls_wrap: ">= 0.11.3",
      "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
      tls: true,
      "node:tls": [">= 14.18 && < 15", ">= 16"],
      trace_events: ">= 10",
      "node:trace_events": [">= 14.18 && < 15", ">= 16"],
      tty: true,
      "node:tty": [">= 14.18 && < 15", ">= 16"],
      url: true,
      "node:url": [">= 14.18 && < 15", ">= 16"],
      util: true,
      "node:util": [">= 14.18 && < 15", ">= 16"],
      "util/types": ">= 15.3",
      "node:util/types": ">= 16",
      "v8/tools/arguments": ">= 10 && < 12",
      "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      v8: ">= 1",
      "node:v8": [">= 14.18 && < 15", ">= 16"],
      vm: true,
      "node:vm": [">= 14.18 && < 15", ">= 16"],
      wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
      "node:wasi": [">= 18.17 && < 19", ">= 20"],
      worker_threads: ">= 11.7",
      "node:worker_threads": [">= 14.18 && < 15", ">= 16"],
      zlib: ">= 0.5",
      "node:zlib": [">= 14.18 && < 15", ">= 16"]
    };
  }
});

// node_modules/is-core-module/index.js
var require_is_core_module = __commonJS({
  "node_modules/is-core-module/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var hasOwn = require_hasown();
    function specifierIncluded(current, specifier) {
      var nodeParts = current.split(".");
      var parts = specifier.split(" ");
      var op = parts.length > 1 ? parts[0] : "=";
      var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split(".");
      for (var i = 0; i < 3; ++i) {
        var cur = parseInt(nodeParts[i] || 0, 10);
        var ver = parseInt(versionParts[i] || 0, 10);
        if (cur === ver) {
          continue;
        }
        if (op === "<") {
          return cur < ver;
        }
        if (op === ">=") {
          return cur >= ver;
        }
        return false;
      }
      return op === ">=";
    }
    __name(specifierIncluded, "specifierIncluded");
    function matchesRange(current, range) {
      var specifiers = range.split(/ ?&& ?/);
      if (specifiers.length === 0) {
        return false;
      }
      for (var i = 0; i < specifiers.length; ++i) {
        if (!specifierIncluded(current, specifiers[i])) {
          return false;
        }
      }
      return true;
    }
    __name(matchesRange, "matchesRange");
    function versionIncluded(nodeVersion, specifierValue) {
      if (typeof specifierValue === "boolean") {
        return specifierValue;
      }
      var current = typeof nodeVersion === "undefined" ? process.versions && process.versions.node : nodeVersion;
      if (typeof current !== "string") {
        throw new TypeError(typeof nodeVersion === "undefined" ? "Unable to determine current node version" : "If provided, a valid node version is required");
      }
      if (specifierValue && typeof specifierValue === "object") {
        for (var i = 0; i < specifierValue.length; ++i) {
          if (matchesRange(current, specifierValue[i])) {
            return true;
          }
        }
        return false;
      }
      return matchesRange(current, specifierValue);
    }
    __name(versionIncluded, "versionIncluded");
    var data = require_core();
    module.exports = /* @__PURE__ */ __name(function isCore(x, nodeVersion) {
      return hasOwn(data, x) && versionIncluded(nodeVersion, data[x]);
    }, "isCore");
  }
});

// node_modules/resolve/lib/async.js
var require_async = __commonJS({
  "node_modules/resolve/lib/async.js"(exports, module) {
    init_esbuild_shims();
    var fs9 = __require("fs");
    var getHomedir = require_homedir();
    var path11 = __require("path");
    var caller = require_caller();
    var nodeModulesPaths = require_node_modules_paths();
    var normalizeOptions = require_normalize_options();
    var isCore = require_is_core_module();
    var realpathFS = process.platform !== "win32" && fs9.realpath && typeof fs9.realpath.native === "function" ? fs9.realpath.native : fs9.realpath;
    var homedir3 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path11.join(homedir3, ".node_modules"),
        path11.join(homedir3, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile(file, cb) {
      fs9.stat(file, function(err, stat) {
        if (!err) {
          return cb(null, stat.isFile() || stat.isFIFO());
        }
        if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
        return cb(err);
      });
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir, cb) {
      fs9.stat(dir, function(err, stat) {
        if (!err) {
          return cb(null, stat.isDirectory());
        }
        if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false);
        return cb(err);
      });
    }, "isDirectory");
    var defaultRealpath = /* @__PURE__ */ __name(function realpath(x, cb) {
      realpathFS(x, function(realpathErr, realPath) {
        if (realpathErr && realpathErr.code !== "ENOENT") cb(realpathErr);
        else cb(null, realpathErr ? x : realPath);
      });
    }, "realpath");
    var maybeRealpath = /* @__PURE__ */ __name(function maybeRealpath2(realpath, x, opts, cb) {
      if (opts && opts.preserveSymlinks === false) {
        realpath(x, cb);
      } else {
        cb(null, x);
      }
    }, "maybeRealpath");
    var defaultReadPackage = /* @__PURE__ */ __name(function defaultReadPackage2(readFile, pkgfile, cb) {
      readFile(pkgfile, function(readFileErr, body) {
        if (readFileErr) cb(readFileErr);
        else {
          try {
            var pkg = JSON.parse(body);
            cb(null, pkg);
          } catch (jsonErr) {
            cb(null);
          }
        }
      });
    }, "defaultReadPackage");
    var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x, start, opts) {
      var dirs = nodeModulesPaths(start, opts, x);
      for (var i = 0; i < dirs.length; i++) {
        dirs[i] = path11.join(dirs[i], x);
      }
      return dirs;
    }, "getPackageCandidates");
    module.exports = /* @__PURE__ */ __name(function resolve2(x, options, callback) {
      var cb = callback;
      var opts = options;
      if (typeof options === "function") {
        cb = opts;
        opts = {};
      }
      if (typeof x !== "string") {
        var err = new TypeError("Path must be a string.");
        return process.nextTick(function() {
          cb(err);
        });
      }
      opts = normalizeOptions(x, opts);
      var isFile = opts.isFile || defaultIsFile;
      var isDirectory = opts.isDirectory || defaultIsDir;
      var readFile = opts.readFile || fs9.readFile;
      var realpath = opts.realpath || defaultRealpath;
      var readPackage = opts.readPackage || defaultReadPackage;
      if (opts.readFile && opts.readPackage) {
        var conflictErr = new TypeError("`readFile` and `readPackage` are mutually exclusive.");
        return process.nextTick(function() {
          cb(conflictErr);
        });
      }
      var packageIterator = opts.packageIterator;
      var extensions = opts.extensions || [".js"];
      var includeCoreModules = opts.includeCoreModules !== false;
      var basedir = opts.basedir || path11.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = path11.resolve(basedir);
      maybeRealpath(
        realpath,
        absoluteStart,
        opts,
        function(err2, realStart) {
          if (err2) cb(err2);
          else init(realStart);
        }
      );
      var res;
      function init(basedir2) {
        if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
          res = path11.resolve(basedir2, x);
          if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
          if (/\/$/.test(x) && res === basedir2) {
            loadAsDirectory(res, opts.package, onfile);
          } else loadAsFile(res, opts.package, onfile);
        } else if (includeCoreModules && isCore(x)) {
          return cb(null, x);
        } else loadNodeModules(x, basedir2, function(err2, n, pkg) {
          if (err2) cb(err2);
          else if (n) {
            return maybeRealpath(realpath, n, opts, function(err3, realN) {
              if (err3) {
                cb(err3);
              } else {
                cb(null, realN, pkg);
              }
            });
          } else {
            var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
            moduleError.code = "MODULE_NOT_FOUND";
            cb(moduleError);
          }
        });
      }
      __name(init, "init");
      function onfile(err2, m, pkg) {
        if (err2) cb(err2);
        else if (m) cb(null, m, pkg);
        else loadAsDirectory(res, function(err3, d, pkg2) {
          if (err3) cb(err3);
          else if (d) {
            maybeRealpath(realpath, d, opts, function(err4, realD) {
              if (err4) {
                cb(err4);
              } else {
                cb(null, realD, pkg2);
              }
            });
          } else {
            var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
            moduleError.code = "MODULE_NOT_FOUND";
            cb(moduleError);
          }
        });
      }
      __name(onfile, "onfile");
      function loadAsFile(x2, thePackage, callback2) {
        var loadAsFilePackage = thePackage;
        var cb2 = callback2;
        if (typeof loadAsFilePackage === "function") {
          cb2 = loadAsFilePackage;
          loadAsFilePackage = void 0;
        }
        var exts = [""].concat(extensions);
        load(exts, x2, loadAsFilePackage);
        function load(exts2, x3, loadPackage) {
          if (exts2.length === 0) return cb2(null, void 0, loadPackage);
          var file = x3 + exts2[0];
          var pkg = loadPackage;
          if (pkg) onpkg(null, pkg);
          else loadpkg(path11.dirname(file), onpkg);
          function onpkg(err2, pkg_, dir) {
            pkg = pkg_;
            if (err2) return cb2(err2);
            if (dir && pkg && opts.pathFilter) {
              var rfile = path11.relative(dir, file);
              var rel = rfile.slice(0, rfile.length - exts2[0].length);
              var r = opts.pathFilter(pkg, x3, rel);
              if (r) return load(
                [""].concat(extensions.slice()),
                path11.resolve(dir, r),
                pkg
              );
            }
            isFile(file, onex);
          }
          __name(onpkg, "onpkg");
          function onex(err2, ex) {
            if (err2) return cb2(err2);
            if (ex) return cb2(null, file, pkg);
            load(exts2.slice(1), x3, pkg);
          }
          __name(onex, "onex");
        }
        __name(load, "load");
      }
      __name(loadAsFile, "loadAsFile");
      function loadpkg(dir, cb2) {
        if (dir === "" || dir === "/") return cb2(null);
        if (process.platform === "win32" && /^\w:[/\\]*$/.test(dir)) {
          return cb2(null);
        }
        if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb2(null);
        maybeRealpath(realpath, dir, opts, function(unwrapErr, pkgdir) {
          if (unwrapErr) return loadpkg(path11.dirname(dir), cb2);
          var pkgfile = path11.join(pkgdir, "package.json");
          isFile(pkgfile, function(err2, ex) {
            if (!ex) return loadpkg(path11.dirname(dir), cb2);
            readPackage(readFile, pkgfile, function(err3, pkgParam) {
              if (err3) cb2(err3);
              var pkg = pkgParam;
              if (pkg && opts.packageFilter) {
                pkg = opts.packageFilter(pkg, pkgfile);
              }
              cb2(null, pkg, dir);
            });
          });
        });
      }
      __name(loadpkg, "loadpkg");
      function loadAsDirectory(x2, loadAsDirectoryPackage, callback2) {
        var cb2 = callback2;
        var fpkg = loadAsDirectoryPackage;
        if (typeof fpkg === "function") {
          cb2 = fpkg;
          fpkg = opts.package;
        }
        maybeRealpath(realpath, x2, opts, function(unwrapErr, pkgdir) {
          if (unwrapErr) return cb2(unwrapErr);
          var pkgfile = path11.join(pkgdir, "package.json");
          isFile(pkgfile, function(err2, ex) {
            if (err2) return cb2(err2);
            if (!ex) return loadAsFile(path11.join(x2, "index"), fpkg, cb2);
            readPackage(readFile, pkgfile, function(err3, pkgParam) {
              if (err3) return cb2(err3);
              var pkg = pkgParam;
              if (pkg && opts.packageFilter) {
                pkg = opts.packageFilter(pkg, pkgfile);
              }
              if (pkg && pkg.main) {
                if (typeof pkg.main !== "string") {
                  var mainError = new TypeError("package \u201C" + pkg.name + "\u201D `main` must be a string");
                  mainError.code = "INVALID_PACKAGE_MAIN";
                  return cb2(mainError);
                }
                if (pkg.main === "." || pkg.main === "./") {
                  pkg.main = "index";
                }
                loadAsFile(path11.resolve(x2, pkg.main), pkg, function(err4, m, pkg2) {
                  if (err4) return cb2(err4);
                  if (m) return cb2(null, m, pkg2);
                  if (!pkg2) return loadAsFile(path11.join(x2, "index"), pkg2, cb2);
                  var dir = path11.resolve(x2, pkg2.main);
                  loadAsDirectory(dir, pkg2, function(err5, n, pkg3) {
                    if (err5) return cb2(err5);
                    if (n) return cb2(null, n, pkg3);
                    loadAsFile(path11.join(x2, "index"), pkg3, cb2);
                  });
                });
                return;
              }
              loadAsFile(path11.join(x2, "/index"), pkg, cb2);
            });
          });
        });
      }
      __name(loadAsDirectory, "loadAsDirectory");
      function processDirs(cb2, dirs) {
        if (dirs.length === 0) return cb2(null, void 0);
        var dir = dirs[0];
        isDirectory(path11.dirname(dir), isdir);
        function isdir(err2, isdir2) {
          if (err2) return cb2(err2);
          if (!isdir2) return processDirs(cb2, dirs.slice(1));
          loadAsFile(dir, opts.package, onfile2);
        }
        __name(isdir, "isdir");
        function onfile2(err2, m, pkg) {
          if (err2) return cb2(err2);
          if (m) return cb2(null, m, pkg);
          loadAsDirectory(dir, opts.package, ondir);
        }
        __name(onfile2, "onfile");
        function ondir(err2, n, pkg) {
          if (err2) return cb2(err2);
          if (n) return cb2(null, n, pkg);
          processDirs(cb2, dirs.slice(1));
        }
        __name(ondir, "ondir");
      }
      __name(processDirs, "processDirs");
      function loadNodeModules(x2, start, cb2) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x2, start, opts);
        }, "thunk");
        processDirs(
          cb2,
          packageIterator ? packageIterator(x2, start, thunk, opts) : thunk()
        );
      }
      __name(loadNodeModules, "loadNodeModules");
    }, "resolve");
  }
});

// node_modules/resolve/lib/core.json
var require_core2 = __commonJS({
  "node_modules/resolve/lib/core.json"(exports, module) {
    module.exports = {
      assert: true,
      "node:assert": [">= 14.18 && < 15", ">= 16"],
      "assert/strict": ">= 15",
      "node:assert/strict": ">= 16",
      async_hooks: ">= 8",
      "node:async_hooks": [">= 14.18 && < 15", ">= 16"],
      buffer_ieee754: ">= 0.5 && < 0.9.7",
      buffer: true,
      "node:buffer": [">= 14.18 && < 15", ">= 16"],
      child_process: true,
      "node:child_process": [">= 14.18 && < 15", ">= 16"],
      cluster: ">= 0.5",
      "node:cluster": [">= 14.18 && < 15", ">= 16"],
      console: true,
      "node:console": [">= 14.18 && < 15", ">= 16"],
      constants: true,
      "node:constants": [">= 14.18 && < 15", ">= 16"],
      crypto: true,
      "node:crypto": [">= 14.18 && < 15", ">= 16"],
      _debug_agent: ">= 1 && < 8",
      _debugger: "< 8",
      dgram: true,
      "node:dgram": [">= 14.18 && < 15", ">= 16"],
      diagnostics_channel: [">= 14.17 && < 15", ">= 15.1"],
      "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"],
      dns: true,
      "node:dns": [">= 14.18 && < 15", ">= 16"],
      "dns/promises": ">= 15",
      "node:dns/promises": ">= 16",
      domain: ">= 0.7.12",
      "node:domain": [">= 14.18 && < 15", ">= 16"],
      events: true,
      "node:events": [">= 14.18 && < 15", ">= 16"],
      freelist: "< 6",
      fs: true,
      "node:fs": [">= 14.18 && < 15", ">= 16"],
      "fs/promises": [">= 10 && < 10.1", ">= 14"],
      "node:fs/promises": [">= 14.18 && < 15", ">= 16"],
      _http_agent: ">= 0.11.1",
      "node:_http_agent": [">= 14.18 && < 15", ">= 16"],
      _http_client: ">= 0.11.1",
      "node:_http_client": [">= 14.18 && < 15", ">= 16"],
      _http_common: ">= 0.11.1",
      "node:_http_common": [">= 14.18 && < 15", ">= 16"],
      _http_incoming: ">= 0.11.1",
      "node:_http_incoming": [">= 14.18 && < 15", ">= 16"],
      _http_outgoing: ">= 0.11.1",
      "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"],
      _http_server: ">= 0.11.1",
      "node:_http_server": [">= 14.18 && < 15", ">= 16"],
      http: true,
      "node:http": [">= 14.18 && < 15", ">= 16"],
      http2: ">= 8.8",
      "node:http2": [">= 14.18 && < 15", ">= 16"],
      https: true,
      "node:https": [">= 14.18 && < 15", ">= 16"],
      inspector: ">= 8",
      "node:inspector": [">= 14.18 && < 15", ">= 16"],
      "inspector/promises": [">= 19"],
      "node:inspector/promises": [">= 19"],
      _linklist: "< 8",
      module: true,
      "node:module": [">= 14.18 && < 15", ">= 16"],
      net: true,
      "node:net": [">= 14.18 && < 15", ">= 16"],
      "node-inspect/lib/_inspect": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
      "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
      os: true,
      "node:os": [">= 14.18 && < 15", ">= 16"],
      path: true,
      "node:path": [">= 14.18 && < 15", ">= 16"],
      "path/posix": ">= 15.3",
      "node:path/posix": ">= 16",
      "path/win32": ">= 15.3",
      "node:path/win32": ">= 16",
      perf_hooks: ">= 8.5",
      "node:perf_hooks": [">= 14.18 && < 15", ">= 16"],
      process: ">= 1",
      "node:process": [">= 14.18 && < 15", ">= 16"],
      punycode: ">= 0.5",
      "node:punycode": [">= 14.18 && < 15", ">= 16"],
      querystring: true,
      "node:querystring": [">= 14.18 && < 15", ">= 16"],
      readline: true,
      "node:readline": [">= 14.18 && < 15", ">= 16"],
      "readline/promises": ">= 17",
      "node:readline/promises": ">= 17",
      repl: true,
      "node:repl": [">= 14.18 && < 15", ">= 16"],
      "node:sea": [">= 20.12 && < 21", ">= 21.7"],
      smalloc: ">= 0.11.5 && < 3",
      "node:sqlite": ">= 23.4",
      _stream_duplex: ">= 0.9.4",
      "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"],
      _stream_transform: ">= 0.9.4",
      "node:_stream_transform": [">= 14.18 && < 15", ">= 16"],
      _stream_wrap: ">= 1.4.1",
      "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"],
      _stream_passthrough: ">= 0.9.4",
      "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"],
      _stream_readable: ">= 0.9.4",
      "node:_stream_readable": [">= 14.18 && < 15", ">= 16"],
      _stream_writable: ">= 0.9.4",
      "node:_stream_writable": [">= 14.18 && < 15", ">= 16"],
      stream: true,
      "node:stream": [">= 14.18 && < 15", ">= 16"],
      "stream/consumers": ">= 16.7",
      "node:stream/consumers": ">= 16.7",
      "stream/promises": ">= 15",
      "node:stream/promises": ">= 16",
      "stream/web": ">= 16.5",
      "node:stream/web": ">= 16.5",
      string_decoder: true,
      "node:string_decoder": [">= 14.18 && < 15", ">= 16"],
      sys: [">= 0.4 && < 0.7", ">= 0.8"],
      "node:sys": [">= 14.18 && < 15", ">= 16"],
      "test/reporters": ">= 19.9 && < 20.2",
      "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"],
      "test/mock_loader": ">= 22.3 && < 22.7",
      "node:test/mock_loader": ">= 22.3 && < 22.7",
      "node:test": [">= 16.17 && < 17", ">= 18"],
      timers: true,
      "node:timers": [">= 14.18 && < 15", ">= 16"],
      "timers/promises": ">= 15",
      "node:timers/promises": ">= 16",
      _tls_common: ">= 0.11.13",
      "node:_tls_common": [">= 14.18 && < 15", ">= 16"],
      _tls_legacy: ">= 0.11.3 && < 10",
      _tls_wrap: ">= 0.11.3",
      "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"],
      tls: true,
      "node:tls": [">= 14.18 && < 15", ">= 16"],
      trace_events: ">= 10",
      "node:trace_events": [">= 14.18 && < 15", ">= 16"],
      tty: true,
      "node:tty": [">= 14.18 && < 15", ">= 16"],
      url: true,
      "node:url": [">= 14.18 && < 15", ">= 16"],
      util: true,
      "node:util": [">= 14.18 && < 15", ">= 16"],
      "util/types": ">= 15.3",
      "node:util/types": ">= 16",
      "v8/tools/arguments": ">= 10 && < 12",
      "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"],
      v8: ">= 1",
      "node:v8": [">= 14.18 && < 15", ">= 16"],
      vm: true,
      "node:vm": [">= 14.18 && < 15", ">= 16"],
      wasi: [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"],
      "node:wasi": [">= 18.17 && < 19", ">= 20"],
      worker_threads: ">= 11.7",
      "node:worker_threads": [">= 14.18 && < 15", ">= 16"],
      zlib: ">= 0.5",
      "node:zlib": [">= 14.18 && < 15", ">= 16"]
    };
  }
});

// node_modules/resolve/lib/core.js
var require_core3 = __commonJS({
  "node_modules/resolve/lib/core.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var isCoreModule = require_is_core_module();
    var data = require_core2();
    var core = {};
    for (mod in data) {
      if (Object.prototype.hasOwnProperty.call(data, mod)) {
        core[mod] = isCoreModule(mod);
      }
    }
    var mod;
    module.exports = core;
  }
});

// node_modules/resolve/lib/is-core.js
var require_is_core = __commonJS({
  "node_modules/resolve/lib/is-core.js"(exports, module) {
    init_esbuild_shims();
    var isCoreModule = require_is_core_module();
    module.exports = /* @__PURE__ */ __name(function isCore(x) {
      return isCoreModule(x);
    }, "isCore");
  }
});

// node_modules/resolve/lib/sync.js
var require_sync = __commonJS({
  "node_modules/resolve/lib/sync.js"(exports, module) {
    init_esbuild_shims();
    var isCore = require_is_core_module();
    var fs9 = __require("fs");
    var path11 = __require("path");
    var getHomedir = require_homedir();
    var caller = require_caller();
    var nodeModulesPaths = require_node_modules_paths();
    var normalizeOptions = require_normalize_options();
    var realpathFS = process.platform !== "win32" && fs9.realpathSync && typeof fs9.realpathSync.native === "function" ? fs9.realpathSync.native : fs9.realpathSync;
    var homedir3 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path11.join(homedir3, ".node_modules"),
        path11.join(homedir3, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile(file) {
      try {
        var stat = fs9.statSync(file, { throwIfNoEntry: false });
      } catch (e) {
        if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false;
        throw e;
      }
      return !!stat && (stat.isFile() || stat.isFIFO());
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir) {
      try {
        var stat = fs9.statSync(dir, { throwIfNoEntry: false });
      } catch (e) {
        if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false;
        throw e;
      }
      return !!stat && stat.isDirectory();
    }, "isDirectory");
    var defaultRealpathSync = /* @__PURE__ */ __name(function realpathSync(x) {
      try {
        return realpathFS(x);
      } catch (realpathErr) {
        if (realpathErr.code !== "ENOENT") {
          throw realpathErr;
        }
      }
      return x;
    }, "realpathSync");
    var maybeRealpathSync = /* @__PURE__ */ __name(function maybeRealpathSync2(realpathSync, x, opts) {
      if (opts && opts.preserveSymlinks === false) {
        return realpathSync(x);
      }
      return x;
    }, "maybeRealpathSync");
    var defaultReadPackageSync = /* @__PURE__ */ __name(function defaultReadPackageSync2(readFileSync, pkgfile) {
      var body = readFileSync(pkgfile);
      try {
        var pkg = JSON.parse(body);
        return pkg;
      } catch (jsonErr) {
      }
    }, "defaultReadPackageSync");
    var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x, start, opts) {
      var dirs = nodeModulesPaths(start, opts, x);
      for (var i = 0; i < dirs.length; i++) {
        dirs[i] = path11.join(dirs[i], x);
      }
      return dirs;
    }, "getPackageCandidates");
    module.exports = /* @__PURE__ */ __name(function resolveSync(x, options) {
      if (typeof x !== "string") {
        throw new TypeError("Path must be a string.");
      }
      var opts = normalizeOptions(x, options);
      var isFile = opts.isFile || defaultIsFile;
      var readFileSync = opts.readFileSync || fs9.readFileSync;
      var isDirectory = opts.isDirectory || defaultIsDir;
      var realpathSync = opts.realpathSync || defaultRealpathSync;
      var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
      if (opts.readFileSync && opts.readPackageSync) {
        throw new TypeError("`readFileSync` and `readPackageSync` are mutually exclusive.");
      }
      var packageIterator = opts.packageIterator;
      var extensions = opts.extensions || [".js"];
      var includeCoreModules = opts.includeCoreModules !== false;
      var basedir = opts.basedir || path11.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = maybeRealpathSync(realpathSync, path11.resolve(basedir), opts);
      if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
        var res = path11.resolve(absoluteStart, x);
        if (x === "." || x === ".." || x.slice(-1) === "/") res += "/";
        var m = loadAsFileSync(res) || loadAsDirectorySync(res);
        if (m) return maybeRealpathSync(realpathSync, m, opts);
      } else if (includeCoreModules && isCore(x)) {
        return x;
      } else {
        var n = loadNodeModulesSync(x, absoluteStart);
        if (n) return maybeRealpathSync(realpathSync, n, opts);
      }
      var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
      err.code = "MODULE_NOT_FOUND";
      throw err;
      function loadAsFileSync(x2) {
        var pkg = loadpkg(path11.dirname(x2));
        if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
          var rfile = path11.relative(pkg.dir, x2);
          var r = opts.pathFilter(pkg.pkg, x2, rfile);
          if (r) {
            x2 = path11.resolve(pkg.dir, r);
          }
        }
        if (isFile(x2)) {
          return x2;
        }
        for (var i = 0; i < extensions.length; i++) {
          var file = x2 + extensions[i];
          if (isFile(file)) {
            return file;
          }
        }
      }
      __name(loadAsFileSync, "loadAsFileSync");
      function loadpkg(dir) {
        if (dir === "" || dir === "/") return;
        if (process.platform === "win32" && /^\w:[/\\]*$/.test(dir)) {
          return;
        }
        if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
        var pkgfile = path11.join(maybeRealpathSync(realpathSync, dir, opts), "package.json");
        if (!isFile(pkgfile)) {
          return loadpkg(path11.dirname(dir));
        }
        var pkg = readPackageSync(readFileSync, pkgfile);
        if (pkg && opts.packageFilter) {
          pkg = opts.packageFilter(
            pkg,
            /*pkgfile,*/
            dir
          );
        }
        return { pkg, dir };
      }
      __name(loadpkg, "loadpkg");
      function loadAsDirectorySync(x2) {
        var pkgfile = path11.join(maybeRealpathSync(realpathSync, x2, opts), "/package.json");
        if (isFile(pkgfile)) {
          try {
            var pkg = readPackageSync(readFileSync, pkgfile);
          } catch (e) {
          }
          if (pkg && opts.packageFilter) {
            pkg = opts.packageFilter(
              pkg,
              /*pkgfile,*/
              x2
            );
          }
          if (pkg && pkg.main) {
            if (typeof pkg.main !== "string") {
              var mainError = new TypeError("package \u201C" + pkg.name + "\u201D `main` must be a string");
              mainError.code = "INVALID_PACKAGE_MAIN";
              throw mainError;
            }
            if (pkg.main === "." || pkg.main === "./") {
              pkg.main = "index";
            }
            try {
              var m2 = loadAsFileSync(path11.resolve(x2, pkg.main));
              if (m2) return m2;
              var n2 = loadAsDirectorySync(path11.resolve(x2, pkg.main));
              if (n2) return n2;
            } catch (e) {
            }
          }
        }
        return loadAsFileSync(path11.join(x2, "/index"));
      }
      __name(loadAsDirectorySync, "loadAsDirectorySync");
      function loadNodeModulesSync(x2, start) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x2, start, opts);
        }, "thunk");
        var dirs = packageIterator ? packageIterator(x2, start, thunk, opts) : thunk();
        for (var i = 0; i < dirs.length; i++) {
          var dir = dirs[i];
          if (isDirectory(path11.dirname(dir))) {
            var m2 = loadAsFileSync(dir);
            if (m2) return m2;
            var n2 = loadAsDirectorySync(dir);
            if (n2) return n2;
          }
        }
      }
      __name(loadNodeModulesSync, "loadNodeModulesSync");
    }, "resolveSync");
  }
});

// node_modules/resolve/index.js
var require_resolve = __commonJS({
  "node_modules/resolve/index.js"(exports, module) {
    init_esbuild_shims();
    var async = require_async();
    async.core = require_core3();
    async.isCore = require_is_core();
    async.sync = require_sync();
    module.exports = async;
  }
});

// node_modules/require-in-the-middle/package.json
var require_package2 = __commonJS({
  "node_modules/require-in-the-middle/package.json"(exports, module) {
    module.exports = {
      name: "require-in-the-middle",
      version: "7.5.2",
      description: "Module to hook into the Node.js require function",
      main: "index.js",
      types: "types/index.d.ts",
      dependencies: {
        debug: "^4.3.5",
        "module-details-from-path": "^1.0.3",
        resolve: "^1.22.8"
      },
      devDependencies: {
        "@babel/core": "^7.9.0",
        "@babel/preset-env": "^7.9.5",
        "@babel/preset-typescript": "^7.9.0",
        "@babel/register": "^7.9.0",
        "ipp-printer": "^1.0.0",
        patterns: "^1.0.3",
        roundround: "^0.2.0",
        semver: "^6.3.0",
        standard: "^14.3.1",
        tape: "^4.11.0"
      },
      scripts: {
        test: "npm run test:lint && npm run test:tape && npm run test:babel",
        "test:lint": "standard",
        "test:tape": "tape test/*.js",
        "test:babel": "node test/babel/babel-register.js"
      },
      repository: {
        type: "git",
        url: "git+https://github.com/nodejs/require-in-the-middle.git"
      },
      keywords: [
        "require",
        "hook",
        "shim",
        "shimmer",
        "shimming",
        "patch",
        "monkey",
        "monkeypatch",
        "module",
        "load"
      ],
      files: [
        "types"
      ],
      author: "Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)",
      license: "MIT",
      bugs: {
        url: "https://github.com/nodejs/require-in-the-middle/issues"
      },
      homepage: "https://github.com/nodejs/require-in-the-middle#readme",
      engines: {
        node: ">=8.6.0"
      }
    };
  }
});

// node_modules/require-in-the-middle/index.js
var require_require_in_the_middle = __commonJS({
  "node_modules/require-in-the-middle/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var path11 = __require("path");
    var Module = __require("module");
    var debug = require_src()("require-in-the-middle");
    var moduleDetailsFromPath = require_module_details_from_path();
    module.exports = Hook;
    module.exports.Hook = Hook;
    var builtinModules;
    var isCore;
    if (Module.isBuiltin) {
      isCore = Module.isBuiltin;
    } else if (Module.builtinModules) {
      isCore = /* @__PURE__ */ __name((moduleName) => {
        if (moduleName.startsWith("node:")) {
          return true;
        }
        if (builtinModules === void 0) {
          builtinModules = new Set(Module.builtinModules);
        }
        return builtinModules.has(moduleName);
      }, "isCore");
    } else {
      const _resolve2 = require_resolve();
      const [major, minor] = process.versions.node.split(".").map(Number);
      if (major === 8 && minor < 8) {
        isCore = /* @__PURE__ */ __name((moduleName) => {
          if (moduleName === "http2") {
            return true;
          }
          return !!_resolve2.core[moduleName];
        }, "isCore");
      } else {
        isCore = /* @__PURE__ */ __name((moduleName) => {
          return !!_resolve2.core[moduleName];
        }, "isCore");
      }
    }
    var _resolve;
    function resolve2(moduleName, basedir) {
      if (!_resolve) {
        if (__require.resolve && __require.resolve.paths) {
          _resolve = /* @__PURE__ */ __name(function(moduleName2, basedir2) {
            return __require.resolve(moduleName2, { paths: [basedir2] });
          }, "_resolve");
        } else {
          const resolve3 = require_resolve();
          _resolve = /* @__PURE__ */ __name(function(moduleName2, basedir2) {
            return resolve3.sync(moduleName2, { basedir: basedir2 });
          }, "_resolve");
        }
      }
      return _resolve(moduleName, basedir);
    }
    __name(resolve2, "resolve");
    var normalize2 = /([/\\]index)?(\.js)?$/;
    var ExportsCache = class {
      static {
        __name(this, "ExportsCache");
      }
      constructor() {
        this._localCache = /* @__PURE__ */ new Map();
        this._kRitmExports = Symbol("RitmExports");
      }
      has(filename, isBuiltin) {
        if (this._localCache.has(filename)) {
          return true;
        } else if (!isBuiltin) {
          const mod = __require.cache[filename];
          return !!(mod && this._kRitmExports in mod);
        } else {
          return false;
        }
      }
      get(filename, isBuiltin) {
        const cachedExports = this._localCache.get(filename);
        if (cachedExports !== void 0) {
          return cachedExports;
        } else if (!isBuiltin) {
          const mod = __require.cache[filename];
          return mod && mod[this._kRitmExports];
        }
      }
      set(filename, exports2, isBuiltin) {
        if (isBuiltin) {
          this._localCache.set(filename, exports2);
        } else if (filename in __require.cache) {
          __require.cache[filename][this._kRitmExports] = exports2;
        } else {
          debug('non-core module is unexpectedly not in require.cache: "%s"', filename);
          this._localCache.set(filename, exports2);
        }
      }
    };
    function Hook(modules, options, onrequire) {
      if (this instanceof Hook === false) return new Hook(modules, options, onrequire);
      if (typeof modules === "function") {
        onrequire = modules;
        modules = null;
        options = null;
      } else if (typeof options === "function") {
        onrequire = options;
        options = null;
      }
      if (typeof Module._resolveFilename !== "function") {
        console.error("Error: Expected Module._resolveFilename to be a function (was: %s) - aborting!", typeof Module._resolveFilename);
        console.error("Please report this error as an issue related to Node.js %s at %s", process.version, require_package2().bugs.url);
        return;
      }
      this._cache = new ExportsCache();
      this._unhooked = false;
      this._origRequire = Module.prototype.require;
      const self2 = this;
      const patching = /* @__PURE__ */ new Set();
      const internals = options ? options.internals === true : false;
      const hasWhitelist = Array.isArray(modules);
      debug("registering require hook");
      this._require = Module.prototype.require = function(id) {
        if (self2._unhooked === true) {
          debug("ignoring require call - module is soft-unhooked");
          return self2._origRequire.apply(this, arguments);
        }
        return patchedRequire.call(this, arguments, false);
      };
      if (typeof process.getBuiltinModule === "function") {
        this._origGetBuiltinModule = process.getBuiltinModule;
        this._getBuiltinModule = process.getBuiltinModule = function(id) {
          if (self2._unhooked === true) {
            debug("ignoring process.getBuiltinModule call - module is soft-unhooked");
            return self2._origGetBuiltinModule.apply(this, arguments);
          }
          return patchedRequire.call(this, arguments, true);
        };
      }
      function patchedRequire(args, coreOnly) {
        const id = args[0];
        const core = isCore(id);
        let filename;
        if (core) {
          filename = id;
          if (id.startsWith("node:")) {
            const idWithoutPrefix = id.slice(5);
            if (isCore(idWithoutPrefix)) {
              filename = idWithoutPrefix;
            }
          }
        } else if (coreOnly) {
          debug("call to process.getBuiltinModule with unknown built-in id");
          return self2._origGetBuiltinModule.apply(this, args);
        } else {
          try {
            filename = Module._resolveFilename(id, this);
          } catch (resolveErr) {
            debug('Module._resolveFilename("%s") threw %j, calling original Module.require', id, resolveErr.message);
            return self2._origRequire.apply(this, args);
          }
        }
        let moduleName, basedir;
        debug("processing %s module require('%s'): %s", core === true ? "core" : "non-core", id, filename);
        if (self2._cache.has(filename, core) === true) {
          debug("returning already patched cached module: %s", filename);
          return self2._cache.get(filename, core);
        }
        const isPatching = patching.has(filename);
        if (isPatching === false) {
          patching.add(filename);
        }
        const exports2 = coreOnly ? self2._origGetBuiltinModule.apply(this, args) : self2._origRequire.apply(this, args);
        if (isPatching === true) {
          debug("module is in the process of being patched already - ignoring: %s", filename);
          return exports2;
        }
        patching.delete(filename);
        if (core === true) {
          if (hasWhitelist === true && modules.includes(filename) === false) {
            debug("ignoring core module not on whitelist: %s", filename);
            return exports2;
          }
          moduleName = filename;
        } else if (hasWhitelist === true && modules.includes(filename)) {
          const parsedPath = path11.parse(filename);
          moduleName = parsedPath.name;
          basedir = parsedPath.dir;
        } else {
          const stat = moduleDetailsFromPath(filename);
          if (stat === void 0) {
            debug("could not parse filename: %s", filename);
            return exports2;
          }
          moduleName = stat.name;
          basedir = stat.basedir;
          const fullModuleName = resolveModuleName(stat);
          debug("resolved filename to module: %s (id: %s, resolved: %s, basedir: %s)", moduleName, id, fullModuleName, basedir);
          let matchFound = false;
          if (hasWhitelist) {
            if (!id.startsWith(".") && modules.includes(id)) {
              moduleName = id;
              matchFound = true;
            }
            if (!modules.includes(moduleName) && !modules.includes(fullModuleName)) {
              return exports2;
            }
            if (modules.includes(fullModuleName) && fullModuleName !== moduleName) {
              moduleName = fullModuleName;
              matchFound = true;
            }
          }
          if (!matchFound) {
            let res;
            try {
              res = resolve2(moduleName, basedir);
            } catch (e) {
              debug("could not resolve module: %s", moduleName);
              self2._cache.set(filename, exports2, core);
              return exports2;
            }
            if (res !== filename) {
              if (internals === true) {
                moduleName = moduleName + path11.sep + path11.relative(basedir, filename);
                debug("preparing to process require of internal file: %s", moduleName);
              } else {
                debug("ignoring require of non-main module file: %s", res);
                self2._cache.set(filename, exports2, core);
                return exports2;
              }
            }
          }
        }
        self2._cache.set(filename, exports2, core);
        debug("calling require hook: %s", moduleName);
        const patchedExports = onrequire(exports2, moduleName, basedir);
        self2._cache.set(filename, patchedExports, core);
        debug("returning module: %s", moduleName);
        return patchedExports;
      }
      __name(patchedRequire, "patchedRequire");
    }
    __name(Hook, "Hook");
    Hook.prototype.unhook = function() {
      this._unhooked = true;
      if (this._require === Module.prototype.require) {
        Module.prototype.require = this._origRequire;
        debug("require unhook successful");
      } else {
        debug("require unhook unsuccessful");
      }
      if (process.getBuiltinModule !== void 0) {
        if (this._getBuiltinModule === process.getBuiltinModule) {
          process.getBuiltinModule = this._origGetBuiltinModule;
          debug("process.getBuiltinModule unhook successful");
        } else {
          debug("process.getBuiltinModule unhook unsuccessful");
        }
      }
    };
    function resolveModuleName(stat) {
      const normalizedPath = path11.sep !== "/" ? stat.path.split(path11.sep).join("/") : stat.path;
      return path11.posix.join(stat.name, normalizedPath).replace(normalize2, "");
    }
    __name(resolveModuleName, "resolveModuleName");
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/ModuleNameTrie.js
var require_ModuleNameTrie = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/ModuleNameTrie.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModuleNameTrie = exports.ModuleNameSeparator = void 0;
    exports.ModuleNameSeparator = "/";
    var ModuleNameTrieNode = class {
      static {
        __name(this, "ModuleNameTrieNode");
      }
      hooks = [];
      children = /* @__PURE__ */ new Map();
    };
    var ModuleNameTrie = class {
      static {
        __name(this, "ModuleNameTrie");
      }
      _trie = new ModuleNameTrieNode();
      _counter = 0;
      /**
       * Insert a module hook into the trie
       *
       * @param {Hooked} hook Hook
       */
      insert(hook) {
        let trieNode = this._trie;
        for (const moduleNamePart of hook.moduleName.split(exports.ModuleNameSeparator)) {
          let nextNode = trieNode.children.get(moduleNamePart);
          if (!nextNode) {
            nextNode = new ModuleNameTrieNode();
            trieNode.children.set(moduleNamePart, nextNode);
          }
          trieNode = nextNode;
        }
        trieNode.hooks.push({ hook, insertedId: this._counter++ });
      }
      /**
       * Search for matching hooks in the trie
       *
       * @param {string} moduleName Module name
       * @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
       * @param {boolean} fullOnly Whether to return only full matches
       * @returns {Hooked[]} Matching hooks
       */
      search(moduleName, { maintainInsertionOrder, fullOnly } = {}) {
        let trieNode = this._trie;
        const results = [];
        let foundFull = true;
        for (const moduleNamePart of moduleName.split(exports.ModuleNameSeparator)) {
          const nextNode = trieNode.children.get(moduleNamePart);
          if (!nextNode) {
            foundFull = false;
            break;
          }
          if (!fullOnly) {
            results.push(...nextNode.hooks);
          }
          trieNode = nextNode;
        }
        if (fullOnly && foundFull) {
          results.push(...trieNode.hooks);
        }
        if (results.length === 0) {
          return [];
        }
        if (results.length === 1) {
          return [results[0].hook];
        }
        if (maintainInsertionOrder) {
          results.sort((a, b) => a.insertedId - b.insertedId);
        }
        return results.map(({ hook }) => hook);
      }
    };
    exports.ModuleNameTrie = ModuleNameTrie;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/RequireInTheMiddleSingleton.js
var require_RequireInTheMiddleSingleton = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/RequireInTheMiddleSingleton.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RequireInTheMiddleSingleton = void 0;
    var require_in_the_middle_1 = require_require_in_the_middle();
    var path11 = __require("path");
    var ModuleNameTrie_1 = require_ModuleNameTrie();
    var isMocha = [
      "afterEach",
      "after",
      "beforeEach",
      "before",
      "describe",
      "it"
    ].every((fn) => {
      return typeof globalThis[fn] === "function";
    });
    var RequireInTheMiddleSingleton = class _RequireInTheMiddleSingleton {
      static {
        __name(this, "RequireInTheMiddleSingleton");
      }
      _moduleNameTrie = new ModuleNameTrie_1.ModuleNameTrie();
      static _instance;
      constructor() {
        this._initialize();
      }
      _initialize() {
        new require_in_the_middle_1.Hook(
          // Intercept all `require` calls; we will filter the matching ones below
          null,
          { internals: true },
          (exports2, name, basedir) => {
            const normalizedModuleName = normalizePathSeparators(name);
            const matches = this._moduleNameTrie.search(normalizedModuleName, {
              maintainInsertionOrder: true,
              // For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises').
              // This matches the behavior of `require-in-the-middle`.
              // `basedir` is always `undefined` for core modules.
              fullOnly: basedir === void 0
            });
            for (const { onRequire } of matches) {
              exports2 = onRequire(exports2, name, basedir);
            }
            return exports2;
          }
        );
      }
      /**
       * Register a hook with `require-in-the-middle`
       *
       * @param {string} moduleName Module name
       * @param {OnRequireFn} onRequire Hook function
       * @returns {Hooked} Registered hook
       */
      register(moduleName, onRequire) {
        const hooked = { moduleName, onRequire };
        this._moduleNameTrie.insert(hooked);
        return hooked;
      }
      /**
       * Get the `RequireInTheMiddleSingleton` singleton
       *
       * @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
       */
      static getInstance() {
        if (isMocha)
          return new _RequireInTheMiddleSingleton();
        return this._instance = this._instance ?? new _RequireInTheMiddleSingleton();
      }
    };
    exports.RequireInTheMiddleSingleton = RequireInTheMiddleSingleton;
    function normalizePathSeparators(moduleNameOrPath) {
      return path11.sep !== ModuleNameTrie_1.ModuleNameSeparator ? moduleNameOrPath.split(path11.sep).join(ModuleNameTrie_1.ModuleNameSeparator) : moduleNameOrPath;
    }
    __name(normalizePathSeparators, "normalizePathSeparators");
  }
});

// node_modules/import-in-the-middle/lib/register.js
var require_register = __commonJS({
  "node_modules/import-in-the-middle/lib/register.js"(exports) {
    init_esbuild_shims();
    var importHooks = [];
    var setters = /* @__PURE__ */ new WeakMap();
    var getters = /* @__PURE__ */ new WeakMap();
    var specifiers = /* @__PURE__ */ new Map();
    var toHook = [];
    var proxyHandler = {
      set(target, name, value) {
        return setters.get(target)[name](value);
      },
      get(target, name) {
        if (name === Symbol.toStringTag) {
          return "Module";
        }
        const getter = getters.get(target)[name];
        if (typeof getter === "function") {
          return getter();
        }
      },
      defineProperty(target, property, descriptor) {
        if (!("value" in descriptor)) {
          throw new Error("Getters/setters are not supported for exports property descriptors.");
        }
        return setters.get(target)[property](descriptor.value);
      }
    };
    function register(name, namespace, set, get, specifier) {
      specifiers.set(name, specifier);
      setters.set(namespace, set);
      getters.set(namespace, get);
      const proxy = new Proxy(namespace, proxyHandler);
      importHooks.forEach((hook) => hook(name, proxy));
      toHook.push([name, proxy]);
    }
    __name(register, "register");
    var experimentalPatchInternals = false;
    function getExperimentalPatchInternals() {
      return experimentalPatchInternals;
    }
    __name(getExperimentalPatchInternals, "getExperimentalPatchInternals");
    function setExperimentalPatchInternals(value) {
      experimentalPatchInternals = value;
    }
    __name(setExperimentalPatchInternals, "setExperimentalPatchInternals");
    exports.register = register;
    exports.importHooks = importHooks;
    exports.specifiers = specifiers;
    exports.toHook = toHook;
    exports.getExperimentalPatchInternals = getExperimentalPatchInternals;
    exports.setExperimentalPatchInternals = setExperimentalPatchInternals;
  }
});

// node_modules/import-in-the-middle/index.js
var require_import_in_the_middle = __commonJS({
  "node_modules/import-in-the-middle/index.js"(exports, module) {
    init_esbuild_shims();
    var path11 = __require("path");
    var parse = require_module_details_from_path();
    var { fileURLToPath } = __require("url");
    var { MessageChannel } = __require("worker_threads");
    var {
      importHooks,
      specifiers,
      toHook,
      getExperimentalPatchInternals
    } = require_register();
    function addHook(hook) {
      importHooks.push(hook);
      toHook.forEach(([name, namespace]) => hook(name, namespace));
    }
    __name(addHook, "addHook");
    function removeHook(hook) {
      const index = importHooks.indexOf(hook);
      if (index > -1) {
        importHooks.splice(index, 1);
      }
    }
    __name(removeHook, "removeHook");
    function callHookFn(hookFn, namespace, name, baseDir) {
      const newDefault = hookFn(namespace, name, baseDir);
      if (newDefault && newDefault !== namespace) {
        namespace.default = newDefault;
      }
    }
    __name(callHookFn, "callHookFn");
    var sendModulesToLoader;
    function createAddHookMessageChannel() {
      const { port1, port2 } = new MessageChannel();
      let pendingAckCount = 0;
      let resolveFn;
      sendModulesToLoader = /* @__PURE__ */ __name((modules) => {
        pendingAckCount++;
        port1.postMessage(modules);
      }, "sendModulesToLoader");
      port1.on("message", () => {
        pendingAckCount--;
        if (resolveFn && pendingAckCount <= 0) {
          resolveFn();
        }
      }).unref();
      function waitForAllMessagesAcknowledged() {
        const timer = setInterval(() => {
        }, 1e3);
        const promise = new Promise((resolve2) => {
          resolveFn = resolve2;
        }).then(() => {
          clearInterval(timer);
        });
        if (pendingAckCount === 0) {
          resolveFn();
        }
        return promise;
      }
      __name(waitForAllMessagesAcknowledged, "waitForAllMessagesAcknowledged");
      const addHookMessagePort = port2;
      const registerOptions = { data: { addHookMessagePort, include: [] }, transferList: [addHookMessagePort] };
      return { registerOptions, addHookMessagePort, waitForAllMessagesAcknowledged };
    }
    __name(createAddHookMessageChannel, "createAddHookMessageChannel");
    function Hook(modules, options, hookFn) {
      if (this instanceof Hook === false) return new Hook(modules, options, hookFn);
      if (typeof modules === "function") {
        hookFn = modules;
        modules = null;
        options = null;
      } else if (typeof options === "function") {
        hookFn = options;
        options = null;
      }
      const internals = options ? options.internals === true : false;
      if (sendModulesToLoader && Array.isArray(modules)) {
        sendModulesToLoader(modules);
      }
      this._iitmHook = (name, namespace) => {
        const filename = name;
        const isBuiltin = name.startsWith("node:");
        let baseDir;
        if (isBuiltin) {
          name = name.replace(/^node:/, "");
        } else {
          if (name.startsWith("file://")) {
            try {
              name = fileURLToPath(name);
            } catch (e) {
            }
          }
          const details = parse(name);
          if (details) {
            name = details.name;
            baseDir = details.basedir;
          }
        }
        if (modules) {
          for (const moduleName of modules) {
            if (moduleName === name) {
              if (baseDir) {
                if (internals) {
                  name = name + path11.sep + path11.relative(baseDir, fileURLToPath(filename));
                } else {
                  if (!getExperimentalPatchInternals() && !baseDir.endsWith(specifiers.get(filename))) continue;
                }
              }
              callHookFn(hookFn, namespace, name, baseDir);
            }
          }
        } else {
          callHookFn(hookFn, namespace, name, baseDir);
        }
      };
      addHook(this._iitmHook);
    }
    __name(Hook, "Hook");
    Hook.prototype.unhook = function() {
      removeHook(this._iitmHook);
    };
    module.exports = Hook;
    module.exports.Hook = Hook;
    module.exports.addHook = addHook;
    module.exports.removeHook = removeHook;
    module.exports.createAddHookMessageChannel = createAddHookMessageChannel;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/utils.js
var require_utils7 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isWrapped = exports.safeExecuteInTheMiddleAsync = exports.safeExecuteInTheMiddle = void 0;
    function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) {
      let error;
      let result;
      try {
        result = execute();
      } catch (e) {
        error = e;
      } finally {
        onFinish(error, result);
        if (error && !preventThrowingError) {
          throw error;
        }
        return result;
      }
    }
    __name(safeExecuteInTheMiddle, "safeExecuteInTheMiddle");
    exports.safeExecuteInTheMiddle = safeExecuteInTheMiddle;
    async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) {
      let error;
      let result;
      try {
        result = await execute();
      } catch (e) {
        error = e;
      } finally {
        onFinish(error, result);
        if (error && !preventThrowingError) {
          throw error;
        }
        return result;
      }
    }
    __name(safeExecuteInTheMiddleAsync, "safeExecuteInTheMiddleAsync");
    exports.safeExecuteInTheMiddleAsync = safeExecuteInTheMiddleAsync;
    function isWrapped(func) {
      return typeof func === "function" && typeof func.__original === "function" && typeof func.__unwrap === "function" && func.__wrapped === true;
    }
    __name(isWrapped, "isWrapped");
    exports.isWrapped = isWrapped;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/instrumentation.js
var require_instrumentation2 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/instrumentation.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InstrumentationBase = void 0;
    var path11 = __require("path");
    var util_1 = __require("util");
    var semver_1 = require_semver();
    var shimmer_1 = require_shimmer();
    var instrumentation_1 = require_instrumentation();
    var RequireInTheMiddleSingleton_1 = require_RequireInTheMiddleSingleton();
    var import_in_the_middle_1 = require_import_in_the_middle();
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var require_in_the_middle_1 = require_require_in_the_middle();
    var fs_1 = __require("fs");
    var utils_1 = require_utils7();
    var InstrumentationBase = class extends instrumentation_1.InstrumentationAbstract {
      static {
        __name(this, "InstrumentationBase");
      }
      _modules;
      _hooks = [];
      _requireInTheMiddleSingleton = RequireInTheMiddleSingleton_1.RequireInTheMiddleSingleton.getInstance();
      _enabled = false;
      constructor(instrumentationName, instrumentationVersion, config) {
        super(instrumentationName, instrumentationVersion, config);
        let modules = this.init();
        if (modules && !Array.isArray(modules)) {
          modules = [modules];
        }
        this._modules = modules || [];
        if (this._config.enabled) {
          this.enable();
        }
      }
      _wrap = /* @__PURE__ */ __name((moduleExports, name, wrapper) => {
        if ((0, utils_1.isWrapped)(moduleExports[name])) {
          this._unwrap(moduleExports, name);
        }
        if (!util_1.types.isProxy(moduleExports)) {
          return (0, shimmer_1.wrap)(moduleExports, name, wrapper);
        } else {
          const wrapped = (0, shimmer_1.wrap)(Object.assign({}, moduleExports), name, wrapper);
          Object.defineProperty(moduleExports, name, {
            value: wrapped
          });
          return wrapped;
        }
      }, "_wrap");
      _unwrap = /* @__PURE__ */ __name((moduleExports, name) => {
        if (!util_1.types.isProxy(moduleExports)) {
          return (0, shimmer_1.unwrap)(moduleExports, name);
        } else {
          return Object.defineProperty(moduleExports, name, {
            value: moduleExports[name]
          });
        }
      }, "_unwrap");
      _massWrap = /* @__PURE__ */ __name((moduleExportsArray, names, wrapper) => {
        if (!moduleExportsArray) {
          api_1.diag.error("must provide one or more modules to patch");
          return;
        } else if (!Array.isArray(moduleExportsArray)) {
          moduleExportsArray = [moduleExportsArray];
        }
        if (!(names && Array.isArray(names))) {
          api_1.diag.error("must provide one or more functions to wrap on modules");
          return;
        }
        moduleExportsArray.forEach((moduleExports) => {
          names.forEach((name) => {
            this._wrap(moduleExports, name, wrapper);
          });
        });
      }, "_massWrap");
      _massUnwrap = /* @__PURE__ */ __name((moduleExportsArray, names) => {
        if (!moduleExportsArray) {
          api_1.diag.error("must provide one or more modules to patch");
          return;
        } else if (!Array.isArray(moduleExportsArray)) {
          moduleExportsArray = [moduleExportsArray];
        }
        if (!(names && Array.isArray(names))) {
          api_1.diag.error("must provide one or more functions to wrap on modules");
          return;
        }
        moduleExportsArray.forEach((moduleExports) => {
          names.forEach((name) => {
            this._unwrap(moduleExports, name);
          });
        });
      }, "_massUnwrap");
      _warnOnPreloadedModules() {
        this._modules.forEach((module2) => {
          const { name } = module2;
          try {
            const resolvedModule = __require.resolve(name);
            if (__require.cache[resolvedModule]) {
              this._diag.warn(`Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`);
            }
          } catch {
          }
        });
      }
      _extractPackageVersion(baseDir) {
        try {
          const json = (0, fs_1.readFileSync)(path11.join(baseDir, "package.json"), {
            encoding: "utf8"
          });
          const version = JSON.parse(json).version;
          return typeof version === "string" ? version : void 0;
        } catch {
          api_1.diag.warn("Failed extracting version", baseDir);
        }
        return void 0;
      }
      _onRequire(module2, exports2, name, baseDir) {
        if (!baseDir) {
          if (typeof module2.patch === "function") {
            module2.moduleExports = exports2;
            if (this._enabled) {
              this._diag.debug("Applying instrumentation patch for nodejs core module on require hook", {
                module: module2.name
              });
              return module2.patch(exports2);
            }
          }
          return exports2;
        }
        const version = this._extractPackageVersion(baseDir);
        module2.moduleVersion = version;
        if (module2.name === name) {
          if (isSupported(module2.supportedVersions, version, module2.includePrerelease)) {
            if (typeof module2.patch === "function") {
              module2.moduleExports = exports2;
              if (this._enabled) {
                this._diag.debug("Applying instrumentation patch for module on require hook", {
                  module: module2.name,
                  version: module2.moduleVersion,
                  baseDir
                });
                return module2.patch(exports2, module2.moduleVersion);
              }
            }
          }
          return exports2;
        }
        const files = module2.files ?? [];
        const normalizedName = path11.normalize(name);
        const supportedFileInstrumentations = files.filter((f) => f.name === normalizedName).filter((f) => isSupported(f.supportedVersions, version, module2.includePrerelease));
        return supportedFileInstrumentations.reduce((patchedExports, file) => {
          file.moduleExports = patchedExports;
          if (this._enabled) {
            this._diag.debug("Applying instrumentation patch for nodejs module file on require hook", {
              module: module2.name,
              version: module2.moduleVersion,
              fileName: file.name,
              baseDir
            });
            return file.patch(patchedExports, module2.moduleVersion);
          }
          return patchedExports;
        }, exports2);
      }
      enable() {
        if (this._enabled) {
          return;
        }
        this._enabled = true;
        if (this._hooks.length > 0) {
          for (const module2 of this._modules) {
            if (typeof module2.patch === "function" && module2.moduleExports) {
              this._diag.debug("Applying instrumentation patch for nodejs module on instrumentation enabled", {
                module: module2.name,
                version: module2.moduleVersion
              });
              module2.patch(module2.moduleExports, module2.moduleVersion);
            }
            for (const file of module2.files) {
              if (file.moduleExports) {
                this._diag.debug("Applying instrumentation patch for nodejs module file on instrumentation enabled", {
                  module: module2.name,
                  version: module2.moduleVersion,
                  fileName: file.name
                });
                file.patch(file.moduleExports, module2.moduleVersion);
              }
            }
          }
          return;
        }
        this._warnOnPreloadedModules();
        for (const module2 of this._modules) {
          const hookFn = /* @__PURE__ */ __name((exports2, name, baseDir) => {
            if (!baseDir && path11.isAbsolute(name)) {
              const parsedPath = path11.parse(name);
              name = parsedPath.name;
              baseDir = parsedPath.dir;
            }
            return this._onRequire(module2, exports2, name, baseDir);
          }, "hookFn");
          const onRequire = /* @__PURE__ */ __name((exports2, name, baseDir) => {
            return this._onRequire(module2, exports2, name, baseDir);
          }, "onRequire");
          const hook = path11.isAbsolute(module2.name) ? new require_in_the_middle_1.Hook([module2.name], { internals: true }, onRequire) : this._requireInTheMiddleSingleton.register(module2.name, onRequire);
          this._hooks.push(hook);
          const esmHook = new import_in_the_middle_1.Hook([module2.name], { internals: false }, hookFn);
          this._hooks.push(esmHook);
        }
      }
      disable() {
        if (!this._enabled) {
          return;
        }
        this._enabled = false;
        for (const module2 of this._modules) {
          if (typeof module2.unpatch === "function" && module2.moduleExports) {
            this._diag.debug("Removing instrumentation patch for nodejs module on instrumentation disabled", {
              module: module2.name,
              version: module2.moduleVersion
            });
            module2.unpatch(module2.moduleExports, module2.moduleVersion);
          }
          for (const file of module2.files) {
            if (file.moduleExports) {
              this._diag.debug("Removing instrumentation patch for nodejs module file on instrumentation disabled", {
                module: module2.name,
                version: module2.moduleVersion,
                fileName: file.name
              });
              file.unpatch(file.moduleExports, module2.moduleVersion);
            }
          }
        }
      }
      isEnabled() {
        return this._enabled;
      }
    };
    exports.InstrumentationBase = InstrumentationBase;
    function isSupported(supportedVersions, version, includePrerelease) {
      if (typeof version === "undefined") {
        return supportedVersions.includes("*");
      }
      return supportedVersions.some((supportedVersion) => {
        return (0, semver_1.satisfies)(version, supportedVersion, { includePrerelease });
      });
    }
    __name(isSupported, "isSupported");
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/normalize.js
var require_normalize = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/normalize.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalize = void 0;
    var path_1 = __require("path");
    Object.defineProperty(exports, "normalize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return path_1.normalize;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/node/index.js
var require_node11 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalize = exports.InstrumentationBase = void 0;
    var instrumentation_1 = require_instrumentation2();
    Object.defineProperty(exports, "InstrumentationBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return instrumentation_1.InstrumentationBase;
    }, "get") });
    var normalize_1 = require_normalize();
    Object.defineProperty(exports, "normalize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return normalize_1.normalize;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/platform/index.js
var require_platform10 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalize = exports.InstrumentationBase = void 0;
    var node_1 = require_node11();
    Object.defineProperty(exports, "InstrumentationBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.InstrumentationBase;
    }, "get") });
    Object.defineProperty(exports, "normalize", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.normalize;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleDefinition.js
var require_instrumentationNodeModuleDefinition = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleDefinition.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InstrumentationNodeModuleDefinition = void 0;
    var InstrumentationNodeModuleDefinition = class {
      static {
        __name(this, "InstrumentationNodeModuleDefinition");
      }
      name;
      supportedVersions;
      patch;
      unpatch;
      files;
      constructor(name, supportedVersions, patch, unpatch, files) {
        this.name = name;
        this.supportedVersions = supportedVersions;
        this.patch = patch;
        this.unpatch = unpatch;
        this.files = files || [];
      }
    };
    exports.InstrumentationNodeModuleDefinition = InstrumentationNodeModuleDefinition;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleFile.js
var require_instrumentationNodeModuleFile = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleFile.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InstrumentationNodeModuleFile = void 0;
    var index_1 = require_platform10();
    var InstrumentationNodeModuleFile = class {
      static {
        __name(this, "InstrumentationNodeModuleFile");
      }
      supportedVersions;
      patch;
      unpatch;
      name;
      constructor(name, supportedVersions, patch, unpatch) {
        this.supportedVersions = supportedVersions;
        this.patch = patch;
        this.unpatch = unpatch;
        this.name = (0, index_1.normalize)(name);
      }
    };
    exports.InstrumentationNodeModuleFile = InstrumentationNodeModuleFile;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/semconvStability.js
var require_semconvStability = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/semconvStability.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.semconvStabilityFromStr = exports.SemconvStability = void 0;
    var SemconvStability;
    (function(SemconvStability2) {
      SemconvStability2[SemconvStability2["STABLE"] = 1] = "STABLE";
      SemconvStability2[SemconvStability2["OLD"] = 2] = "OLD";
      SemconvStability2[SemconvStability2["DUPLICATE"] = 3] = "DUPLICATE";
    })(SemconvStability = exports.SemconvStability || (exports.SemconvStability = {}));
    function semconvStabilityFromStr(namespace, str) {
      let semconvStability = SemconvStability.OLD;
      const entries = str?.split(",").map((v) => v.trim()).filter((s) => s !== "");
      for (const entry of entries ?? []) {
        if (entry.toLowerCase() === namespace + "/dup") {
          semconvStability = SemconvStability.DUPLICATE;
          break;
        } else if (entry.toLowerCase() === namespace) {
          semconvStability = SemconvStability.STABLE;
        }
      }
      return semconvStability;
    }
    __name(semconvStabilityFromStr, "semconvStabilityFromStr");
    exports.semconvStabilityFromStr = semconvStabilityFromStr;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/index.js
var require_src21 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.semconvStabilityFromStr = exports.SemconvStability = exports.safeExecuteInTheMiddleAsync = exports.safeExecuteInTheMiddle = exports.isWrapped = exports.InstrumentationNodeModuleFile = exports.InstrumentationNodeModuleDefinition = exports.InstrumentationBase = exports.registerInstrumentations = void 0;
    var autoLoader_1 = require_autoLoader();
    Object.defineProperty(exports, "registerInstrumentations", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return autoLoader_1.registerInstrumentations;
    }, "get") });
    var index_1 = require_platform10();
    Object.defineProperty(exports, "InstrumentationBase", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return index_1.InstrumentationBase;
    }, "get") });
    var instrumentationNodeModuleDefinition_1 = require_instrumentationNodeModuleDefinition();
    Object.defineProperty(exports, "InstrumentationNodeModuleDefinition", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return instrumentationNodeModuleDefinition_1.InstrumentationNodeModuleDefinition;
    }, "get") });
    var instrumentationNodeModuleFile_1 = require_instrumentationNodeModuleFile();
    Object.defineProperty(exports, "InstrumentationNodeModuleFile", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return instrumentationNodeModuleFile_1.InstrumentationNodeModuleFile;
    }, "get") });
    var utils_1 = require_utils7();
    Object.defineProperty(exports, "isWrapped", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.isWrapped;
    }, "get") });
    Object.defineProperty(exports, "safeExecuteInTheMiddle", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.safeExecuteInTheMiddle;
    }, "get") });
    Object.defineProperty(exports, "safeExecuteInTheMiddleAsync", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.safeExecuteInTheMiddleAsync;
    }, "get") });
    var semconvStability_1 = require_semconvStability();
    Object.defineProperty(exports, "SemconvStability", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return semconvStability_1.SemconvStability;
    }, "get") });
    Object.defineProperty(exports, "semconvStabilityFromStr", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return semconvStability_1.semconvStabilityFromStr;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/version.js
var require_version6 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js
var require_OTLPLogExporter3 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var otlp_transformer_1 = require_src10();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var version_1 = require_version6();
    var OTLPLogExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPLogExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "LOGS", "v1/logs", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/x-protobuf"
        }), otlp_transformer_1.ProtobufLogsSerializer));
      }
    };
    exports.OTLPLogExporter = OTLPLogExporter2;
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js
var require_node12 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var OTLPLogExporter_1 = require_OTLPLogExporter3();
    Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPLogExporter_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js
var require_platform11 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var node_1 = require_node12();
    Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js
var require_src22 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPLogExporter = void 0;
    var platform_1 = require_platform11();
    Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPLogExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/version.js
var require_version7 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js
var require_OTLPMetricExporter3 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var exporter_metrics_otlp_http_1 = require_src13();
    var otlp_transformer_1 = require_src10();
    var version_1 = require_version7();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPMetricExporter2 = class extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase {
      static {
        __name(this, "OTLPMetricExporter");
      }
      constructor(config) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, "METRICS", "v1/metrics", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/x-protobuf"
        }), otlp_transformer_1.ProtobufMetricsSerializer), config);
      }
    };
    exports.OTLPMetricExporter = OTLPMetricExporter2;
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js
var require_node13 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var OTLPMetricExporter_1 = require_OTLPMetricExporter3();
    Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPMetricExporter_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js
var require_platform12 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var node_1 = require_node13();
    Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js
var require_src23 = __commonJS({
  "node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPMetricExporter = void 0;
    var platform_1 = require_platform12();
    Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPMetricExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js
var require_PrometheusSerializer = __commonJS({
  "node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PrometheusSerializer = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var sdk_metrics_1 = require_src9();
    var core_1 = require_src3();
    function escapeString(str) {
      return str.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
    }
    __name(escapeString, "escapeString");
    function escapeAttributeValue(str = "") {
      if (typeof str !== "string") {
        str = JSON.stringify(str);
      }
      return escapeString(str).replace(/"/g, '\\"');
    }
    __name(escapeAttributeValue, "escapeAttributeValue");
    var invalidCharacterRegex = /[^a-z0-9_]/gi;
    var multipleUnderscoreRegex = /_{2,}/g;
    function sanitizePrometheusMetricName(name) {
      return name.replace(invalidCharacterRegex, "_").replace(multipleUnderscoreRegex, "_");
    }
    __name(sanitizePrometheusMetricName, "sanitizePrometheusMetricName");
    function enforcePrometheusNamingConvention(name, data) {
      if (!name.endsWith("_total") && data.dataPointType === sdk_metrics_1.DataPointType.SUM && data.isMonotonic) {
        name = name + "_total";
      }
      return name;
    }
    __name(enforcePrometheusNamingConvention, "enforcePrometheusNamingConvention");
    function valueString(value) {
      if (value === Infinity) {
        return "+Inf";
      } else if (value === -Infinity) {
        return "-Inf";
      } else {
        return `${value}`;
      }
    }
    __name(valueString, "valueString");
    function toPrometheusType(metricData) {
      switch (metricData.dataPointType) {
        case sdk_metrics_1.DataPointType.SUM:
          if (metricData.isMonotonic) {
            return "counter";
          }
          return "gauge";
        case sdk_metrics_1.DataPointType.GAUGE:
          return "gauge";
        case sdk_metrics_1.DataPointType.HISTOGRAM:
          return "histogram";
        default:
          return "untyped";
      }
    }
    __name(toPrometheusType, "toPrometheusType");
    function stringify(metricName, attributes, value, timestamp, additionalAttributes) {
      let hasAttribute = false;
      let attributesStr = "";
      for (const [key, val] of Object.entries(attributes)) {
        const sanitizedAttributeName = sanitizePrometheusMetricName(key);
        hasAttribute = true;
        attributesStr += `${attributesStr.length > 0 ? "," : ""}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`;
      }
      if (additionalAttributes) {
        for (const [key, val] of Object.entries(additionalAttributes)) {
          const sanitizedAttributeName = sanitizePrometheusMetricName(key);
          hasAttribute = true;
          attributesStr += `${attributesStr.length > 0 ? "," : ""}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`;
        }
      }
      if (hasAttribute) {
        metricName += `{${attributesStr}}`;
      }
      return `${metricName} ${valueString(value)}${timestamp !== void 0 ? " " + String(timestamp) : ""}
`;
    }
    __name(stringify, "stringify");
    var NO_REGISTERED_METRICS = "# no registered metrics";
    var PrometheusSerializer = class {
      static {
        __name(this, "PrometheusSerializer");
      }
      _prefix;
      _appendTimestamp;
      _additionalAttributes;
      _withResourceConstantLabels;
      constructor(prefix, appendTimestamp = false, withResourceConstantLabels) {
        if (prefix) {
          this._prefix = prefix + "_";
        }
        this._appendTimestamp = appendTimestamp;
        this._withResourceConstantLabels = withResourceConstantLabels;
      }
      serialize(resourceMetrics) {
        let str = "";
        this._additionalAttributes = this._filterResourceConstantLabels(resourceMetrics.resource.attributes, this._withResourceConstantLabels);
        for (const scopeMetrics of resourceMetrics.scopeMetrics) {
          str += this._serializeScopeMetrics(scopeMetrics);
        }
        if (str === "") {
          str += NO_REGISTERED_METRICS;
        }
        return this._serializeResource(resourceMetrics.resource) + str;
      }
      _filterResourceConstantLabels(attributes, pattern) {
        if (pattern) {
          const filteredAttributes = {};
          for (const [key, value] of Object.entries(attributes)) {
            if (key.match(pattern)) {
              filteredAttributes[key] = value;
            }
          }
          return filteredAttributes;
        }
        return;
      }
      _serializeScopeMetrics(scopeMetrics) {
        let str = "";
        for (const metric of scopeMetrics.metrics) {
          str += this._serializeMetricData(metric) + "\n";
        }
        return str;
      }
      _serializeMetricData(metricData) {
        let name = sanitizePrometheusMetricName(escapeString(metricData.descriptor.name));
        if (this._prefix) {
          name = `${this._prefix}${name}`;
        }
        const dataPointType = metricData.dataPointType;
        name = enforcePrometheusNamingConvention(name, metricData);
        const help = `# HELP ${name} ${escapeString(metricData.descriptor.description || "description missing")}`;
        const unit = metricData.descriptor.unit ? `
# UNIT ${name} ${escapeString(metricData.descriptor.unit)}` : "";
        const type = `# TYPE ${name} ${toPrometheusType(metricData)}`;
        let results = "";
        switch (dataPointType) {
          case sdk_metrics_1.DataPointType.SUM:
          case sdk_metrics_1.DataPointType.GAUGE: {
            results = metricData.dataPoints.map((it) => this._serializeSingularDataPoint(name, metricData, it)).join("");
            break;
          }
          case sdk_metrics_1.DataPointType.HISTOGRAM: {
            results = metricData.dataPoints.map((it) => this._serializeHistogramDataPoint(name, metricData, it)).join("");
            break;
          }
          default: {
            api_1.diag.error(`Unrecognizable DataPointType: ${dataPointType} for metric "${name}"`);
          }
        }
        return `${help}${unit}
${type}
${results}`.trim();
      }
      _serializeSingularDataPoint(name, data, dataPoint) {
        let results = "";
        name = enforcePrometheusNamingConvention(name, data);
        const { value, attributes } = dataPoint;
        const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime);
        results += stringify(name, attributes, value, this._appendTimestamp ? timestamp : void 0, this._additionalAttributes);
        return results;
      }
      _serializeHistogramDataPoint(name, data, dataPoint) {
        let results = "";
        name = enforcePrometheusNamingConvention(name, data);
        const attributes = dataPoint.attributes;
        const histogram = dataPoint.value;
        const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime);
        for (const key of ["count", "sum"]) {
          const value = histogram[key];
          if (value != null)
            results += stringify(name + "_" + key, attributes, value, this._appendTimestamp ? timestamp : void 0, this._additionalAttributes);
        }
        let cumulativeSum = 0;
        const countEntries = histogram.buckets.counts.entries();
        let infiniteBoundaryDefined = false;
        for (const [idx, val] of countEntries) {
          cumulativeSum += val;
          const upperBound = histogram.buckets.boundaries[idx];
          if (upperBound === void 0 && infiniteBoundaryDefined) {
            break;
          }
          if (upperBound === Infinity) {
            infiniteBoundaryDefined = true;
          }
          results += stringify(name + "_bucket", attributes, cumulativeSum, this._appendTimestamp ? timestamp : void 0, Object.assign({}, this._additionalAttributes ?? {}, {
            le: upperBound === void 0 || upperBound === Infinity ? "+Inf" : String(upperBound)
          }));
        }
        return results;
      }
      _serializeResource(resource) {
        const name = "target_info";
        const help = `# HELP ${name} Target metadata`;
        const type = `# TYPE ${name} gauge`;
        const results = stringify(name, resource.attributes, 1).trim();
        return `${help}
${type}
${results}
`;
      }
    };
    exports.PrometheusSerializer = PrometheusSerializer;
  }
});

// node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js
var require_PrometheusExporter = __commonJS({
  "node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PrometheusExporter = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var sdk_metrics_1 = require_src9();
    var http_1 = __require("http");
    var PrometheusSerializer_1 = require_PrometheusSerializer();
    var url_1 = __require("url");
    var PrometheusExporter = class _PrometheusExporter extends sdk_metrics_1.MetricReader {
      static {
        __name(this, "PrometheusExporter");
      }
      static DEFAULT_OPTIONS = {
        host: void 0,
        port: 9464,
        endpoint: "/metrics",
        prefix: "",
        appendTimestamp: false,
        withResourceConstantLabels: void 0
      };
      _host;
      _port;
      _baseUrl;
      _endpoint;
      _server;
      _prefix;
      _appendTimestamp;
      _serializer;
      _startServerPromise;
      // This will be required when histogram is implemented. Leaving here so it is not forgotten
      // Histogram cannot have a attribute named 'le'
      // private static readonly RESERVED_HISTOGRAM_LABEL = 'le';
      /**
       * Constructor
       * @param config Exporter configuration
       * @param callback Callback to be called after a server was started
       */
      constructor(config = {}, callback = () => {
      }) {
        super({
          aggregationSelector: /* @__PURE__ */ __name((_instrumentType) => {
            return {
              type: sdk_metrics_1.AggregationType.DEFAULT
            };
          }, "aggregationSelector"),
          aggregationTemporalitySelector: /* @__PURE__ */ __name((_instrumentType) => sdk_metrics_1.AggregationTemporality.CUMULATIVE, "aggregationTemporalitySelector"),
          metricProducers: config.metricProducers
        });
        this._host = config.host || process.env.OTEL_EXPORTER_PROMETHEUS_HOST || _PrometheusExporter.DEFAULT_OPTIONS.host;
        this._port = config.port || Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT) || _PrometheusExporter.DEFAULT_OPTIONS.port;
        this._prefix = config.prefix || _PrometheusExporter.DEFAULT_OPTIONS.prefix;
        this._appendTimestamp = typeof config.appendTimestamp === "boolean" ? config.appendTimestamp : _PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp;
        const _withResourceConstantLabels = config.withResourceConstantLabels || _PrometheusExporter.DEFAULT_OPTIONS.withResourceConstantLabels;
        this._server = (0, http_1.createServer)(this._requestHandler).unref();
        this._serializer = new PrometheusSerializer_1.PrometheusSerializer(this._prefix, this._appendTimestamp, _withResourceConstantLabels);
        this._baseUrl = `http://${this._host}:${this._port}/`;
        this._endpoint = (config.endpoint || _PrometheusExporter.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/, "/$1");
        if (config.preventServerStart !== true) {
          this.startServer().then(callback, (err) => {
            api_1.diag.error(err);
            callback(err);
          });
        } else if (callback) {
          queueMicrotask(callback);
        }
      }
      async onForceFlush() {
      }
      /**
       * Shuts down the export server and clears the registry
       */
      onShutdown() {
        return this.stopServer();
      }
      /**
       * Stops the Prometheus export server
       */
      stopServer() {
        if (!this._server) {
          api_1.diag.debug("Prometheus stopServer() was called but server was never started.");
          return Promise.resolve();
        } else {
          return new Promise((resolve2) => {
            this._server.close((err) => {
              if (!err) {
                api_1.diag.debug("Prometheus exporter was stopped");
              } else {
                if (err.code !== "ERR_SERVER_NOT_RUNNING") {
                  (0, core_1.globalErrorHandler)(err);
                }
              }
              resolve2();
            });
          });
        }
      }
      /**
       * Starts the Prometheus export server
       */
      startServer() {
        this._startServerPromise ??= new Promise((resolve2, reject) => {
          this._server.once("error", reject);
          this._server.listen({
            port: this._port,
            host: this._host
          }, () => {
            api_1.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`);
            resolve2();
          });
        });
        return this._startServerPromise;
      }
      /**
       * Request handler that responds with the current state of metrics
       * @param _request Incoming HTTP request of server instance
       * @param response HTTP response object used to response to request
       */
      getMetricsRequestHandler(_request, response) {
        this._exportMetrics(response);
      }
      /**
       * Request handler used by http library to respond to incoming requests
       * for the current state of metrics by the Prometheus backend.
       *
       * @param request Incoming HTTP request to export server
       * @param response HTTP response object used to respond to request
       */
      _requestHandler = /* @__PURE__ */ __name((request4, response) => {
        if (request4.url != null && new url_1.URL(request4.url, this._baseUrl).pathname === this._endpoint) {
          this._exportMetrics(response);
        } else {
          this._notFound(response);
        }
      }, "_requestHandler");
      /**
       * Responds to incoming message with current state of all metrics.
       */
      _exportMetrics = /* @__PURE__ */ __name((response) => {
        response.statusCode = 200;
        response.setHeader("content-type", "text/plain");
        this.collect().then((collectionResult) => {
          const { resourceMetrics, errors } = collectionResult;
          if (errors.length) {
            api_1.diag.error("PrometheusExporter: metrics collection errors", ...errors);
          }
          response.end(this._serializer.serialize(resourceMetrics));
        }, (err) => {
          response.end(`# failed to export metrics: ${err}`);
        });
      }, "_exportMetrics");
      /**
       * Responds with 404 status code to all requests that do not match the configured endpoint.
       */
      _notFound = /* @__PURE__ */ __name((response) => {
        response.statusCode = 404;
        response.end();
      }, "_notFound");
    };
    exports.PrometheusExporter = PrometheusExporter;
  }
});

// node_modules/@opentelemetry/exporter-prometheus/build/src/index.js
var require_src24 = __commonJS({
  "node_modules/@opentelemetry/exporter-prometheus/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PrometheusSerializer = exports.PrometheusExporter = void 0;
    var PrometheusExporter_1 = require_PrometheusExporter();
    Object.defineProperty(exports, "PrometheusExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return PrometheusExporter_1.PrometheusExporter;
    }, "get") });
    var PrometheusSerializer_1 = require_PrometheusSerializer();
    Object.defineProperty(exports, "PrometheusSerializer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return PrometheusSerializer_1.PrometheusSerializer;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/version.js
var require_version8 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js
var require_OTLPTraceExporter3 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var otlp_transformer_1 = require_src10();
    var version_1 = require_version8();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var OTLPTraceExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPTraceExporter");
      }
      constructor(config = {}) {
        super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "TRACES", "v1/traces", {
          "User-Agent": `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`,
          "Content-Type": "application/x-protobuf"
        }), otlp_transformer_1.ProtobufTraceSerializer));
      }
    };
    exports.OTLPTraceExporter = OTLPTraceExporter2;
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js
var require_node14 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var OTLPTraceExporter_1 = require_OTLPTraceExporter3();
    Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return OTLPTraceExporter_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js
var require_platform13 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var node_1 = require_node14();
    Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js
var require_src25 = __commonJS({
  "node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OTLPTraceExporter = void 0;
    var platform_1 = require_platform13();
    Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.OTLPTraceExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/util.js
var require_util4 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/util.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prepareSend = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var http2 = __require("http");
    var https3 = __require("https");
    function prepareSend(urlStr, headers) {
      const url = new URL(urlStr);
      const reqOpts = Object.assign({
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...headers
        }
      });
      return /* @__PURE__ */ __name(function send(zipkinSpans, done) {
        if (zipkinSpans.length === 0) {
          api_1.diag.debug("Zipkin send with empty spans");
          return done({ code: core_1.ExportResultCode.SUCCESS });
        }
        const { request: request4 } = url.protocol === "http:" ? http2 : https3;
        const req = request4(url, reqOpts, (res) => {
          let rawData = "";
          res.on("data", (chunk) => {
            rawData += chunk;
          });
          res.on("end", () => {
            const statusCode = res.statusCode || 0;
            api_1.diag.debug(`Zipkin response status code: ${statusCode}, body: ${rawData}`);
            if (statusCode < 400) {
              return done({ code: core_1.ExportResultCode.SUCCESS });
            } else {
              return done({
                code: core_1.ExportResultCode.FAILED,
                error: new Error(`Got unexpected status code from zipkin: ${statusCode}`)
              });
            }
          });
        });
        req.on("error", (error) => {
          return done({
            code: core_1.ExportResultCode.FAILED,
            error
          });
        });
        const payload = JSON.stringify(zipkinSpans);
        api_1.diag.debug(`Zipkin request payload: ${payload}`);
        req.write(payload, "utf8");
        req.end();
      }, "send");
    }
    __name(prepareSend, "prepareSend");
    exports.prepareSend = prepareSend;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/index.js
var require_node15 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prepareSend = void 0;
    var util_1 = require_util4();
    Object.defineProperty(exports, "prepareSend", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return util_1.prepareSend;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/index.js
var require_platform14 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/platform/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prepareSend = void 0;
    var node_1 = require_node15();
    Object.defineProperty(exports, "prepareSend", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.prepareSend;
    }, "get") });
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/types.js
var require_types4 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/types.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SpanKind = void 0;
    var SpanKind2;
    (function(SpanKind3) {
      SpanKind3["CLIENT"] = "CLIENT";
      SpanKind3["SERVER"] = "SERVER";
      SpanKind3["CONSUMER"] = "CONSUMER";
      SpanKind3["PRODUCER"] = "PRODUCER";
    })(SpanKind2 = exports.SpanKind || (exports.SpanKind = {}));
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/transform.js
var require_transform = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/transform.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports._toZipkinAnnotations = exports._toZipkinTags = exports.toZipkinSpan = exports.defaultStatusErrorTagName = exports.defaultStatusCodeTagName = void 0;
    var api = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var zipkinTypes = require_types4();
    var ZIPKIN_SPAN_KIND_MAPPING = {
      [api.SpanKind.CLIENT]: zipkinTypes.SpanKind.CLIENT,
      [api.SpanKind.SERVER]: zipkinTypes.SpanKind.SERVER,
      [api.SpanKind.CONSUMER]: zipkinTypes.SpanKind.CONSUMER,
      [api.SpanKind.PRODUCER]: zipkinTypes.SpanKind.PRODUCER,
      // When absent, the span is local.
      [api.SpanKind.INTERNAL]: void 0
    };
    exports.defaultStatusCodeTagName = "otel.status_code";
    exports.defaultStatusErrorTagName = "error";
    function toZipkinSpan(span, serviceName, statusCodeTagName, statusErrorTagName) {
      const zipkinSpan = {
        traceId: span.spanContext().traceId,
        parentId: span.parentSpanContext?.spanId,
        name: span.name,
        id: span.spanContext().spanId,
        kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind],
        timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),
        duration: Math.round((0, core_1.hrTimeToMicroseconds)(span.duration)),
        localEndpoint: { serviceName },
        tags: _toZipkinTags(span, statusCodeTagName, statusErrorTagName),
        annotations: span.events.length ? _toZipkinAnnotations(span.events) : void 0
      };
      return zipkinSpan;
    }
    __name(toZipkinSpan, "toZipkinSpan");
    exports.toZipkinSpan = toZipkinSpan;
    function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount }, statusCodeTagName, statusErrorTagName) {
      const tags = {};
      for (const key of Object.keys(attributes)) {
        tags[key] = String(attributes[key]);
      }
      if (status.code !== api.SpanStatusCode.UNSET) {
        tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]);
      }
      if (status.code === api.SpanStatusCode.ERROR && status.message) {
        tags[statusErrorTagName] = status.message;
      }
      if (droppedAttributesCount) {
        tags["otel.dropped_attributes_count"] = String(droppedAttributesCount);
      }
      if (droppedEventsCount) {
        tags["otel.dropped_events_count"] = String(droppedEventsCount);
      }
      if (droppedLinksCount) {
        tags["otel.dropped_links_count"] = String(droppedLinksCount);
      }
      Object.keys(resource.attributes).forEach((name) => tags[name] = String(resource.attributes[name]));
      return tags;
    }
    __name(_toZipkinTags, "_toZipkinTags");
    exports._toZipkinTags = _toZipkinTags;
    function _toZipkinAnnotations(events) {
      return events.map((event) => ({
        timestamp: Math.round((0, core_1.hrTimeToMicroseconds)(event.time)),
        value: event.name
      }));
    }
    __name(_toZipkinAnnotations, "_toZipkinAnnotations");
    exports._toZipkinAnnotations = _toZipkinAnnotations;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/utils.js
var require_utils8 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prepareGetHeaders = void 0;
    function prepareGetHeaders(getExportRequestHeaders) {
      return function() {
        return getExportRequestHeaders();
      };
    }
    __name(prepareGetHeaders, "prepareGetHeaders");
    exports.prepareGetHeaders = prepareGetHeaders;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/zipkin.js
var require_zipkin = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/zipkin.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ZipkinExporter = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var index_1 = require_platform14();
    var transform_1 = require_transform();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var utils_1 = require_utils8();
    var ZipkinExporter = class {
      static {
        __name(this, "ZipkinExporter");
      }
      DEFAULT_SERVICE_NAME = "OpenTelemetry Service";
      _statusCodeTagName;
      _statusDescriptionTagName;
      _urlStr;
      _send;
      _getHeaders;
      _serviceName;
      _isShutdown;
      _sendingPromises = [];
      constructor(config = {}) {
        this._urlStr = config.url || ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_ZIPKIN_ENDPOINT") ?? "http://localhost:9411/api/v2/spans");
        this._send = (0, index_1.prepareSend)(this._urlStr, config.headers);
        this._serviceName = config.serviceName;
        this._statusCodeTagName = config.statusCodeTagName || transform_1.defaultStatusCodeTagName;
        this._statusDescriptionTagName = config.statusDescriptionTagName || transform_1.defaultStatusErrorTagName;
        this._isShutdown = false;
        if (typeof config.getExportRequestHeaders === "function") {
          this._getHeaders = (0, utils_1.prepareGetHeaders)(config.getExportRequestHeaders);
        } else {
          this._beforeSend = function() {
          };
        }
      }
      /**
       * Export spans.
       */
      export(spans, resultCallback) {
        const serviceName = String(this._serviceName || spans[0].resource.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || this.DEFAULT_SERVICE_NAME);
        api_1.diag.debug("Zipkin exporter export");
        if (this._isShutdown) {
          setTimeout(() => resultCallback({
            code: core_1.ExportResultCode.FAILED,
            error: new Error("Exporter has been shutdown")
          }));
          return;
        }
        const promise = new Promise((resolve2) => {
          this._sendSpans(spans, serviceName, (result) => {
            resolve2();
            resultCallback(result);
          });
        });
        this._sendingPromises.push(promise);
        const popPromise = /* @__PURE__ */ __name(() => {
          const index = this._sendingPromises.indexOf(promise);
          this._sendingPromises.splice(index, 1);
        }, "popPromise");
        promise.then(popPromise, popPromise);
      }
      /**
       * Shutdown exporter. Noop operation in this exporter.
       */
      shutdown() {
        api_1.diag.debug("Zipkin exporter shutdown");
        this._isShutdown = true;
        return this.forceFlush();
      }
      /**
       * Exports any pending spans in exporter
       */
      forceFlush() {
        return new Promise((resolve2, reject) => {
          Promise.all(this._sendingPromises).then(() => {
            resolve2();
          }, reject);
        });
      }
      /**
       * if user defines getExportRequestHeaders in config then this will be called
       * every time before send, otherwise it will be replaced with noop in
       * constructor
       * @default noop
       */
      _beforeSend() {
        if (this._getHeaders) {
          this._send = (0, index_1.prepareSend)(this._urlStr, this._getHeaders());
        }
      }
      /**
       * Transform spans and sends to Zipkin service.
       */
      _sendSpans(spans, serviceName, done) {
        const zipkinSpans = spans.map((span) => (0, transform_1.toZipkinSpan)(span, String(span.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || span.resource.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || serviceName), this._statusCodeTagName, this._statusDescriptionTagName));
        this._beforeSend();
        return this._send(zipkinSpans, (result) => {
          if (done) {
            return done(result);
          }
        });
      }
    };
    exports.ZipkinExporter = ZipkinExporter;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/index.js
var require_src26 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ZipkinExporter = exports.prepareSend = void 0;
    var platform_1 = require_platform14();
    Object.defineProperty(exports, "prepareSend", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return platform_1.prepareSend;
    }, "get") });
    var zipkin_1 = require_zipkin();
    Object.defineProperty(exports, "ZipkinExporter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return zipkin_1.ZipkinExporter;
    }, "get") });
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/common.js
var require_common2 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/common.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.B3_DEBUG_FLAG_KEY = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    exports.B3_DEBUG_FLAG_KEY = (0, api_1.createContextKey)("OpenTelemetry Context Key B3 Debug Flag");
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/constants.js
var require_constants3 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/constants.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.X_B3_FLAGS = exports.X_B3_PARENT_SPAN_ID = exports.X_B3_SAMPLED = exports.X_B3_SPAN_ID = exports.X_B3_TRACE_ID = exports.B3_CONTEXT_HEADER = void 0;
    exports.B3_CONTEXT_HEADER = "b3";
    exports.X_B3_TRACE_ID = "x-b3-traceid";
    exports.X_B3_SPAN_ID = "x-b3-spanid";
    exports.X_B3_SAMPLED = "x-b3-sampled";
    exports.X_B3_PARENT_SPAN_ID = "x-b3-parentspanid";
    exports.X_B3_FLAGS = "x-b3-flags";
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/B3MultiPropagator.js
var require_B3MultiPropagator = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/B3MultiPropagator.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.B3MultiPropagator = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var common_1 = require_common2();
    var constants_1 = require_constants3();
    var VALID_SAMPLED_VALUES = /* @__PURE__ */ new Set([true, "true", "True", "1", 1]);
    var VALID_UNSAMPLED_VALUES = /* @__PURE__ */ new Set([false, "false", "False", "0", 0]);
    function isValidSampledValue(sampled) {
      return sampled === api_1.TraceFlags.SAMPLED || sampled === api_1.TraceFlags.NONE;
    }
    __name(isValidSampledValue, "isValidSampledValue");
    function parseHeader(header) {
      return Array.isArray(header) ? header[0] : header;
    }
    __name(parseHeader, "parseHeader");
    function getHeaderValue(carrier, getter, key) {
      const header = getter.get(carrier, key);
      return parseHeader(header);
    }
    __name(getHeaderValue, "getHeaderValue");
    function getTraceId(carrier, getter) {
      const traceId = getHeaderValue(carrier, getter, constants_1.X_B3_TRACE_ID);
      if (typeof traceId === "string") {
        return traceId.padStart(32, "0");
      }
      return "";
    }
    __name(getTraceId, "getTraceId");
    function getSpanId2(carrier, getter) {
      const spanId = getHeaderValue(carrier, getter, constants_1.X_B3_SPAN_ID);
      if (typeof spanId === "string") {
        return spanId;
      }
      return "";
    }
    __name(getSpanId2, "getSpanId");
    function getDebug(carrier, getter) {
      const debug = getHeaderValue(carrier, getter, constants_1.X_B3_FLAGS);
      return debug === "1" ? "1" : void 0;
    }
    __name(getDebug, "getDebug");
    function getTraceFlags(carrier, getter) {
      const traceFlags = getHeaderValue(carrier, getter, constants_1.X_B3_SAMPLED);
      const debug = getDebug(carrier, getter);
      if (debug === "1" || VALID_SAMPLED_VALUES.has(traceFlags)) {
        return api_1.TraceFlags.SAMPLED;
      }
      if (traceFlags === void 0 || VALID_UNSAMPLED_VALUES.has(traceFlags)) {
        return api_1.TraceFlags.NONE;
      }
      return;
    }
    __name(getTraceFlags, "getTraceFlags");
    var B3MultiPropagator = class {
      static {
        __name(this, "B3MultiPropagator");
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        if (!spanContext || !(0, api_1.isSpanContextValid)(spanContext) || (0, core_1.isTracingSuppressed)(context2))
          return;
        const debug = context2.getValue(common_1.B3_DEBUG_FLAG_KEY);
        setter.set(carrier, constants_1.X_B3_TRACE_ID, spanContext.traceId);
        setter.set(carrier, constants_1.X_B3_SPAN_ID, spanContext.spanId);
        if (debug === "1") {
          setter.set(carrier, constants_1.X_B3_FLAGS, debug);
        } else if (spanContext.traceFlags !== void 0) {
          setter.set(carrier, constants_1.X_B3_SAMPLED, (api_1.TraceFlags.SAMPLED & spanContext.traceFlags) === api_1.TraceFlags.SAMPLED ? "1" : "0");
        }
      }
      extract(context2, carrier, getter) {
        const traceId = getTraceId(carrier, getter);
        const spanId = getSpanId2(carrier, getter);
        const traceFlags = getTraceFlags(carrier, getter);
        const debug = getDebug(carrier, getter);
        if ((0, api_1.isValidTraceId)(traceId) && (0, api_1.isValidSpanId)(spanId) && isValidSampledValue(traceFlags)) {
          context2 = context2.setValue(common_1.B3_DEBUG_FLAG_KEY, debug);
          return api_1.trace.setSpanContext(context2, {
            traceId,
            spanId,
            isRemote: true,
            traceFlags
          });
        }
        return context2;
      }
      fields() {
        return [
          constants_1.X_B3_TRACE_ID,
          constants_1.X_B3_SPAN_ID,
          constants_1.X_B3_FLAGS,
          constants_1.X_B3_SAMPLED,
          constants_1.X_B3_PARENT_SPAN_ID
        ];
      }
    };
    exports.B3MultiPropagator = B3MultiPropagator;
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/B3SinglePropagator.js
var require_B3SinglePropagator = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/B3SinglePropagator.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.B3SinglePropagator = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var common_1 = require_common2();
    var constants_1 = require_constants3();
    var B3_CONTEXT_REGEX = /((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/;
    var PADDING = "0".repeat(16);
    var SAMPLED_VALUES = /* @__PURE__ */ new Set(["d", "1"]);
    var DEBUG_STATE = "d";
    function convertToTraceId128(traceId) {
      return traceId.length === 32 ? traceId : `${PADDING}${traceId}`;
    }
    __name(convertToTraceId128, "convertToTraceId128");
    function convertToTraceFlags(samplingState) {
      if (samplingState && SAMPLED_VALUES.has(samplingState)) {
        return api_1.TraceFlags.SAMPLED;
      }
      return api_1.TraceFlags.NONE;
    }
    __name(convertToTraceFlags, "convertToTraceFlags");
    var B3SinglePropagator = class {
      static {
        __name(this, "B3SinglePropagator");
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        if (!spanContext || !(0, api_1.isSpanContextValid)(spanContext) || (0, core_1.isTracingSuppressed)(context2))
          return;
        const samplingState = context2.getValue(common_1.B3_DEBUG_FLAG_KEY) || spanContext.traceFlags & 1;
        const value = `${spanContext.traceId}-${spanContext.spanId}-${samplingState}`;
        setter.set(carrier, constants_1.B3_CONTEXT_HEADER, value);
      }
      extract(context2, carrier, getter) {
        const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER);
        const b3Context = Array.isArray(header) ? header[0] : header;
        if (typeof b3Context !== "string")
          return context2;
        const match = b3Context.match(B3_CONTEXT_REGEX);
        if (!match)
          return context2;
        const [, extractedTraceId, spanId, samplingState] = match;
        const traceId = convertToTraceId128(extractedTraceId);
        if (!(0, api_1.isValidTraceId)(traceId) || !(0, api_1.isValidSpanId)(spanId))
          return context2;
        const traceFlags = convertToTraceFlags(samplingState);
        if (samplingState === DEBUG_STATE) {
          context2 = context2.setValue(common_1.B3_DEBUG_FLAG_KEY, samplingState);
        }
        return api_1.trace.setSpanContext(context2, {
          traceId,
          spanId,
          isRemote: true,
          traceFlags
        });
      }
      fields() {
        return [constants_1.B3_CONTEXT_HEADER];
      }
    };
    exports.B3SinglePropagator = B3SinglePropagator;
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/types.js
var require_types5 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/types.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.B3InjectEncoding = void 0;
    var B3InjectEncoding;
    (function(B3InjectEncoding2) {
      B3InjectEncoding2[B3InjectEncoding2["SINGLE_HEADER"] = 0] = "SINGLE_HEADER";
      B3InjectEncoding2[B3InjectEncoding2["MULTI_HEADER"] = 1] = "MULTI_HEADER";
    })(B3InjectEncoding = exports.B3InjectEncoding || (exports.B3InjectEncoding = {}));
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/B3Propagator.js
var require_B3Propagator = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/B3Propagator.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.B3Propagator = void 0;
    var core_1 = require_src3();
    var B3MultiPropagator_1 = require_B3MultiPropagator();
    var B3SinglePropagator_1 = require_B3SinglePropagator();
    var constants_1 = require_constants3();
    var types_1 = require_types5();
    var B3Propagator = class {
      static {
        __name(this, "B3Propagator");
      }
      _b3MultiPropagator = new B3MultiPropagator_1.B3MultiPropagator();
      _b3SinglePropagator = new B3SinglePropagator_1.B3SinglePropagator();
      _inject;
      _fields;
      constructor(config = {}) {
        if (config.injectEncoding === types_1.B3InjectEncoding.MULTI_HEADER) {
          this._inject = this._b3MultiPropagator.inject;
          this._fields = this._b3MultiPropagator.fields();
        } else {
          this._inject = this._b3SinglePropagator.inject;
          this._fields = this._b3SinglePropagator.fields();
        }
      }
      inject(context2, carrier, setter) {
        if ((0, core_1.isTracingSuppressed)(context2)) {
          return;
        }
        this._inject(context2, carrier, setter);
      }
      extract(context2, carrier, getter) {
        const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER);
        const b3Context = Array.isArray(header) ? header[0] : header;
        if (b3Context) {
          return this._b3SinglePropagator.extract(context2, carrier, getter);
        } else {
          return this._b3MultiPropagator.extract(context2, carrier, getter);
        }
      }
      fields() {
        return this._fields;
      }
    };
    exports.B3Propagator = B3Propagator;
  }
});

// node_modules/@opentelemetry/propagator-b3/build/src/index.js
var require_src27 = __commonJS({
  "node_modules/@opentelemetry/propagator-b3/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.B3InjectEncoding = exports.X_B3_TRACE_ID = exports.X_B3_SPAN_ID = exports.X_B3_SAMPLED = exports.X_B3_PARENT_SPAN_ID = exports.X_B3_FLAGS = exports.B3_CONTEXT_HEADER = exports.B3Propagator = void 0;
    var B3Propagator_1 = require_B3Propagator();
    Object.defineProperty(exports, "B3Propagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return B3Propagator_1.B3Propagator;
    }, "get") });
    var constants_1 = require_constants3();
    Object.defineProperty(exports, "B3_CONTEXT_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.B3_CONTEXT_HEADER;
    }, "get") });
    Object.defineProperty(exports, "X_B3_FLAGS", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_FLAGS;
    }, "get") });
    Object.defineProperty(exports, "X_B3_PARENT_SPAN_ID", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_PARENT_SPAN_ID;
    }, "get") });
    Object.defineProperty(exports, "X_B3_SAMPLED", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_SAMPLED;
    }, "get") });
    Object.defineProperty(exports, "X_B3_SPAN_ID", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_SPAN_ID;
    }, "get") });
    Object.defineProperty(exports, "X_B3_TRACE_ID", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return constants_1.X_B3_TRACE_ID;
    }, "get") });
    var types_1 = require_types5();
    Object.defineProperty(exports, "B3InjectEncoding", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return types_1.B3InjectEncoding;
    }, "get") });
  }
});

// node_modules/@opentelemetry/propagator-jaeger/build/src/JaegerPropagator.js
var require_JaegerPropagator = __commonJS({
  "node_modules/@opentelemetry/propagator-jaeger/build/src/JaegerPropagator.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JaegerPropagator = exports.UBER_BAGGAGE_HEADER_PREFIX = exports.UBER_TRACE_ID_HEADER = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    exports.UBER_TRACE_ID_HEADER = "uber-trace-id";
    exports.UBER_BAGGAGE_HEADER_PREFIX = "uberctx";
    var JaegerPropagator = class {
      static {
        __name(this, "JaegerPropagator");
      }
      _jaegerTraceHeader;
      _jaegerBaggageHeaderPrefix;
      constructor(config) {
        if (typeof config === "string") {
          this._jaegerTraceHeader = config;
          this._jaegerBaggageHeaderPrefix = exports.UBER_BAGGAGE_HEADER_PREFIX;
        } else {
          this._jaegerTraceHeader = config?.customTraceHeader || exports.UBER_TRACE_ID_HEADER;
          this._jaegerBaggageHeaderPrefix = config?.customBaggageHeaderPrefix || exports.UBER_BAGGAGE_HEADER_PREFIX;
        }
      }
      inject(context2, carrier, setter) {
        const spanContext = api_1.trace.getSpanContext(context2);
        const baggage = api_1.propagation.getBaggage(context2);
        if (spanContext && (0, core_1.isTracingSuppressed)(context2) === false) {
          const traceFlags = `0${(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`;
          setter.set(carrier, this._jaegerTraceHeader, `${spanContext.traceId}:${spanContext.spanId}:0:${traceFlags}`);
        }
        if (baggage) {
          for (const [key, entry] of baggage.getAllEntries()) {
            setter.set(carrier, `${this._jaegerBaggageHeaderPrefix}-${key}`, encodeURIComponent(entry.value));
          }
        }
      }
      extract(context2, carrier, getter) {
        const uberTraceIdHeader = getter.get(carrier, this._jaegerTraceHeader);
        const uberTraceId = Array.isArray(uberTraceIdHeader) ? uberTraceIdHeader[0] : uberTraceIdHeader;
        const baggageValues = getter.keys(carrier).filter((key) => key.startsWith(`${this._jaegerBaggageHeaderPrefix}-`)).map((key) => {
          const value = getter.get(carrier, key);
          return {
            key: key.substring(this._jaegerBaggageHeaderPrefix.length + 1),
            value: Array.isArray(value) ? value[0] : value
          };
        });
        let newContext = context2;
        if (typeof uberTraceId === "string") {
          const spanContext = deserializeSpanContext(uberTraceId);
          if (spanContext) {
            newContext = api_1.trace.setSpanContext(newContext, spanContext);
          }
        }
        if (baggageValues.length === 0)
          return newContext;
        let currentBaggage = api_1.propagation.getBaggage(context2) ?? api_1.propagation.createBaggage();
        for (const baggageEntry of baggageValues) {
          if (baggageEntry.value === void 0)
            continue;
          currentBaggage = currentBaggage.setEntry(baggageEntry.key, {
            value: decodeURIComponent(baggageEntry.value)
          });
        }
        newContext = api_1.propagation.setBaggage(newContext, currentBaggage);
        return newContext;
      }
      fields() {
        return [this._jaegerTraceHeader];
      }
    };
    exports.JaegerPropagator = JaegerPropagator;
    var VALID_HEX_RE = /^[0-9a-f]{1,2}$/i;
    function deserializeSpanContext(serializedString) {
      const headers = decodeURIComponent(serializedString).split(":");
      if (headers.length !== 4) {
        return null;
      }
      const [_traceId, _spanId, , flags] = headers;
      const traceId = _traceId.padStart(32, "0");
      const spanId = _spanId.padStart(16, "0");
      const traceFlags = VALID_HEX_RE.test(flags) ? parseInt(flags, 16) & 1 : 1;
      return { traceId, spanId, isRemote: true, traceFlags };
    }
    __name(deserializeSpanContext, "deserializeSpanContext");
  }
});

// node_modules/@opentelemetry/propagator-jaeger/build/src/index.js
var require_src28 = __commonJS({
  "node_modules/@opentelemetry/propagator-jaeger/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UBER_TRACE_ID_HEADER = exports.UBER_BAGGAGE_HEADER_PREFIX = exports.JaegerPropagator = void 0;
    var JaegerPropagator_1 = require_JaegerPropagator();
    Object.defineProperty(exports, "JaegerPropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.JaegerPropagator;
    }, "get") });
    Object.defineProperty(exports, "UBER_BAGGAGE_HEADER_PREFIX", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.UBER_BAGGAGE_HEADER_PREFIX;
    }, "get") });
    Object.defineProperty(exports, "UBER_TRACE_ID_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.UBER_TRACE_ID_HEADER;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-node/build/src/utils.js
var require_utils9 = __commonJS({
  "node_modules/@opentelemetry/sdk-node/build/src/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getPropagatorFromEnv = exports.getSpanProcessorsFromEnv = exports.getOtlpProtocolFromEnv = exports.filterBlanksAndNulls = exports.getResourceDetectorsFromEnv = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var exporter_trace_otlp_proto_1 = require_src25();
    var exporter_trace_otlp_http_1 = require_src15();
    var exporter_trace_otlp_grpc_1 = require_src11();
    var exporter_zipkin_1 = require_src26();
    var resources_1 = require_src8();
    var sdk_trace_base_1 = require_src19();
    var propagator_b3_1 = require_src27();
    var propagator_jaeger_1 = require_src28();
    var RESOURCE_DETECTOR_ENVIRONMENT = "env";
    var RESOURCE_DETECTOR_HOST = "host";
    var RESOURCE_DETECTOR_OS = "os";
    var RESOURCE_DETECTOR_PROCESS = "process";
    var RESOURCE_DETECTOR_SERVICE_INSTANCE_ID = "serviceinstance";
    function getResourceDetectorsFromEnv() {
      const resourceDetectors = /* @__PURE__ */ new Map([
        [RESOURCE_DETECTOR_ENVIRONMENT, resources_1.envDetector],
        [RESOURCE_DETECTOR_HOST, resources_1.hostDetector],
        [RESOURCE_DETECTOR_OS, resources_1.osDetector],
        [RESOURCE_DETECTOR_SERVICE_INSTANCE_ID, resources_1.serviceInstanceIdDetector],
        [RESOURCE_DETECTOR_PROCESS, resources_1.processDetector]
      ]);
      const resourceDetectorsFromEnv = (0, core_1.getStringListFromEnv)("OTEL_NODE_RESOURCE_DETECTORS") ?? ["all"];
      if (resourceDetectorsFromEnv.includes("all")) {
        return [...resourceDetectors.values()].flat();
      }
      if (resourceDetectorsFromEnv.includes("none")) {
        return [];
      }
      return resourceDetectorsFromEnv.flatMap((detector) => {
        const resourceDetector = resourceDetectors.get(detector);
        if (!resourceDetector) {
          api_1.diag.warn(`Invalid resource detector "${detector}" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS`);
        }
        return resourceDetector || [];
      });
    }
    __name(getResourceDetectorsFromEnv, "getResourceDetectorsFromEnv");
    exports.getResourceDetectorsFromEnv = getResourceDetectorsFromEnv;
    function filterBlanksAndNulls(list) {
      return list.map((item) => item.trim()).filter((s) => s !== "null" && s !== "");
    }
    __name(filterBlanksAndNulls, "filterBlanksAndNulls");
    exports.filterBlanksAndNulls = filterBlanksAndNulls;
    function getOtlpProtocolFromEnv() {
      return (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf";
    }
    __name(getOtlpProtocolFromEnv, "getOtlpProtocolFromEnv");
    exports.getOtlpProtocolFromEnv = getOtlpProtocolFromEnv;
    function getOtlpExporterFromEnv() {
      const protocol = getOtlpProtocolFromEnv();
      switch (protocol) {
        case "grpc":
          return new exporter_trace_otlp_grpc_1.OTLPTraceExporter();
        case "http/json":
          return new exporter_trace_otlp_http_1.OTLPTraceExporter();
        case "http/protobuf":
          return new exporter_trace_otlp_proto_1.OTLPTraceExporter();
        default:
          api_1.diag.warn(`Unsupported OTLP traces protocol: ${protocol}. Using http/protobuf.`);
          return new exporter_trace_otlp_proto_1.OTLPTraceExporter();
      }
    }
    __name(getOtlpExporterFromEnv, "getOtlpExporterFromEnv");
    function getJaegerExporter() {
      try {
        const { JaegerExporter } = __require("@opentelemetry/exporter-jaeger");
        return new JaegerExporter();
      } catch (e) {
        throw new Error(`Could not instantiate JaegerExporter. This could be due to the JaegerExporter's lack of support for bundling. If possible, use @opentelemetry/exporter-trace-otlp-proto instead. Original Error: ${e}`);
      }
    }
    __name(getJaegerExporter, "getJaegerExporter");
    function getSpanProcessorsFromEnv() {
      const exportersMap = /* @__PURE__ */ new Map([
        ["otlp", () => getOtlpExporterFromEnv()],
        ["zipkin", () => new exporter_zipkin_1.ZipkinExporter()],
        ["console", () => new sdk_trace_base_1.ConsoleSpanExporter()],
        ["jaeger", () => getJaegerExporter()]
      ]);
      const exporters = [];
      const processors = [];
      let traceExportersList = filterBlanksAndNulls(Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_TRACES_EXPORTER"))));
      if (traceExportersList[0] === "none") {
        api_1.diag.warn('OTEL_TRACES_EXPORTER contains "none". SDK will not be initialized.');
        return [];
      }
      if (traceExportersList.length === 0) {
        api_1.diag.debug("OTEL_TRACES_EXPORTER is empty. Using default otlp exporter.");
        traceExportersList = ["otlp"];
      } else if (traceExportersList.length > 1 && traceExportersList.includes("none")) {
        api_1.diag.warn('OTEL_TRACES_EXPORTER contains "none" along with other exporters. Using default otlp exporter.');
        traceExportersList = ["otlp"];
      }
      for (const name of traceExportersList) {
        const exporter = exportersMap.get(name)?.();
        if (exporter) {
          exporters.push(exporter);
        } else {
          api_1.diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${name}.`);
        }
      }
      for (const exp of exporters) {
        if (exp instanceof sdk_trace_base_1.ConsoleSpanExporter) {
          processors.push(new sdk_trace_base_1.SimpleSpanProcessor(exp));
        } else {
          processors.push(new sdk_trace_base_1.BatchSpanProcessor(exp));
        }
      }
      if (exporters.length === 0) {
        api_1.diag.warn("Unable to set up trace exporter(s) due to invalid exporter and/or protocol values.");
      }
      return processors;
    }
    __name(getSpanProcessorsFromEnv, "getSpanProcessorsFromEnv");
    exports.getSpanProcessorsFromEnv = getSpanProcessorsFromEnv;
    function getPropagatorFromEnv() {
      const propagatorsEnvVarValue = (0, core_1.getStringListFromEnv)("OTEL_PROPAGATORS");
      if (propagatorsEnvVarValue == null) {
        return void 0;
      }
      const propagatorsFactory = /* @__PURE__ */ new Map([
        ["tracecontext", () => new core_1.W3CTraceContextPropagator()],
        ["baggage", () => new core_1.W3CBaggagePropagator()],
        ["b3", () => new propagator_b3_1.B3Propagator()],
        [
          "b3multi",
          () => new propagator_b3_1.B3Propagator({ injectEncoding: propagator_b3_1.B3InjectEncoding.MULTI_HEADER })
        ],
        ["jaeger", () => new propagator_jaeger_1.JaegerPropagator()]
      ]);
      const uniquePropagatorNames = Array.from(new Set(propagatorsEnvVarValue));
      const propagators = uniquePropagatorNames.map((name) => {
        const propagator = propagatorsFactory.get(name)?.();
        if (!propagator) {
          api_1.diag.warn(`Propagator "${name}" requested through environment variable is unavailable.`);
          return void 0;
        }
        return propagator;
      });
      const validPropagators = propagators.reduce((list, item) => {
        if (item) {
          list.push(item);
        }
        return list;
      }, []);
      if (validPropagators.length === 0) {
        return null;
      } else if (uniquePropagatorNames.length === 1) {
        return validPropagators[0];
      } else {
        return new core_1.CompositePropagator({
          propagators: validPropagators
        });
      }
    }
    __name(getPropagatorFromEnv, "getPropagatorFromEnv");
    exports.getPropagatorFromEnv = getPropagatorFromEnv;
  }
});

// node_modules/@opentelemetry/sdk-node/build/src/sdk.js
var require_sdk = __commonJS({
  "node_modules/@opentelemetry/sdk-node/build/src/sdk.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodeSDK = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var api_logs_1 = require_src2();
    var instrumentation_1 = require_src21();
    var resources_1 = require_src8();
    var sdk_logs_1 = require_src17();
    var exporter_logs_otlp_http_1 = require_src16();
    var exporter_logs_otlp_grpc_1 = require_src12();
    var exporter_logs_otlp_proto_1 = require_src22();
    var exporter_metrics_otlp_grpc_1 = require_src14();
    var exporter_metrics_otlp_proto_1 = require_src23();
    var exporter_metrics_otlp_http_1 = require_src13();
    var exporter_prometheus_1 = require_src24();
    var sdk_metrics_1 = require_src9();
    var sdk_trace_base_1 = require_src19();
    var sdk_trace_node_1 = require_src20();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src3();
    var utils_1 = require_utils9();
    function getValueInMillis(envName, defaultValue) {
      return parseInt(process.env[envName] || "") || defaultValue;
    }
    __name(getValueInMillis, "getValueInMillis");
    function configureMetricProviderFromEnv() {
      const metricReaders = [];
      const enabledExporters = (0, core_1.getStringListFromEnv)("OTEL_METRICS_EXPORTER");
      if (!enabledExporters) {
        return metricReaders;
      }
      if (enabledExporters.length === 0) {
        api_1.diag.debug("OTEL_METRICS_EXPORTER is empty. Using default otlp exporter.");
      }
      if (enabledExporters.includes("none")) {
        api_1.diag.info(`OTEL_METRICS_EXPORTER contains "none". Metric provider will not be initialized.`);
        return metricReaders;
      }
      enabledExporters.forEach((exporter) => {
        if (exporter === "otlp") {
          const protocol = process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim() || process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim();
          const exportIntervalMillis = getValueInMillis("OTEL_METRIC_EXPORT_INTERVAL", 6e4);
          const exportTimeoutMillis = getValueInMillis("OTEL_METRIC_EXPORT_TIMEOUT", 3e4);
          switch (protocol) {
            case "grpc":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_grpc_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            case "http/json":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_http_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            case "http/protobuf":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_proto_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            default:
              api_1.diag.warn(`Unsupported OTLP metrics protocol: "${protocol}". Using http/protobuf.`);
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_proto_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
          }
        } else if (exporter === "console") {
          metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
            exporter: new sdk_metrics_1.ConsoleMetricExporter()
          }));
        } else if (exporter === "prometheus") {
          metricReaders.push(new exporter_prometheus_1.PrometheusExporter());
        } else {
          api_1.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${exporter}". Supported values are: otlp, console, prometheus, none.`);
        }
      });
      return metricReaders;
    }
    __name(configureMetricProviderFromEnv, "configureMetricProviderFromEnv");
    var NodeSDK2 = class {
      static {
        __name(this, "NodeSDK");
      }
      _tracerProviderConfig;
      _loggerProviderConfig;
      _meterProviderConfig;
      _instrumentations;
      _resource;
      _resourceDetectors;
      _autoDetectResources;
      _tracerProvider;
      _loggerProvider;
      _meterProvider;
      _serviceName;
      _configuration;
      _disabled;
      /**
       * Create a new NodeJS SDK instance
       */
      constructor(configuration = {}) {
        if ((0, core_1.getBooleanFromEnv)("OTEL_SDK_DISABLED")) {
          this._disabled = true;
        }
        const logLevel = (0, core_1.getStringFromEnv)("OTEL_LOG_LEVEL");
        if (logLevel != null) {
          api_1.diag.setLogger(new api_1.DiagConsoleLogger(), {
            logLevel: (0, core_1.diagLogLevelFromString)(logLevel)
          });
        }
        this._configuration = configuration;
        this._resource = configuration.resource ?? (0, resources_1.defaultResource)();
        this._autoDetectResources = configuration.autoDetectResources ?? true;
        if (!this._autoDetectResources) {
          this._resourceDetectors = [];
        } else if (configuration.resourceDetectors != null) {
          this._resourceDetectors = configuration.resourceDetectors;
        } else if ((0, core_1.getStringFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")) {
          this._resourceDetectors = (0, utils_1.getResourceDetectorsFromEnv)();
        } else {
          this._resourceDetectors = [resources_1.envDetector, resources_1.processDetector, resources_1.hostDetector];
        }
        this._serviceName = configuration.serviceName;
        if (configuration.traceExporter || configuration.spanProcessor || configuration.spanProcessors) {
          const tracerProviderConfig = {};
          if (configuration.sampler) {
            tracerProviderConfig.sampler = configuration.sampler;
          }
          if (configuration.spanLimits) {
            tracerProviderConfig.spanLimits = configuration.spanLimits;
          }
          if (configuration.idGenerator) {
            tracerProviderConfig.idGenerator = configuration.idGenerator;
          }
          if (configuration.spanProcessor) {
            api_1.diag.warn("The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead.");
          }
          const spanProcessor = configuration.spanProcessor ?? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          new sdk_trace_base_1.BatchSpanProcessor(configuration.traceExporter);
          const spanProcessors = configuration.spanProcessors ?? [spanProcessor];
          this._tracerProviderConfig = {
            tracerConfig: tracerProviderConfig,
            spanProcessors,
            contextManager: configuration.contextManager,
            textMapPropagator: configuration.textMapPropagator
          };
        }
        if (configuration.logRecordProcessors) {
          this._loggerProviderConfig = {
            logRecordProcessors: configuration.logRecordProcessors
          };
        } else if (configuration.logRecordProcessor) {
          this._loggerProviderConfig = {
            logRecordProcessors: [configuration.logRecordProcessor]
          };
          api_1.diag.warn("The 'logRecordProcessor' option is deprecated. Please use 'logRecordProcessors' instead.");
        } else {
          this.configureLoggerProviderFromEnv();
        }
        if (configuration.metricReader || configuration.views) {
          const meterProviderConfig = {};
          if (configuration.metricReader) {
            meterProviderConfig.reader = configuration.metricReader;
          }
          if (configuration.views) {
            meterProviderConfig.views = configuration.views;
          }
          this._meterProviderConfig = meterProviderConfig;
        }
        this._instrumentations = configuration.instrumentations?.flat() ?? [];
      }
      /**
       * Call this method to construct SDK components and register them with the OpenTelemetry API.
       */
      start() {
        if (this._disabled) {
          return;
        }
        (0, instrumentation_1.registerInstrumentations)({
          instrumentations: this._instrumentations
        });
        if (this._autoDetectResources) {
          const internalConfig = {
            detectors: this._resourceDetectors
          };
          this._resource = this._resource.merge((0, resources_1.detectResources)(internalConfig));
        }
        this._resource = this._serviceName === void 0 ? this._resource : this._resource.merge((0, resources_1.resourceFromAttributes)({
          [semantic_conventions_1.ATTR_SERVICE_NAME]: this._serviceName
        }));
        const spanProcessors = this._tracerProviderConfig ? this._tracerProviderConfig.spanProcessors : (0, utils_1.getSpanProcessorsFromEnv)();
        this._tracerProvider = new sdk_trace_node_1.NodeTracerProvider({
          ...this._configuration,
          resource: this._resource,
          spanProcessors
        });
        if (spanProcessors.length > 0) {
          this._tracerProvider.register({
            contextManager: this._tracerProviderConfig?.contextManager ?? // _tracerProviderConfig may be undefined if trace-specific settings are not provided - fall back to raw config
            this._configuration?.contextManager,
            propagator: this._tracerProviderConfig?.textMapPropagator ?? (0, utils_1.getPropagatorFromEnv)()
          });
        }
        if (this._loggerProviderConfig) {
          const loggerProvider = new sdk_logs_1.LoggerProvider({
            resource: this._resource,
            processors: this._loggerProviderConfig.logRecordProcessors
          });
          this._loggerProvider = loggerProvider;
          api_logs_1.logs.setGlobalLoggerProvider(loggerProvider);
        }
        const metricReadersFromEnv = configureMetricProviderFromEnv();
        if (this._meterProviderConfig || metricReadersFromEnv.length > 0) {
          const readers = [];
          if (this._meterProviderConfig?.reader) {
            readers.push(this._meterProviderConfig.reader);
          }
          if (readers.length === 0) {
            metricReadersFromEnv.forEach((r) => readers.push(r));
          }
          const meterProvider = new sdk_metrics_1.MeterProvider({
            resource: this._resource,
            views: this._meterProviderConfig?.views ?? [],
            readers
          });
          this._meterProvider = meterProvider;
          api_1.metrics.setGlobalMeterProvider(meterProvider);
          for (const instrumentation of this._instrumentations) {
            instrumentation.setMeterProvider(api_1.metrics.getMeterProvider());
          }
        }
      }
      shutdown() {
        const promises = [];
        if (this._tracerProvider) {
          promises.push(this._tracerProvider.shutdown());
        }
        if (this._loggerProvider) {
          promises.push(this._loggerProvider.shutdown());
        }
        if (this._meterProvider) {
          promises.push(this._meterProvider.shutdown());
        }
        return Promise.all(promises).then(() => {
        });
      }
      configureLoggerProviderFromEnv() {
        const enabledExporters = (0, core_1.getStringListFromEnv)("OTEL_LOGS_EXPORTER") ?? [];
        if (enabledExporters.length === 0) {
          api_1.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter.");
          enabledExporters.push("otlp");
        }
        if (enabledExporters.includes("none")) {
          api_1.diag.info(`OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.`);
          return;
        }
        const exporters = [];
        enabledExporters.forEach((exporter) => {
          if (exporter === "otlp") {
            const protocol = ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim();
            switch (protocol) {
              case "grpc":
                exporters.push(new exporter_logs_otlp_grpc_1.OTLPLogExporter());
                break;
              case "http/json":
                exporters.push(new exporter_logs_otlp_http_1.OTLPLogExporter());
                break;
              case "http/protobuf":
                exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter());
                break;
              case void 0:
              case "":
                exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter());
                break;
              default:
                api_1.diag.warn(`Unsupported OTLP logs protocol: "${protocol}". Using http/protobuf.`);
                exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter());
            }
          } else if (exporter === "console") {
            exporters.push(new sdk_logs_1.ConsoleLogRecordExporter());
          } else {
            api_1.diag.warn(`Unsupported OTEL_LOGS_EXPORTER value: "${exporter}". Supported values are: otlp, console, none.`);
          }
        });
        if (exporters.length > 0) {
          this._loggerProviderConfig = {
            logRecordProcessors: exporters.map((exporter) => {
              if (exporter instanceof sdk_logs_1.ConsoleLogRecordExporter) {
                return new sdk_logs_1.SimpleLogRecordProcessor(exporter);
              } else {
                return new sdk_logs_1.BatchLogRecordProcessor(exporter);
              }
            })
          };
        }
      }
    };
    exports.NodeSDK = NodeSDK2;
  }
});

// node_modules/@opentelemetry/sdk-node/build/src/index.js
var require_src29 = __commonJS({
  "node_modules/@opentelemetry/sdk-node/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodeSDK = exports.tracing = exports.resources = exports.node = exports.metrics = exports.logs = exports.core = exports.contextBase = exports.api = void 0;
    exports.api = (init_esm(), __toCommonJS(esm_exports));
    exports.contextBase = (init_esm(), __toCommonJS(esm_exports));
    exports.core = require_src3();
    exports.logs = require_src17();
    exports.metrics = require_src9();
    exports.node = require_src20();
    exports.resources = require_src8();
    exports.tracing = require_src19();
    var sdk_1 = require_sdk();
    Object.defineProperty(exports, "NodeSDK", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return sdk_1.NodeSDK;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/version.js
var require_version9 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VERSION = void 0;
    exports.VERSION = "0.203.0";
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/semconv.js
var require_semconv3 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/semconv.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HTTP_FLAVOR_VALUE_HTTP_1_1 = exports.NET_TRANSPORT_VALUE_IP_UDP = exports.NET_TRANSPORT_VALUE_IP_TCP = exports.ATTR_NET_TRANSPORT = exports.ATTR_NET_PEER_PORT = exports.ATTR_NET_PEER_NAME = exports.ATTR_NET_PEER_IP = exports.ATTR_NET_HOST_PORT = exports.ATTR_NET_HOST_NAME = exports.ATTR_NET_HOST_IP = exports.ATTR_HTTP_USER_AGENT = exports.ATTR_HTTP_URL = exports.ATTR_HTTP_TARGET = exports.ATTR_HTTP_STATUS_CODE = exports.ATTR_HTTP_SERVER_NAME = exports.ATTR_HTTP_SCHEME = exports.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.ATTR_HTTP_RESPONSE_CONTENT_LENGTH = exports.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.ATTR_HTTP_REQUEST_CONTENT_LENGTH = exports.ATTR_HTTP_METHOD = exports.ATTR_HTTP_HOST = exports.ATTR_HTTP_FLAVOR = exports.ATTR_HTTP_CLIENT_IP = exports.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST = exports.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT = exports.ATTR_USER_AGENT_SYNTHETIC_TYPE = void 0;
    exports.ATTR_USER_AGENT_SYNTHETIC_TYPE = "user_agent.synthetic.type";
    exports.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT = "bot";
    exports.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST = "test";
    exports.ATTR_HTTP_CLIENT_IP = "http.client_ip";
    exports.ATTR_HTTP_FLAVOR = "http.flavor";
    exports.ATTR_HTTP_HOST = "http.host";
    exports.ATTR_HTTP_METHOD = "http.method";
    exports.ATTR_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length";
    exports.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed";
    exports.ATTR_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length";
    exports.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed";
    exports.ATTR_HTTP_SCHEME = "http.scheme";
    exports.ATTR_HTTP_SERVER_NAME = "http.server_name";
    exports.ATTR_HTTP_STATUS_CODE = "http.status_code";
    exports.ATTR_HTTP_TARGET = "http.target";
    exports.ATTR_HTTP_URL = "http.url";
    exports.ATTR_HTTP_USER_AGENT = "http.user_agent";
    exports.ATTR_NET_HOST_IP = "net.host.ip";
    exports.ATTR_NET_HOST_NAME = "net.host.name";
    exports.ATTR_NET_HOST_PORT = "net.host.port";
    exports.ATTR_NET_PEER_IP = "net.peer.ip";
    exports.ATTR_NET_PEER_NAME = "net.peer.name";
    exports.ATTR_NET_PEER_PORT = "net.peer.port";
    exports.ATTR_NET_TRANSPORT = "net.transport";
    exports.NET_TRANSPORT_VALUE_IP_TCP = "ip_tcp";
    exports.NET_TRANSPORT_VALUE_IP_UDP = "ip_udp";
    exports.HTTP_FLAVOR_VALUE_HTTP_1_1 = "1.1";
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/enums/AttributeNames.js
var require_AttributeNames = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/enums/AttributeNames.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AttributeNames = void 0;
    var AttributeNames;
    (function(AttributeNames2) {
      AttributeNames2["HTTP_ERROR_NAME"] = "http.error_name";
      AttributeNames2["HTTP_ERROR_MESSAGE"] = "http.error_message";
      AttributeNames2["HTTP_STATUS_TEXT"] = "http.status_text";
    })(AttributeNames = exports.AttributeNames || (exports.AttributeNames = {}));
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/internal-types.js
var require_internal_types2 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/internal-types.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SYNTHETIC_BOT_NAMES = exports.SYNTHETIC_TEST_NAMES = void 0;
    exports.SYNTHETIC_TEST_NAMES = ["alwayson"];
    exports.SYNTHETIC_BOT_NAMES = ["googlebot", "bingbot"];
  }
});

// node_modules/forwarded-parse/lib/error.js
var require_error2 = __commonJS({
  "node_modules/forwarded-parse/lib/error.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var util = __require("util");
    function ParseError(message, input) {
      Error.captureStackTrace(this, ParseError);
      this.name = this.constructor.name;
      this.message = message;
      this.input = input;
    }
    __name(ParseError, "ParseError");
    util.inherits(ParseError, Error);
    module.exports = ParseError;
  }
});

// node_modules/forwarded-parse/lib/ascii.js
var require_ascii2 = __commonJS({
  "node_modules/forwarded-parse/lib/ascii.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    function isDelimiter(code) {
      return code === 34 || code === 40 || code === 41 || code === 44 || code === 47 || code >= 58 && code <= 64 || code >= 91 && code <= 93 || code === 123 || code === 125;
    }
    __name(isDelimiter, "isDelimiter");
    function isTokenChar(code) {
      return code === 33 || code >= 35 && code <= 39 || code === 42 || code === 43 || code === 45 || code === 46 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 94 && code <= 122 || code === 124 || code === 126;
    }
    __name(isTokenChar, "isTokenChar");
    function isPrint(code) {
      return code >= 32 && code <= 126;
    }
    __name(isPrint, "isPrint");
    function isExtended(code) {
      return code >= 128 && code <= 255;
    }
    __name(isExtended, "isExtended");
    module.exports = {
      isDelimiter,
      isTokenChar,
      isExtended,
      isPrint
    };
  }
});

// node_modules/forwarded-parse/index.js
var require_forwarded_parse = __commonJS({
  "node_modules/forwarded-parse/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var util = __require("util");
    var ParseError = require_error2();
    var ascii = require_ascii2();
    var isDelimiter = ascii.isDelimiter;
    var isTokenChar = ascii.isTokenChar;
    var isExtended = ascii.isExtended;
    var isPrint = ascii.isPrint;
    function decode(str) {
      return str.replace(/\\(.)/g, "$1");
    }
    __name(decode, "decode");
    function unexpectedCharacterMessage(header, position) {
      return util.format(
        "Unexpected character '%s' at index %d",
        header.charAt(position),
        position
      );
    }
    __name(unexpectedCharacterMessage, "unexpectedCharacterMessage");
    function parse(header) {
      var mustUnescape = false;
      var isEscaping = false;
      var inQuotes = false;
      var forwarded = {};
      var output = [];
      var start = -1;
      var end = -1;
      var parameter;
      var code;
      for (var i = 0; i < header.length; i++) {
        code = header.charCodeAt(i);
        if (parameter === void 0) {
          if (i !== 0 && start === -1 && (code === 32 || code === 9)) {
            continue;
          }
          if (isTokenChar(code)) {
            if (start === -1) start = i;
          } else if (code === 61 && start !== -1) {
            parameter = header.slice(start, i).toLowerCase();
            start = -1;
          } else {
            throw new ParseError(unexpectedCharacterMessage(header, i), header);
          }
        } else {
          if (isEscaping && (code === 9 || isPrint(code) || isExtended(code))) {
            isEscaping = false;
          } else if (isTokenChar(code)) {
            if (end !== -1) {
              throw new ParseError(unexpectedCharacterMessage(header, i), header);
            }
            if (start === -1) start = i;
          } else if (isDelimiter(code) || isExtended(code)) {
            if (inQuotes) {
              if (code === 34) {
                inQuotes = false;
                end = i;
              } else if (code === 92) {
                if (start === -1) start = i;
                isEscaping = mustUnescape = true;
              } else if (start === -1) {
                start = i;
              }
            } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
              inQuotes = true;
            } else if ((code === 44 || code === 59) && (start !== -1 || end !== -1)) {
              if (start !== -1) {
                if (end === -1) end = i;
                forwarded[parameter] = mustUnescape ? decode(header.slice(start, end)) : header.slice(start, end);
              } else {
                forwarded[parameter] = "";
              }
              if (code === 44) {
                output.push(forwarded);
                forwarded = {};
              }
              parameter = void 0;
              start = end = -1;
            } else {
              throw new ParseError(unexpectedCharacterMessage(header, i), header);
            }
          } else if (code === 32 || code === 9) {
            if (end !== -1) continue;
            if (inQuotes) {
              if (start === -1) start = i;
            } else if (start !== -1) {
              end = i;
            } else {
              throw new ParseError(unexpectedCharacterMessage(header, i), header);
            }
          } else {
            throw new ParseError(unexpectedCharacterMessage(header, i), header);
          }
        }
      }
      if (parameter === void 0 || inQuotes || start === -1 && end === -1 || code === 32 || code === 9) {
        throw new ParseError("Unexpected end of input", header);
      }
      if (start !== -1) {
        if (end === -1) end = i;
        forwarded[parameter] = mustUnescape ? decode(header.slice(start, end)) : header.slice(start, end);
      } else {
        forwarded[parameter] = "";
      }
      output.push(forwarded);
      return output;
    }
    __name(parse, "parse");
    module.exports = parse;
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/utils.js
var require_utils10 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/utils.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.headerCapture = exports.getIncomingStableRequestMetricAttributesOnResponse = exports.getIncomingRequestMetricAttributesOnResponse = exports.getIncomingRequestAttributesOnResponse = exports.getIncomingRequestMetricAttributes = exports.getIncomingRequestAttributes = exports.getRemoteClientAddress = exports.getOutgoingStableRequestMetricAttributesOnResponse = exports.getOutgoingRequestMetricAttributesOnResponse = exports.getOutgoingRequestAttributesOnResponse = exports.setAttributesFromHttpKind = exports.getOutgoingRequestMetricAttributes = exports.getOutgoingRequestAttributes = exports.extractHostnameAndPort = exports.isValidOptionsType = exports.getRequestInfo = exports.isCompressed = exports.setResponseContentLengthAttribute = exports.setRequestContentLengthAttribute = exports.setSpanWithError = exports.satisfiesPattern = exports.parseResponseStatus = exports.getAbsoluteUrl = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var semconv_1 = require_semconv3();
    var core_1 = require_src3();
    var instrumentation_1 = require_src21();
    var url = __require("url");
    var AttributeNames_1 = require_AttributeNames();
    var internal_types_1 = require_internal_types2();
    var forwardedParse = require_forwarded_parse();
    var getAbsoluteUrl = /* @__PURE__ */ __name((requestUrl, headers, fallbackProtocol = "http:") => {
      const reqUrlObject = requestUrl || {};
      const protocol = reqUrlObject.protocol || fallbackProtocol;
      const port = (reqUrlObject.port || "").toString();
      const path11 = reqUrlObject.path || "/";
      let host = reqUrlObject.host || reqUrlObject.hostname || headers.host || "localhost";
      if (host.indexOf(":") === -1 && port && port !== "80" && port !== "443") {
        host += `:${port}`;
      }
      return `${protocol}//${host}${path11}`;
    }, "getAbsoluteUrl");
    exports.getAbsoluteUrl = getAbsoluteUrl;
    var parseResponseStatus = /* @__PURE__ */ __name((kind, statusCode) => {
      const upperBound = kind === api_1.SpanKind.CLIENT ? 400 : 500;
      if (statusCode && statusCode >= 100 && statusCode < upperBound) {
        return api_1.SpanStatusCode.UNSET;
      }
      return api_1.SpanStatusCode.ERROR;
    }, "parseResponseStatus");
    exports.parseResponseStatus = parseResponseStatus;
    var satisfiesPattern = /* @__PURE__ */ __name((constant, pattern) => {
      if (typeof pattern === "string") {
        return pattern === constant;
      } else if (pattern instanceof RegExp) {
        return pattern.test(constant);
      } else if (typeof pattern === "function") {
        return pattern(constant);
      } else {
        throw new TypeError("Pattern is in unsupported datatype");
      }
    }, "satisfiesPattern");
    exports.satisfiesPattern = satisfiesPattern;
    var setSpanWithError = /* @__PURE__ */ __name((span, error, semconvStability) => {
      const message = error.message;
      if (semconvStability & instrumentation_1.SemconvStability.OLD) {
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_NAME, error.name);
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_MESSAGE, message);
      }
      if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
        span.setAttribute(semantic_conventions_1.ATTR_ERROR_TYPE, error.name);
      }
      span.setStatus({ code: api_1.SpanStatusCode.ERROR, message });
      span.recordException(error);
    }, "setSpanWithError");
    exports.setSpanWithError = setSpanWithError;
    var setRequestContentLengthAttribute = /* @__PURE__ */ __name((request4, attributes) => {
      const length = getContentLength(request4.headers);
      if (length === null)
        return;
      if ((0, exports.isCompressed)(request4.headers)) {
        attributes[semconv_1.ATTR_HTTP_REQUEST_CONTENT_LENGTH] = length;
      } else {
        attributes[semconv_1.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED] = length;
      }
    }, "setRequestContentLengthAttribute");
    exports.setRequestContentLengthAttribute = setRequestContentLengthAttribute;
    var setResponseContentLengthAttribute = /* @__PURE__ */ __name((response, attributes) => {
      const length = getContentLength(response.headers);
      if (length === null)
        return;
      if ((0, exports.isCompressed)(response.headers)) {
        attributes[semconv_1.ATTR_HTTP_RESPONSE_CONTENT_LENGTH] = length;
      } else {
        attributes[semconv_1.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED] = length;
      }
    }, "setResponseContentLengthAttribute");
    exports.setResponseContentLengthAttribute = setResponseContentLengthAttribute;
    function getContentLength(headers) {
      const contentLengthHeader = headers["content-length"];
      if (contentLengthHeader === void 0)
        return null;
      const contentLength = parseInt(contentLengthHeader, 10);
      if (isNaN(contentLength))
        return null;
      return contentLength;
    }
    __name(getContentLength, "getContentLength");
    var isCompressed = /* @__PURE__ */ __name((headers) => {
      const encoding = headers["content-encoding"];
      return !!encoding && encoding !== "identity";
    }, "isCompressed");
    exports.isCompressed = isCompressed;
    function stringUrlToHttpOptions(stringUrl) {
      const { hostname: hostname2, pathname, port, username, password, search, protocol, hash, href, origin, host } = new URL(stringUrl);
      const options = {
        protocol,
        hostname: hostname2 && hostname2[0] === "[" ? hostname2.slice(1, -1) : hostname2,
        hash,
        search,
        pathname,
        path: `${pathname || ""}${search || ""}`,
        href,
        origin,
        host
      };
      if (port !== "") {
        options.port = Number(port);
      }
      if (username || password) {
        options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(password)}`;
      }
      return options;
    }
    __name(stringUrlToHttpOptions, "stringUrlToHttpOptions");
    var getRequestInfo = /* @__PURE__ */ __name((logger, options, extraOptions) => {
      let pathname;
      let origin;
      let optionsParsed;
      let invalidUrl = false;
      if (typeof options === "string") {
        try {
          const convertedOptions = stringUrlToHttpOptions(options);
          optionsParsed = convertedOptions;
          pathname = convertedOptions.pathname || "/";
        } catch (e) {
          invalidUrl = true;
          logger.verbose("Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:", e);
          optionsParsed = {
            path: options
          };
          pathname = optionsParsed.path || "/";
        }
        origin = `${optionsParsed.protocol || "http:"}//${optionsParsed.host}`;
        if (extraOptions !== void 0) {
          Object.assign(optionsParsed, extraOptions);
        }
      } else if (options instanceof url.URL) {
        optionsParsed = {
          protocol: options.protocol,
          hostname: typeof options.hostname === "string" && options.hostname.startsWith("[") ? options.hostname.slice(1, -1) : options.hostname,
          path: `${options.pathname || ""}${options.search || ""}`
        };
        if (options.port !== "") {
          optionsParsed.port = Number(options.port);
        }
        if (options.username || options.password) {
          optionsParsed.auth = `${options.username}:${options.password}`;
        }
        pathname = options.pathname;
        origin = options.origin;
        if (extraOptions !== void 0) {
          Object.assign(optionsParsed, extraOptions);
        }
      } else {
        optionsParsed = Object.assign({ protocol: options.host ? "http:" : void 0 }, options);
        const hostname2 = optionsParsed.host || (optionsParsed.port != null ? `${optionsParsed.hostname}${optionsParsed.port}` : optionsParsed.hostname);
        origin = `${optionsParsed.protocol || "http:"}//${hostname2}`;
        pathname = options.pathname;
        if (!pathname && optionsParsed.path) {
          try {
            const parsedUrl = new URL(optionsParsed.path, origin);
            pathname = parsedUrl.pathname || "/";
          } catch {
            pathname = "/";
          }
        }
      }
      const method = optionsParsed.method ? optionsParsed.method.toUpperCase() : "GET";
      return { origin, pathname, method, optionsParsed, invalidUrl };
    }, "getRequestInfo");
    exports.getRequestInfo = getRequestInfo;
    var isValidOptionsType = /* @__PURE__ */ __name((options) => {
      if (!options) {
        return false;
      }
      const type = typeof options;
      return type === "string" || type === "object" && !Array.isArray(options);
    }, "isValidOptionsType");
    exports.isValidOptionsType = isValidOptionsType;
    var extractHostnameAndPort = /* @__PURE__ */ __name((requestOptions) => {
      if (requestOptions.hostname && requestOptions.port) {
        return { hostname: requestOptions.hostname, port: requestOptions.port };
      }
      const matches = requestOptions.host?.match(/^([^:/ ]+)(:\d{1,5})?/) || null;
      const hostname2 = requestOptions.hostname || (matches === null ? "localhost" : matches[1]);
      let port = requestOptions.port;
      if (!port) {
        if (matches && matches[2]) {
          port = matches[2].substring(1);
        } else {
          port = requestOptions.protocol === "https:" ? "443" : "80";
        }
      }
      return { hostname: hostname2, port };
    }, "extractHostnameAndPort");
    exports.extractHostnameAndPort = extractHostnameAndPort;
    var getOutgoingRequestAttributes = /* @__PURE__ */ __name((requestOptions, options, semconvStability, enableSyntheticSourceDetection) => {
      const hostname2 = options.hostname;
      const port = options.port;
      const method = requestOptions.method ?? "GET";
      const normalizedMethod = normalizeMethod(method);
      const headers = requestOptions.headers || {};
      const userAgent = headers["user-agent"];
      const urlFull = (0, exports.getAbsoluteUrl)(requestOptions, headers, `${options.component}:`);
      const oldAttributes = {
        [semconv_1.ATTR_HTTP_URL]: urlFull,
        [semconv_1.ATTR_HTTP_METHOD]: method,
        [semconv_1.ATTR_HTTP_TARGET]: requestOptions.path || "/",
        [semconv_1.ATTR_NET_PEER_NAME]: hostname2,
        [semconv_1.ATTR_HTTP_HOST]: headers.host ?? `${hostname2}:${port}`
      };
      const newAttributes = {
        // Required attributes
        [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: hostname2,
        [semantic_conventions_1.ATTR_SERVER_PORT]: Number(port),
        [semantic_conventions_1.ATTR_URL_FULL]: urlFull,
        [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent
        // leaving out protocol version, it is not yet negotiated
        // leaving out protocol name, it is only required when protocol version is set
        // retries and redirects not supported
        // Opt-in attributes left off for now
      };
      if (method !== normalizedMethod) {
        newAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
      }
      if (enableSyntheticSourceDetection && userAgent) {
        newAttributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);
      }
      if (userAgent !== void 0) {
        oldAttributes[semconv_1.ATTR_HTTP_USER_AGENT] = userAgent;
      }
      switch (semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return Object.assign(newAttributes, options.hookAttributes);
        case instrumentation_1.SemconvStability.OLD:
          return Object.assign(oldAttributes, options.hookAttributes);
      }
      return Object.assign(oldAttributes, newAttributes, options.hookAttributes);
    }, "getOutgoingRequestAttributes");
    exports.getOutgoingRequestAttributes = getOutgoingRequestAttributes;
    var getOutgoingRequestMetricAttributes = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_HTTP_METHOD] = spanAttributes[semconv_1.ATTR_HTTP_METHOD];
      metricAttributes[semconv_1.ATTR_NET_PEER_NAME] = spanAttributes[semconv_1.ATTR_NET_PEER_NAME];
      return metricAttributes;
    }, "getOutgoingRequestMetricAttributes");
    exports.getOutgoingRequestMetricAttributes = getOutgoingRequestMetricAttributes;
    var setAttributesFromHttpKind = /* @__PURE__ */ __name((kind, attributes) => {
      if (kind) {
        attributes[semconv_1.ATTR_HTTP_FLAVOR] = kind;
        if (kind.toUpperCase() !== "QUIC") {
          attributes[semconv_1.ATTR_NET_TRANSPORT] = semconv_1.NET_TRANSPORT_VALUE_IP_TCP;
        } else {
          attributes[semconv_1.ATTR_NET_TRANSPORT] = semconv_1.NET_TRANSPORT_VALUE_IP_UDP;
        }
      }
    }, "setAttributesFromHttpKind");
    exports.setAttributesFromHttpKind = setAttributesFromHttpKind;
    var getSyntheticType = /* @__PURE__ */ __name((userAgent) => {
      const userAgentString = String(userAgent).toLowerCase();
      for (const name of internal_types_1.SYNTHETIC_TEST_NAMES) {
        if (userAgentString.includes(name)) {
          return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;
        }
      }
      for (const name of internal_types_1.SYNTHETIC_BOT_NAMES) {
        if (userAgentString.includes(name)) {
          return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT;
        }
      }
      return;
    }, "getSyntheticType");
    var getOutgoingRequestAttributesOnResponse = /* @__PURE__ */ __name((response, semconvStability) => {
      const { statusCode, statusMessage, httpVersion, socket } = response;
      const oldAttributes = {};
      const stableAttributes = {};
      if (statusCode != null) {
        stableAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
      }
      if (socket) {
        const { remoteAddress, remotePort } = socket;
        oldAttributes[semconv_1.ATTR_NET_PEER_IP] = remoteAddress;
        oldAttributes[semconv_1.ATTR_NET_PEER_PORT] = remotePort;
        stableAttributes[semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS] = remoteAddress;
        stableAttributes[semantic_conventions_1.ATTR_NETWORK_PEER_PORT] = remotePort;
        stableAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion;
      }
      (0, exports.setResponseContentLengthAttribute)(response, oldAttributes);
      if (statusCode) {
        oldAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = statusCode;
        oldAttributes[AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT] = (statusMessage || "").toUpperCase();
      }
      (0, exports.setAttributesFromHttpKind)(httpVersion, oldAttributes);
      switch (semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return stableAttributes;
        case instrumentation_1.SemconvStability.OLD:
          return oldAttributes;
      }
      return Object.assign(oldAttributes, stableAttributes);
    }, "getOutgoingRequestAttributesOnResponse");
    exports.getOutgoingRequestAttributesOnResponse = getOutgoingRequestAttributesOnResponse;
    var getOutgoingRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_NET_PEER_PORT] = spanAttributes[semconv_1.ATTR_NET_PEER_PORT];
      metricAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = spanAttributes[semconv_1.ATTR_HTTP_STATUS_CODE];
      metricAttributes[semconv_1.ATTR_HTTP_FLAVOR] = spanAttributes[semconv_1.ATTR_HTTP_FLAVOR];
      return metricAttributes;
    }, "getOutgoingRequestMetricAttributesOnResponse");
    exports.getOutgoingRequestMetricAttributesOnResponse = getOutgoingRequestMetricAttributesOnResponse;
    var getOutgoingStableRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
        metricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
      }
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
      }
      return metricAttributes;
    }, "getOutgoingStableRequestMetricAttributesOnResponse");
    exports.getOutgoingStableRequestMetricAttributesOnResponse = getOutgoingStableRequestMetricAttributesOnResponse;
    function parseHostHeader(hostHeader, proto) {
      const parts = hostHeader.split(":");
      if (parts.length === 1) {
        if (proto === "http") {
          return { host: parts[0], port: "80" };
        }
        if (proto === "https") {
          return { host: parts[0], port: "443" };
        }
        return { host: parts[0] };
      }
      if (parts.length === 2) {
        return {
          host: parts[0],
          port: parts[1]
        };
      }
      if (parts[0].startsWith("[")) {
        if (parts[parts.length - 1].endsWith("]")) {
          if (proto === "http") {
            return { host: hostHeader, port: "80" };
          }
          if (proto === "https") {
            return { host: hostHeader, port: "443" };
          }
        } else if (parts[parts.length - 2].endsWith("]")) {
          return {
            host: parts.slice(0, -1).join(":"),
            port: parts[parts.length - 1]
          };
        }
      }
      return { host: hostHeader };
    }
    __name(parseHostHeader, "parseHostHeader");
    function getServerAddress(request4, component) {
      const forwardedHeader = request4.headers["forwarded"];
      if (forwardedHeader) {
        for (const entry of parseForwardedHeader(forwardedHeader)) {
          if (entry.host) {
            return parseHostHeader(entry.host, entry.proto);
          }
        }
      }
      const xForwardedHost = request4.headers["x-forwarded-host"];
      if (typeof xForwardedHost === "string") {
        if (typeof request4.headers["x-forwarded-proto"] === "string") {
          return parseHostHeader(xForwardedHost, request4.headers["x-forwarded-proto"]);
        }
        if (Array.isArray(request4.headers["x-forwarded-proto"])) {
          return parseHostHeader(xForwardedHost, request4.headers["x-forwarded-proto"][0]);
        }
        return parseHostHeader(xForwardedHost);
      } else if (Array.isArray(xForwardedHost) && typeof xForwardedHost[0] === "string" && xForwardedHost[0].length > 0) {
        if (typeof request4.headers["x-forwarded-proto"] === "string") {
          return parseHostHeader(xForwardedHost[0], request4.headers["x-forwarded-proto"]);
        }
        if (Array.isArray(request4.headers["x-forwarded-proto"])) {
          return parseHostHeader(xForwardedHost[0], request4.headers["x-forwarded-proto"][0]);
        }
        return parseHostHeader(xForwardedHost[0]);
      }
      const host = request4.headers["host"];
      if (typeof host === "string" && host.length > 0) {
        return parseHostHeader(host, component);
      }
      return null;
    }
    __name(getServerAddress, "getServerAddress");
    function getRemoteClientAddress(request4) {
      const forwardedHeader = request4.headers["forwarded"];
      if (forwardedHeader) {
        for (const entry of parseForwardedHeader(forwardedHeader)) {
          if (entry.for) {
            return entry.for;
          }
        }
      }
      const xForwardedFor = request4.headers["x-forwarded-for"];
      if (typeof xForwardedFor === "string") {
        return xForwardedFor;
      } else if (Array.isArray(xForwardedFor)) {
        return xForwardedFor[0];
      }
      const remote = request4.socket.remoteAddress;
      if (remote) {
        return remote;
      }
      return null;
    }
    __name(getRemoteClientAddress, "getRemoteClientAddress");
    exports.getRemoteClientAddress = getRemoteClientAddress;
    function getInfoFromIncomingMessage(component, request4, logger) {
      try {
        if (request4.headers.host) {
          return new URL(request4.url ?? "/", `${component}://${request4.headers.host}`);
        } else {
          const unsafeParsedUrl = new URL(
            request4.url ?? "/",
            // using localhost as a workaround to still use the URL constructor for parsing
            `${component}://localhost`
          );
          return {
            pathname: unsafeParsedUrl.pathname,
            search: unsafeParsedUrl.search,
            toString: /* @__PURE__ */ __name(function() {
              return unsafeParsedUrl.pathname + unsafeParsedUrl.search;
            }, "toString")
          };
        }
      } catch (e) {
        logger.verbose("Unable to get URL from request", e);
        return {};
      }
    }
    __name(getInfoFromIncomingMessage, "getInfoFromIncomingMessage");
    var getIncomingRequestAttributes = /* @__PURE__ */ __name((request4, options, logger) => {
      const headers = request4.headers;
      const userAgent = headers["user-agent"];
      const ips = headers["x-forwarded-for"];
      const httpVersion = request4.httpVersion;
      const host = headers.host;
      const hostname2 = host?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost";
      const method = request4.method;
      const normalizedMethod = normalizeMethod(method);
      const serverAddress = getServerAddress(request4, options.component);
      const serverName = options.serverName;
      const remoteClientAddress = getRemoteClientAddress(request4);
      const newAttributes = {
        [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
        [semantic_conventions_1.ATTR_URL_SCHEME]: options.component,
        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: serverAddress?.host,
        [semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS]: request4.socket.remoteAddress,
        [semantic_conventions_1.ATTR_NETWORK_PEER_PORT]: request4.socket.remotePort,
        [semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]: request4.httpVersion,
        [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent
      };
      const parsedUrl = getInfoFromIncomingMessage(options.component, request4, logger);
      if (parsedUrl?.pathname != null) {
        newAttributes[semantic_conventions_1.ATTR_URL_PATH] = parsedUrl.pathname;
      }
      if (parsedUrl.search) {
        newAttributes[semantic_conventions_1.ATTR_URL_QUERY] = parsedUrl.search.slice(1);
      }
      if (remoteClientAddress != null) {
        newAttributes[semantic_conventions_1.ATTR_CLIENT_ADDRESS] = remoteClientAddress.split(",")[0];
      }
      if (serverAddress?.port != null) {
        newAttributes[semantic_conventions_1.ATTR_SERVER_PORT] = Number(serverAddress.port);
      }
      if (method !== normalizedMethod) {
        newAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
      }
      if (options.enableSyntheticSourceDetection && userAgent) {
        newAttributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);
      }
      const oldAttributes = {
        [semconv_1.ATTR_HTTP_URL]: parsedUrl.toString(),
        [semconv_1.ATTR_HTTP_HOST]: host,
        [semconv_1.ATTR_NET_HOST_NAME]: hostname2,
        [semconv_1.ATTR_HTTP_METHOD]: method,
        [semconv_1.ATTR_HTTP_SCHEME]: options.component
      };
      if (typeof ips === "string") {
        oldAttributes[semconv_1.ATTR_HTTP_CLIENT_IP] = ips.split(",")[0];
      }
      if (typeof serverName === "string") {
        oldAttributes[semconv_1.ATTR_HTTP_SERVER_NAME] = serverName;
      }
      if (parsedUrl?.pathname) {
        oldAttributes[semconv_1.ATTR_HTTP_TARGET] = parsedUrl?.pathname + parsedUrl?.search || "/";
      }
      if (userAgent !== void 0) {
        oldAttributes[semconv_1.ATTR_HTTP_USER_AGENT] = userAgent;
      }
      (0, exports.setRequestContentLengthAttribute)(request4, oldAttributes);
      (0, exports.setAttributesFromHttpKind)(httpVersion, oldAttributes);
      switch (options.semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return Object.assign(newAttributes, options.hookAttributes);
        case instrumentation_1.SemconvStability.OLD:
          return Object.assign(oldAttributes, options.hookAttributes);
      }
      return Object.assign(oldAttributes, newAttributes, options.hookAttributes);
    }, "getIncomingRequestAttributes");
    exports.getIncomingRequestAttributes = getIncomingRequestAttributes;
    var getIncomingRequestMetricAttributes = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_HTTP_SCHEME] = spanAttributes[semconv_1.ATTR_HTTP_SCHEME];
      metricAttributes[semconv_1.ATTR_HTTP_METHOD] = spanAttributes[semconv_1.ATTR_HTTP_METHOD];
      metricAttributes[semconv_1.ATTR_NET_HOST_NAME] = spanAttributes[semconv_1.ATTR_NET_HOST_NAME];
      metricAttributes[semconv_1.ATTR_HTTP_FLAVOR] = spanAttributes[semconv_1.ATTR_HTTP_FLAVOR];
      return metricAttributes;
    }, "getIncomingRequestMetricAttributes");
    exports.getIncomingRequestMetricAttributes = getIncomingRequestMetricAttributes;
    var getIncomingRequestAttributesOnResponse = /* @__PURE__ */ __name((request4, response, semconvStability) => {
      const { socket } = request4;
      const { statusCode, statusMessage } = response;
      const newAttributes = {
        [semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode
      };
      const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active());
      const oldAttributes = {};
      if (socket) {
        const { localAddress, localPort, remoteAddress, remotePort } = socket;
        oldAttributes[semconv_1.ATTR_NET_HOST_IP] = localAddress;
        oldAttributes[semconv_1.ATTR_NET_HOST_PORT] = localPort;
        oldAttributes[semconv_1.ATTR_NET_PEER_IP] = remoteAddress;
        oldAttributes[semconv_1.ATTR_NET_PEER_PORT] = remotePort;
      }
      oldAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = statusCode;
      oldAttributes[AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT] = (statusMessage || "").toUpperCase();
      if (rpcMetadata?.type === core_1.RPCType.HTTP && rpcMetadata.route !== void 0) {
        oldAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = rpcMetadata.route;
        newAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = rpcMetadata.route;
      }
      switch (semconvStability) {
        case instrumentation_1.SemconvStability.STABLE:
          return newAttributes;
        case instrumentation_1.SemconvStability.OLD:
          return oldAttributes;
      }
      return Object.assign(oldAttributes, newAttributes);
    }, "getIncomingRequestAttributesOnResponse");
    exports.getIncomingRequestAttributesOnResponse = getIncomingRequestAttributesOnResponse;
    var getIncomingRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      metricAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = spanAttributes[semconv_1.ATTR_HTTP_STATUS_CODE];
      metricAttributes[semconv_1.ATTR_NET_HOST_PORT] = spanAttributes[semconv_1.ATTR_NET_HOST_PORT];
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] !== void 0) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
      }
      return metricAttributes;
    }, "getIncomingRequestMetricAttributesOnResponse");
    exports.getIncomingRequestMetricAttributesOnResponse = getIncomingRequestMetricAttributesOnResponse;
    var getIncomingStableRequestMetricAttributesOnResponse = /* @__PURE__ */ __name((spanAttributes) => {
      const metricAttributes = {};
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] !== void 0) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
      }
      if (spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) {
        metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
      }
      return metricAttributes;
    }, "getIncomingStableRequestMetricAttributesOnResponse");
    exports.getIncomingStableRequestMetricAttributesOnResponse = getIncomingStableRequestMetricAttributesOnResponse;
    function headerCapture(type, headers) {
      const normalizedHeaders = /* @__PURE__ */ new Map();
      for (let i = 0, len = headers.length; i < len; i++) {
        const capturedHeader = headers[i].toLowerCase();
        normalizedHeaders.set(capturedHeader, capturedHeader.replace(/-/g, "_"));
      }
      return (span, getHeader) => {
        for (const capturedHeader of normalizedHeaders.keys()) {
          const value = getHeader(capturedHeader);
          if (value === void 0) {
            continue;
          }
          const normalizedHeader = normalizedHeaders.get(capturedHeader);
          const key = `http.${type}.header.${normalizedHeader}`;
          if (typeof value === "string") {
            span.setAttribute(key, [value]);
          } else if (Array.isArray(value)) {
            span.setAttribute(key, value);
          } else {
            span.setAttribute(key, [value]);
          }
        }
      };
    }
    __name(headerCapture, "headerCapture");
    exports.headerCapture = headerCapture;
    var KNOWN_METHODS = /* @__PURE__ */ new Set([
      // methods from https://www.rfc-editor.org/rfc/rfc9110.html#name-methods
      "GET",
      "HEAD",
      "POST",
      "PUT",
      "DELETE",
      "CONNECT",
      "OPTIONS",
      "TRACE",
      // PATCH from https://www.rfc-editor.org/rfc/rfc5789.html
      "PATCH"
    ]);
    function normalizeMethod(method) {
      if (method == null) {
        return "GET";
      }
      const upper = method.toUpperCase();
      if (KNOWN_METHODS.has(upper)) {
        return upper;
      }
      return "_OTHER";
    }
    __name(normalizeMethod, "normalizeMethod");
    function parseForwardedHeader(header) {
      try {
        return forwardedParse(header);
      } catch {
        return [];
      }
    }
    __name(parseForwardedHeader, "parseForwardedHeader");
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/http.js
var require_http = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/http.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HttpInstrumentation = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src3();
    var url = __require("url");
    var version_1 = require_version9();
    var instrumentation_1 = require_src21();
    var events_1 = __require("events");
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var utils_1 = require_utils10();
    var HttpInstrumentation2 = class extends instrumentation_1.InstrumentationBase {
      static {
        __name(this, "HttpInstrumentation");
      }
      /** keep track on spans not ended */
      _spanNotEnded = /* @__PURE__ */ new WeakSet();
      _headerCapture;
      _semconvStability = instrumentation_1.SemconvStability.OLD;
      constructor(config = {}) {
        super("@opentelemetry/instrumentation-http", version_1.VERSION, config);
        this._headerCapture = this._createHeaderCapture();
        this._semconvStability = (0, instrumentation_1.semconvStabilityFromStr)("http", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
      }
      _updateMetricInstruments() {
        this._oldHttpServerDurationHistogram = this.meter.createHistogram("http.server.duration", {
          description: "Measures the duration of inbound HTTP requests.",
          unit: "ms",
          valueType: api_1.ValueType.DOUBLE
        });
        this._oldHttpClientDurationHistogram = this.meter.createHistogram("http.client.duration", {
          description: "Measures the duration of outbound HTTP requests.",
          unit: "ms",
          valueType: api_1.ValueType.DOUBLE
        });
        this._stableHttpServerDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_SERVER_REQUEST_DURATION, {
          description: "Duration of HTTP server requests.",
          unit: "s",
          valueType: api_1.ValueType.DOUBLE,
          advice: {
            explicitBucketBoundaries: [
              5e-3,
              0.01,
              0.025,
              0.05,
              0.075,
              0.1,
              0.25,
              0.5,
              0.75,
              1,
              2.5,
              5,
              7.5,
              10
            ]
          }
        });
        this._stableHttpClientDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_CLIENT_REQUEST_DURATION, {
          description: "Duration of HTTP client requests.",
          unit: "s",
          valueType: api_1.ValueType.DOUBLE,
          advice: {
            explicitBucketBoundaries: [
              5e-3,
              0.01,
              0.025,
              0.05,
              0.075,
              0.1,
              0.25,
              0.5,
              0.75,
              1,
              2.5,
              5,
              7.5,
              10
            ]
          }
        });
      }
      _recordServerDuration(durationMs, oldAttributes, stableAttributes) {
        if (this._semconvStability & instrumentation_1.SemconvStability.OLD) {
          this._oldHttpServerDurationHistogram.record(durationMs, oldAttributes);
        }
        if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) {
          this._stableHttpServerDurationHistogram.record(durationMs / 1e3, stableAttributes);
        }
      }
      _recordClientDuration(durationMs, oldAttributes, stableAttributes) {
        if (this._semconvStability & instrumentation_1.SemconvStability.OLD) {
          this._oldHttpClientDurationHistogram.record(durationMs, oldAttributes);
        }
        if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) {
          this._stableHttpClientDurationHistogram.record(durationMs / 1e3, stableAttributes);
        }
      }
      setConfig(config = {}) {
        super.setConfig(config);
        this._headerCapture = this._createHeaderCapture();
      }
      init() {
        return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];
      }
      _getHttpInstrumentation() {
        return new instrumentation_1.InstrumentationNodeModuleDefinition("http", ["*"], (moduleExports) => {
          const isESM = moduleExports[Symbol.toStringTag] === "Module";
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            const patchedRequest = this._wrap(moduleExports, "request", this._getPatchOutgoingRequestFunction("http"));
            const patchedGet = this._wrap(moduleExports, "get", this._getPatchOutgoingGetFunction(patchedRequest));
            if (isESM) {
              moduleExports.default.request = patchedRequest;
              moduleExports.default.get = patchedGet;
            }
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("http"));
          }
          return moduleExports;
        }, (moduleExports) => {
          if (moduleExports === void 0)
            return;
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            this._unwrap(moduleExports, "request");
            this._unwrap(moduleExports, "get");
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._unwrap(moduleExports.Server.prototype, "emit");
          }
        });
      }
      _getHttpsInstrumentation() {
        return new instrumentation_1.InstrumentationNodeModuleDefinition("https", ["*"], (moduleExports) => {
          const isESM = moduleExports[Symbol.toStringTag] === "Module";
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            const patchedRequest = this._wrap(moduleExports, "request", this._getPatchHttpsOutgoingRequestFunction("https"));
            const patchedGet = this._wrap(moduleExports, "get", this._getPatchHttpsOutgoingGetFunction(patchedRequest));
            if (isESM) {
              moduleExports.default.request = patchedRequest;
              moduleExports.default.get = patchedGet;
            }
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("https"));
          }
          return moduleExports;
        }, (moduleExports) => {
          if (moduleExports === void 0)
            return;
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            this._unwrap(moduleExports, "request");
            this._unwrap(moduleExports, "get");
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._unwrap(moduleExports.Server.prototype, "emit");
          }
        });
      }
      /**
       * Creates spans for incoming requests, restoring spans' context if applied.
       */
      _getPatchIncomingRequestFunction(component) {
        return (original) => {
          return this._incomingRequestFunction(component, original);
        };
      }
      /**
       * Creates spans for outgoing requests, sending spans' context for distributed
       * tracing.
       */
      _getPatchOutgoingRequestFunction(component) {
        return (original) => {
          return this._outgoingRequestFunction(component, original);
        };
      }
      _getPatchOutgoingGetFunction(clientRequest) {
        return (_original) => {
          return /* @__PURE__ */ __name(function outgoingGetRequest(options, ...args) {
            const req = clientRequest(options, ...args);
            req.end();
            return req;
          }, "outgoingGetRequest");
        };
      }
      /** Patches HTTPS outgoing requests */
      _getPatchHttpsOutgoingRequestFunction(component) {
        return (original) => {
          const instrumentation = this;
          return /* @__PURE__ */ __name(function httpsOutgoingRequest(options, ...args) {
            if (component === "https" && typeof options === "object" && options?.constructor?.name !== "URL") {
              options = Object.assign({}, options);
              instrumentation._setDefaultOptions(options);
            }
            return instrumentation._getPatchOutgoingRequestFunction(component)(original)(options, ...args);
          }, "httpsOutgoingRequest");
        };
      }
      _setDefaultOptions(options) {
        options.protocol = options.protocol || "https:";
        options.port = options.port || 443;
      }
      /** Patches HTTPS outgoing get requests */
      _getPatchHttpsOutgoingGetFunction(clientRequest) {
        return (original) => {
          const instrumentation = this;
          return /* @__PURE__ */ __name(function httpsOutgoingRequest(options, ...args) {
            return instrumentation._getPatchOutgoingGetFunction(clientRequest)(original)(options, ...args);
          }, "httpsOutgoingRequest");
        };
      }
      /**
       * Attach event listeners to a client request to end span and add span attributes.
       *
       * @param request The original request object.
       * @param span representing the current operation
       * @param startTime representing the start time of the request to calculate duration in Metric
       * @param oldMetricAttributes metric attributes for old semantic conventions
       * @param stableMetricAttributes metric attributes for new semantic conventions
       */
      _traceClientRequest(request4, span, startTime, oldMetricAttributes, stableMetricAttributes) {
        if (this.getConfig().requestHook) {
          this._callRequestHook(span, request4);
        }
        let responseFinished = false;
        request4.prependListener("response", (response) => {
          this._diag.debug("outgoingRequest on response()");
          if (request4.listenerCount("response") <= 1) {
            response.resume();
          }
          const responseAttributes = (0, utils_1.getOutgoingRequestAttributesOnResponse)(response, this._semconvStability);
          span.setAttributes(responseAttributes);
          oldMetricAttributes = Object.assign(oldMetricAttributes, (0, utils_1.getOutgoingRequestMetricAttributesOnResponse)(responseAttributes));
          stableMetricAttributes = Object.assign(stableMetricAttributes, (0, utils_1.getOutgoingStableRequestMetricAttributesOnResponse)(responseAttributes));
          if (this.getConfig().responseHook) {
            this._callResponseHook(span, response);
          }
          this._headerCapture.client.captureRequestHeaders(span, (header) => request4.getHeader(header));
          this._headerCapture.client.captureResponseHeaders(span, (header) => response.headers[header]);
          api_1.context.bind(api_1.context.active(), response);
          const endHandler = /* @__PURE__ */ __name(() => {
            this._diag.debug("outgoingRequest on end()");
            if (responseFinished) {
              return;
            }
            responseFinished = true;
            let status;
            if (response.aborted && !response.complete) {
              status = { code: api_1.SpanStatusCode.ERROR };
            } else {
              status = {
                code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.CLIENT, response.statusCode)
              };
            }
            span.setStatus(status);
            if (this.getConfig().applyCustomAttributesOnSpan) {
              (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request4, response), () => {
              }, true);
            }
            this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
          }, "endHandler");
          response.on("end", endHandler);
          response.on(events_1.errorMonitor, (error) => {
            this._diag.debug("outgoingRequest on error()", error);
            if (responseFinished) {
              return;
            }
            responseFinished = true;
            (0, utils_1.setSpanWithError)(span, error, this._semconvStability);
            span.setStatus({
              code: api_1.SpanStatusCode.ERROR,
              message: error.message
            });
            this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
          });
        });
        request4.on("close", () => {
          this._diag.debug("outgoingRequest on request close()");
          if (request4.aborted || responseFinished) {
            return;
          }
          responseFinished = true;
          this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
        });
        request4.on(events_1.errorMonitor, (error) => {
          this._diag.debug("outgoingRequest on request error()", error);
          if (responseFinished) {
            return;
          }
          responseFinished = true;
          (0, utils_1.setSpanWithError)(span, error, this._semconvStability);
          this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
        });
        this._diag.debug("http.ClientRequest return request");
        return request4;
      }
      _incomingRequestFunction(component, original) {
        const instrumentation = this;
        return /* @__PURE__ */ __name(function incomingRequest(event, ...args) {
          if (event !== "request") {
            return original.apply(this, [event, ...args]);
          }
          const request4 = args[0];
          const response = args[1];
          const method = request4.method || "GET";
          instrumentation._diag.debug(`${component} instrumentation incomingRequest`);
          if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation.getConfig().ignoreIncomingRequestHook?.(request4), (e) => {
            if (e != null) {
              instrumentation._diag.error("caught ignoreIncomingRequestHook error: ", e);
            }
          }, true)) {
            return api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => {
              api_1.context.bind(api_1.context.active(), request4);
              api_1.context.bind(api_1.context.active(), response);
              return original.apply(this, [event, ...args]);
            });
          }
          const headers = request4.headers;
          const spanAttributes = (0, utils_1.getIncomingRequestAttributes)(request4, {
            component,
            serverName: instrumentation.getConfig().serverName,
            hookAttributes: instrumentation._callStartSpanHook(request4, instrumentation.getConfig().startIncomingSpanHook),
            semconvStability: instrumentation._semconvStability,
            enableSyntheticSourceDetection: instrumentation.getConfig().enableSyntheticSourceDetection || false
          }, instrumentation._diag);
          const spanOptions = {
            kind: api_1.SpanKind.SERVER,
            attributes: spanAttributes
          };
          const startTime = (0, core_1.hrTime)();
          const oldMetricAttributes = (0, utils_1.getIncomingRequestMetricAttributes)(spanAttributes);
          const stableMetricAttributes = {
            [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: spanAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD],
            [semantic_conventions_1.ATTR_URL_SCHEME]: spanAttributes[semantic_conventions_1.ATTR_URL_SCHEME]
          };
          if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
            stableMetricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
          }
          const ctx = api_1.propagation.extract(api_1.ROOT_CONTEXT, headers);
          const span = instrumentation._startHttpSpan(method, spanOptions, ctx);
          const rpcMetadata = {
            type: core_1.RPCType.HTTP,
            span
          };
          return api_1.context.with((0, core_1.setRPCMetadata)(api_1.trace.setSpan(ctx, span), rpcMetadata), () => {
            api_1.context.bind(api_1.context.active(), request4);
            api_1.context.bind(api_1.context.active(), response);
            if (instrumentation.getConfig().requestHook) {
              instrumentation._callRequestHook(span, request4);
            }
            if (instrumentation.getConfig().responseHook) {
              instrumentation._callResponseHook(span, response);
            }
            instrumentation._headerCapture.server.captureRequestHeaders(span, (header) => request4.headers[header]);
            let hasError = false;
            response.on("close", () => {
              if (hasError) {
                return;
              }
              instrumentation._onServerResponseFinish(request4, response, span, oldMetricAttributes, stableMetricAttributes, startTime);
            });
            response.on(events_1.errorMonitor, (err) => {
              hasError = true;
              instrumentation._onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, err);
            });
            return (0, instrumentation_1.safeExecuteInTheMiddle)(() => original.apply(this, [event, ...args]), (error) => {
              if (error) {
                (0, utils_1.setSpanWithError)(span, error, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error;
              }
            });
          });
        }, "incomingRequest");
      }
      _outgoingRequestFunction(component, original) {
        const instrumentation = this;
        return /* @__PURE__ */ __name(function outgoingRequest(options, ...args) {
          if (!(0, utils_1.isValidOptionsType)(options)) {
            return original.apply(this, [options, ...args]);
          }
          const extraOptions = typeof args[0] === "object" && (typeof options === "string" || options instanceof url.URL) ? args.shift() : void 0;
          const { method, invalidUrl, optionsParsed } = (0, utils_1.getRequestInfo)(instrumentation._diag, options, extraOptions);
          if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation.getConfig().ignoreOutgoingRequestHook?.(optionsParsed), (e) => {
            if (e != null) {
              instrumentation._diag.error("caught ignoreOutgoingRequestHook error: ", e);
            }
          }, true)) {
            return original.apply(this, [optionsParsed, ...args]);
          }
          const { hostname: hostname2, port } = (0, utils_1.extractHostnameAndPort)(optionsParsed);
          const attributes = (0, utils_1.getOutgoingRequestAttributes)(optionsParsed, {
            component,
            port,
            hostname: hostname2,
            hookAttributes: instrumentation._callStartSpanHook(optionsParsed, instrumentation.getConfig().startOutgoingSpanHook)
          }, instrumentation._semconvStability, instrumentation.getConfig().enableSyntheticSourceDetection || false);
          const startTime = (0, core_1.hrTime)();
          const oldMetricAttributes = (0, utils_1.getOutgoingRequestMetricAttributes)(attributes);
          const stableMetricAttributes = {
            [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: attributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD],
            [semantic_conventions_1.ATTR_SERVER_ADDRESS]: attributes[semantic_conventions_1.ATTR_SERVER_ADDRESS],
            [semantic_conventions_1.ATTR_SERVER_PORT]: attributes[semantic_conventions_1.ATTR_SERVER_PORT]
          };
          if (attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) {
            stableMetricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
          }
          if (attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
            stableMetricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
          }
          const spanOptions = {
            kind: api_1.SpanKind.CLIENT,
            attributes
          };
          const span = instrumentation._startHttpSpan(method, spanOptions);
          const parentContext = api_1.context.active();
          const requestContext = api_1.trace.setSpan(parentContext, span);
          if (!optionsParsed.headers) {
            optionsParsed.headers = {};
          } else {
            optionsParsed.headers = Object.assign({}, optionsParsed.headers);
          }
          api_1.propagation.inject(requestContext, optionsParsed.headers);
          return api_1.context.with(requestContext, () => {
            const cb = args[args.length - 1];
            if (typeof cb === "function") {
              args[args.length - 1] = api_1.context.bind(parentContext, cb);
            }
            const request4 = (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
              if (invalidUrl) {
                return original.apply(this, [options, ...args]);
              } else {
                return original.apply(this, [optionsParsed, ...args]);
              }
            }, (error) => {
              if (error) {
                (0, utils_1.setSpanWithError)(span, error, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error;
              }
            });
            instrumentation._diag.debug(`${component} instrumentation outgoingRequest`);
            api_1.context.bind(parentContext, request4);
            return instrumentation._traceClientRequest(request4, span, startTime, oldMetricAttributes, stableMetricAttributes);
          });
        }, "outgoingRequest");
      }
      _onServerResponseFinish(request4, response, span, oldMetricAttributes, stableMetricAttributes, startTime) {
        const attributes = (0, utils_1.getIncomingRequestAttributesOnResponse)(request4, response, this._semconvStability);
        oldMetricAttributes = Object.assign(oldMetricAttributes, (0, utils_1.getIncomingRequestMetricAttributesOnResponse)(attributes));
        stableMetricAttributes = Object.assign(stableMetricAttributes, (0, utils_1.getIncomingStableRequestMetricAttributesOnResponse)(attributes));
        this._headerCapture.server.captureResponseHeaders(span, (header) => response.getHeader(header));
        span.setAttributes(attributes).setStatus({
          code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.SERVER, response.statusCode)
        });
        const route = attributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
        if (route) {
          span.updateName(`${request4.method || "GET"} ${route}`);
        }
        if (this.getConfig().applyCustomAttributesOnSpan) {
          (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request4, response), () => {
          }, true);
        }
        this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
      }
      _onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, error) {
        (0, utils_1.setSpanWithError)(span, error, this._semconvStability);
        this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
      }
      _startHttpSpan(name, options, ctx = api_1.context.active()) {
        const requireParent = options.kind === api_1.SpanKind.CLIENT ? this.getConfig().requireParentforOutgoingSpans : this.getConfig().requireParentforIncomingSpans;
        let span;
        const currentSpan = api_1.trace.getSpan(ctx);
        if (requireParent === true && currentSpan === void 0) {
          span = api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT);
        } else if (requireParent === true && currentSpan?.spanContext().isRemote) {
          span = currentSpan;
        } else {
          span = this.tracer.startSpan(name, options, ctx);
        }
        this._spanNotEnded.add(span);
        return span;
      }
      _closeHttpSpan(span, spanKind, startTime, oldMetricAttributes, stableMetricAttributes) {
        if (!this._spanNotEnded.has(span)) {
          return;
        }
        span.end();
        this._spanNotEnded.delete(span);
        const duration = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)()));
        if (spanKind === api_1.SpanKind.SERVER) {
          this._recordServerDuration(duration, oldMetricAttributes, stableMetricAttributes);
        } else if (spanKind === api_1.SpanKind.CLIENT) {
          this._recordClientDuration(duration, oldMetricAttributes, stableMetricAttributes);
        }
      }
      _callResponseHook(span, response) {
        (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().responseHook(span, response), () => {
        }, true);
      }
      _callRequestHook(span, request4) {
        (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().requestHook(span, request4), () => {
        }, true);
      }
      _callStartSpanHook(request4, hookFunc) {
        if (typeof hookFunc === "function") {
          return (0, instrumentation_1.safeExecuteInTheMiddle)(() => hookFunc(request4), () => {
          }, true);
        }
      }
      _createHeaderCapture() {
        const config = this.getConfig();
        return {
          client: {
            captureRequestHeaders: (0, utils_1.headerCapture)("request", config.headersToSpanAttributes?.client?.requestHeaders ?? []),
            captureResponseHeaders: (0, utils_1.headerCapture)("response", config.headersToSpanAttributes?.client?.responseHeaders ?? [])
          },
          server: {
            captureRequestHeaders: (0, utils_1.headerCapture)("request", config.headersToSpanAttributes?.server?.requestHeaders ?? []),
            captureResponseHeaders: (0, utils_1.headerCapture)("response", config.headersToSpanAttributes?.server?.responseHeaders ?? [])
          }
        };
      }
    };
    exports.HttpInstrumentation = HttpInstrumentation2;
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/index.js
var require_src30 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HttpInstrumentation = void 0;
    var http_1 = require_http();
    Object.defineProperty(exports, "HttpInstrumentation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return http_1.HttpInstrumentation;
    }, "get") });
  }
});

// node_modules/@opentelemetry/instrumentation-undici/build/src/version.js
var require_version10 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-undici/build/src/version.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PACKAGE_NAME = exports.PACKAGE_VERSION = void 0;
    exports.PACKAGE_VERSION = "0.14.0";
    exports.PACKAGE_NAME = "@opentelemetry/instrumentation-undici";
  }
});

// node_modules/@opentelemetry/instrumentation-undici/build/src/enums/SemanticAttributes.js
var require_SemanticAttributes = __commonJS({
  "node_modules/@opentelemetry/instrumentation-undici/build/src/enums/SemanticAttributes.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SemanticAttributes = void 0;
    exports.SemanticAttributes = {
      /**
       * State of the HTTP connection in the HTTP connection pool.
       */
      HTTP_CONNECTION_STATE: "http.connection.state",
      /**
        * Describes a class of error the operation ended with.
        *
        * Note: The `error.type` SHOULD be predictable and SHOULD have low cardinality.
      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 gRPC status codes),
      it&#39;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.
        */
      ERROR_TYPE: "error.type",
      /**
       * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.
       */
      HTTP_REQUEST_BODY_SIZE: "http.request.body.size",
      /**
        * HTTP request method.
        *
        * Note: HTTP request method value SHOULD be &#34;known&#34; to the instrumentation.
      By default, this convention defines &#34;known&#34; methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods)
      and the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html).
      
      If the HTTP request method is not known to instrumentation, it MUST set the `http.request.method` attribute to `_OTHER`.
      
      If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it MUST provide a way to override
      the list of known HTTP methods. If this override is done via environment variable, then the environment variable MUST be named
      OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods
      (this list MUST be a full override of the default known method, it is not a list of known methods in addition to the defaults).
      
      HTTP method names are case-sensitive and `http.request.method` attribute value MUST match a known HTTP method name exactly.
      Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, SHOULD populate a canonical equivalent.
      Tracing instrumentations that do so, MUST also set `http.request.method_original` to the original value.
        */
      HTTP_REQUEST_METHOD: "http.request.method",
      /**
       * Original HTTP method sent by the client in the request line.
       */
      HTTP_REQUEST_METHOD_ORIGINAL: "http.request.method_original",
      /**
       * The ordinal number of request resending attempt (for any reason, including redirects).
       *
       * Note: The resend count SHOULD be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).
       */
      HTTP_REQUEST_RESEND_COUNT: "http.request.resend_count",
      /**
       * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.
       */
      HTTP_RESPONSE_BODY_SIZE: "http.response.body.size",
      /**
       * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).
       */
      HTTP_RESPONSE_STATUS_CODE: "http.response.status_code",
      /**
        * The matched route, that is, the path template in the format used by the respective server framework.
        *
        * Note: MUST NOT be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.
      SHOULD include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.
        */
      HTTP_ROUTE: "http.route",
      /**
       * Peer address of the network connection - IP address or Unix domain socket name.
       */
      NETWORK_PEER_ADDRESS: "network.peer.address",
      /**
       * Peer port number of the network connection.
       */
      NETWORK_PEER_PORT: "network.peer.port",
      /**
       * [OSI application layer](https://osi-model.com/application-layer/) or non-OSI equivalent.
       *
       * Note: The value SHOULD be normalized to lowercase.
       */
      NETWORK_PROTOCOL_NAME: "network.protocol.name",
      /**
       * Version of the protocol specified in `network.protocol.name`.
       *
       * Note: `network.protocol.version` refers to the version of the protocol used and might be different from the protocol client&#39;s version. If the HTTP client has a version of `0.27.2`, but sends HTTP version `1.1`, this attribute should be set to `1.1`.
       */
      NETWORK_PROTOCOL_VERSION: "network.protocol.version",
      /**
       * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.
       *
       * Note: When observed from the client side, and when communicating through an intermediary, `server.address` SHOULD represent the server address behind any intermediaries, for example proxies, if it&#39;s available.
       */
      SERVER_ADDRESS: "server.address",
      /**
       * Server port number.
       *
       * Note: When observed from the client side, and when communicating through an intermediary, `server.port` SHOULD represent the server port behind any intermediaries, for example proxies, if it&#39;s available.
       */
      SERVER_PORT: "server.port",
      /**
        * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986).
        *
        * Note: For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment is not transmitted over HTTP, but if it is known, it SHOULD be included nevertheless.
      `url.full` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case username and password SHOULD be redacted and attribute&#39;s value SHOULD be `https://REDACTED:REDACTED@www.example.com/`.
      `url.full` SHOULD capture the absolute URL when it is available (or can be reconstructed) and SHOULD NOT be validated or modified except for sanitizing purposes.
        */
      URL_FULL: "url.full",
      /**
       * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component.
       */
      URL_PATH: "url.path",
      /**
       * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component.
       *
       * Note: Sensitive content provided in query string SHOULD be scrubbed when instrumentations can identify it.
       */
      URL_QUERY: "url.query",
      /**
       * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.
       */
      URL_SCHEME: "url.scheme",
      /**
       * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.
       */
      USER_AGENT_ORIGINAL: "user_agent.original"
    };
  }
});

// node_modules/@opentelemetry/instrumentation-undici/build/src/undici.js
var require_undici = __commonJS({
  "node_modules/@opentelemetry/instrumentation-undici/build/src/undici.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UndiciInstrumentation = void 0;
    var diagch = __require("diagnostics_channel");
    var url_1 = __require("url");
    var instrumentation_1 = require_src21();
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var version_1 = require_version10();
    var SemanticAttributes_1 = require_SemanticAttributes();
    var core_1 = require_src3();
    var UndiciInstrumentation2 = class extends instrumentation_1.InstrumentationBase {
      static {
        __name(this, "UndiciInstrumentation");
      }
      _recordFromReq = /* @__PURE__ */ new WeakMap();
      constructor(config = {}) {
        super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config);
      }
      // No need to instrument files/modules
      init() {
        return void 0;
      }
      disable() {
        super.disable();
        this._channelSubs.forEach((sub) => sub.unsubscribe());
        this._channelSubs.length = 0;
      }
      enable() {
        super.enable();
        this._channelSubs = this._channelSubs || [];
        if (this._channelSubs.length > 0) {
          return;
        }
        this.subscribeToChannel("undici:request:create", this.onRequestCreated.bind(this));
        this.subscribeToChannel("undici:client:sendHeaders", this.onRequestHeaders.bind(this));
        this.subscribeToChannel("undici:request:headers", this.onResponseHeaders.bind(this));
        this.subscribeToChannel("undici:request:trailers", this.onDone.bind(this));
        this.subscribeToChannel("undici:request:error", this.onError.bind(this));
      }
      _updateMetricInstruments() {
        this._httpClientDurationHistogram = this.meter.createHistogram("http.client.request.duration", {
          description: "Measures the duration of outbound HTTP requests.",
          unit: "s",
          valueType: api_1.ValueType.DOUBLE,
          advice: {
            explicitBucketBoundaries: [
              5e-3,
              0.01,
              0.025,
              0.05,
              0.075,
              0.1,
              0.25,
              0.5,
              0.75,
              1,
              2.5,
              5,
              7.5,
              10
            ]
          }
        });
      }
      subscribeToChannel(diagnosticChannel, onMessage) {
        const [major, minor] = process.version.replace("v", "").split(".").map((n) => Number(n));
        const useNewSubscribe = major > 18 || major === 18 && minor >= 19;
        let unsubscribe;
        if (useNewSubscribe) {
          diagch.subscribe?.(diagnosticChannel, onMessage);
          unsubscribe = /* @__PURE__ */ __name(() => diagch.unsubscribe?.(diagnosticChannel, onMessage), "unsubscribe");
        } else {
          const channel = diagch.channel(diagnosticChannel);
          channel.subscribe(onMessage);
          unsubscribe = /* @__PURE__ */ __name(() => channel.unsubscribe(onMessage), "unsubscribe");
        }
        this._channelSubs.push({
          name: diagnosticChannel,
          unsubscribe
        });
      }
      parseRequestHeaders(request4) {
        const result = /* @__PURE__ */ new Map();
        if (Array.isArray(request4.headers)) {
          for (let i = 0; i < request4.headers.length; i += 2) {
            const key = request4.headers[i];
            const value = request4.headers[i + 1];
            if (typeof key === "string") {
              result.set(key.toLowerCase(), value);
            }
          }
        } else if (typeof request4.headers === "string") {
          const headers = request4.headers.split("\r\n");
          for (const line of headers) {
            if (!line) {
              continue;
            }
            const colonIndex = line.indexOf(":");
            if (colonIndex === -1) {
              continue;
            }
            const key = line.substring(0, colonIndex).toLowerCase();
            const value = line.substring(colonIndex + 1).trim();
            const allValues = result.get(key);
            if (allValues && Array.isArray(allValues)) {
              allValues.push(value);
            } else if (allValues) {
              result.set(key, [allValues, value]);
            } else {
              result.set(key, value);
            }
          }
        }
        return result;
      }
      // This is the 1st message we receive for each request (fired after request creation). Here we will
      // create the span and populate some atttributes, then link the span to the request for further
      // span processing
      onRequestCreated({ request: request4 }) {
        const config = this.getConfig();
        const enabled = config.enabled !== false;
        const shouldIgnoreReq = (0, instrumentation_1.safeExecuteInTheMiddle)(() => !enabled || request4.method === "CONNECT" || config.ignoreRequestHook?.(request4), (e) => e && this._diag.error("caught ignoreRequestHook error: ", e), true);
        if (shouldIgnoreReq) {
          return;
        }
        const startTime = (0, core_1.hrTime)();
        let requestUrl;
        try {
          requestUrl = new url_1.URL(request4.path, request4.origin);
        } catch (err) {
          this._diag.warn("could not determine url.full:", err);
          return;
        }
        const urlScheme = requestUrl.protocol.replace(":", "");
        const requestMethod = this.getRequestMethod(request4.method);
        const attributes = {
          [SemanticAttributes_1.SemanticAttributes.HTTP_REQUEST_METHOD]: requestMethod,
          [SemanticAttributes_1.SemanticAttributes.HTTP_REQUEST_METHOD_ORIGINAL]: request4.method,
          [SemanticAttributes_1.SemanticAttributes.URL_FULL]: requestUrl.toString(),
          [SemanticAttributes_1.SemanticAttributes.URL_PATH]: requestUrl.pathname,
          [SemanticAttributes_1.SemanticAttributes.URL_QUERY]: requestUrl.search,
          [SemanticAttributes_1.SemanticAttributes.URL_SCHEME]: urlScheme
        };
        const schemePorts = { https: "443", http: "80" };
        const serverAddress = requestUrl.hostname;
        const serverPort = requestUrl.port || schemePorts[urlScheme];
        attributes[SemanticAttributes_1.SemanticAttributes.SERVER_ADDRESS] = serverAddress;
        if (serverPort && !isNaN(Number(serverPort))) {
          attributes[SemanticAttributes_1.SemanticAttributes.SERVER_PORT] = Number(serverPort);
        }
        const headersMap = this.parseRequestHeaders(request4);
        const userAgentValues = headersMap.get("user-agent");
        if (userAgentValues) {
          const userAgent = Array.isArray(userAgentValues) ? userAgentValues[userAgentValues.length - 1] : userAgentValues;
          attributes[SemanticAttributes_1.SemanticAttributes.USER_AGENT_ORIGINAL] = userAgent;
        }
        const hookAttributes = (0, instrumentation_1.safeExecuteInTheMiddle)(() => config.startSpanHook?.(request4), (e) => e && this._diag.error("caught startSpanHook error: ", e), true);
        if (hookAttributes) {
          Object.entries(hookAttributes).forEach(([key, val]) => {
            attributes[key] = val;
          });
        }
        const activeCtx = api_1.context.active();
        const currentSpan = api_1.trace.getSpan(activeCtx);
        let span;
        if (config.requireParentforSpans && (!currentSpan || !api_1.trace.isSpanContextValid(currentSpan.spanContext()))) {
          span = api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT);
        } else {
          span = this.tracer.startSpan(requestMethod === "_OTHER" ? "HTTP" : requestMethod, {
            kind: api_1.SpanKind.CLIENT,
            attributes
          }, activeCtx);
        }
        (0, instrumentation_1.safeExecuteInTheMiddle)(() => config.requestHook?.(span, request4), (e) => e && this._diag.error("caught requestHook error: ", e), true);
        const requestContext = api_1.trace.setSpan(api_1.context.active(), span);
        const addedHeaders = {};
        api_1.propagation.inject(requestContext, addedHeaders);
        const headerEntries = Object.entries(addedHeaders);
        for (let i = 0; i < headerEntries.length; i++) {
          const [k, v] = headerEntries[i];
          if (typeof request4.addHeader === "function") {
            request4.addHeader(k, v);
          } else if (typeof request4.headers === "string") {
            request4.headers += `${k}: ${v}\r
`;
          } else if (Array.isArray(request4.headers)) {
            request4.headers.push(k, v);
          }
        }
        this._recordFromReq.set(request4, { span, attributes, startTime });
      }
      // This is the 2nd message we receive for each request. It is fired when connection with
      // the remote is established and about to send the first byte. Here we do have info about the
      // remote address and port so we can populate some `network.*` attributes into the span
      onRequestHeaders({ request: request4, socket }) {
        const record = this._recordFromReq.get(request4);
        if (!record) {
          return;
        }
        const config = this.getConfig();
        const { span } = record;
        const { remoteAddress, remotePort } = socket;
        const spanAttributes = {
          [SemanticAttributes_1.SemanticAttributes.NETWORK_PEER_ADDRESS]: remoteAddress,
          [SemanticAttributes_1.SemanticAttributes.NETWORK_PEER_PORT]: remotePort
        };
        if (config.headersToSpanAttributes?.requestHeaders) {
          const headersToAttribs = new Set(config.headersToSpanAttributes.requestHeaders.map((n) => n.toLowerCase()));
          const headersMap = this.parseRequestHeaders(request4);
          for (const [name, value] of headersMap.entries()) {
            if (headersToAttribs.has(name)) {
              const attrValue = Array.isArray(value) ? value.join(", ") : value;
              spanAttributes[`http.request.header.${name}`] = attrValue;
            }
          }
        }
        span.setAttributes(spanAttributes);
      }
      // This is the 3rd message we get for each request and it's fired when the server
      // headers are received, body may not be accessible yet.
      // From the response headers we can set the status and content length
      onResponseHeaders({ request: request4, response }) {
        const record = this._recordFromReq.get(request4);
        if (!record) {
          return;
        }
        const { span, attributes } = record;
        const spanAttributes = {
          [SemanticAttributes_1.SemanticAttributes.HTTP_RESPONSE_STATUS_CODE]: response.statusCode
        };
        const config = this.getConfig();
        (0, instrumentation_1.safeExecuteInTheMiddle)(() => config.responseHook?.(span, { request: request4, response }), (e) => e && this._diag.error("caught responseHook error: ", e), true);
        const headersToAttribs = /* @__PURE__ */ new Set();
        if (config.headersToSpanAttributes?.responseHeaders) {
          config.headersToSpanAttributes?.responseHeaders.forEach((name) => headersToAttribs.add(name.toLowerCase()));
        }
        for (let idx = 0; idx < response.headers.length; idx = idx + 2) {
          const name = response.headers[idx].toString().toLowerCase();
          const value = response.headers[idx + 1];
          if (headersToAttribs.has(name)) {
            spanAttributes[`http.response.header.${name}`] = value.toString();
          }
          if (name === "content-length") {
            const contentLength = Number(value.toString());
            if (!isNaN(contentLength)) {
              spanAttributes["http.response.header.content-length"] = contentLength;
            }
          }
        }
        span.setAttributes(spanAttributes);
        span.setStatus({
          code: response.statusCode >= 400 ? api_1.SpanStatusCode.ERROR : api_1.SpanStatusCode.UNSET
        });
        record.attributes = Object.assign(attributes, spanAttributes);
      }
      // This is the last event we receive if the request went without any errors
      onDone({ request: request4 }) {
        const record = this._recordFromReq.get(request4);
        if (!record) {
          return;
        }
        const { span, attributes, startTime } = record;
        span.end();
        this._recordFromReq.delete(request4);
        this.recordRequestDuration(attributes, startTime);
      }
      // This is the event we get when something is wrong in the request like
      // - invalid options when calling `fetch` global API or any undici method for request
      // - connectivity errors such as unreachable host
      // - requests aborted through an `AbortController.signal`
      // NOTE: server errors are considered valid responses and it's the lib consumer
      // who should deal with that.
      onError({ request: request4, error }) {
        const record = this._recordFromReq.get(request4);
        if (!record) {
          return;
        }
        const { span, attributes, startTime } = record;
        span.recordException(error);
        span.setStatus({
          code: api_1.SpanStatusCode.ERROR,
          message: error.message
        });
        span.end();
        this._recordFromReq.delete(request4);
        attributes[SemanticAttributes_1.SemanticAttributes.ERROR_TYPE] = error.message;
        this.recordRequestDuration(attributes, startTime);
      }
      recordRequestDuration(attributes, startTime) {
        const metricsAttributes = {};
        const keysToCopy = [
          SemanticAttributes_1.SemanticAttributes.HTTP_RESPONSE_STATUS_CODE,
          SemanticAttributes_1.SemanticAttributes.HTTP_REQUEST_METHOD,
          SemanticAttributes_1.SemanticAttributes.SERVER_ADDRESS,
          SemanticAttributes_1.SemanticAttributes.SERVER_PORT,
          SemanticAttributes_1.SemanticAttributes.URL_SCHEME,
          SemanticAttributes_1.SemanticAttributes.ERROR_TYPE
        ];
        keysToCopy.forEach((key) => {
          if (key in attributes) {
            metricsAttributes[key] = attributes[key];
          }
        });
        const durationSeconds = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)())) / 1e3;
        this._httpClientDurationHistogram.record(durationSeconds, metricsAttributes);
      }
      getRequestMethod(original) {
        const knownMethods = {
          CONNECT: true,
          OPTIONS: true,
          HEAD: true,
          GET: true,
          POST: true,
          PUT: true,
          PATCH: true,
          DELETE: true,
          TRACE: true
        };
        if (original.toUpperCase() in knownMethods) {
          return original.toUpperCase();
        }
        return "_OTHER";
      }
    };
    exports.UndiciInstrumentation = UndiciInstrumentation2;
  }
});

// node_modules/@opentelemetry/instrumentation-undici/build/src/index.js
var require_src31 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-undici/build/src/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UndiciInstrumentation = void 0;
    var undici_1 = require_undici();
    Object.defineProperty(exports, "UndiciInstrumentation", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return undici_1.UndiciInstrumentation;
    }, "get") });
  }
});

// packages/core/src/tools/read-file.ts
init_esbuild_shims();
import path10 from "node:path";
import fs8 from "node:fs/promises";

// packages/core/src/utils/fileUtils.ts
init_esbuild_shims();
import fs2 from "node:fs";
import fsPromises from "node:fs/promises";
import path2 from "node:path";

// packages/core/node_modules/mime/dist/src/index_lite.js
init_esbuild_shims();

// packages/core/node_modules/mime/dist/types/standard.js
init_esbuild_shims();
var types = {
  "application/andrew-inset": ["ez"],
  "application/appinstaller": ["appinstaller"],
  "application/applixware": ["aw"],
  "application/appx": ["appx"],
  "application/appxbundle": ["appxbundle"],
  "application/atom+xml": ["atom"],
  "application/atomcat+xml": ["atomcat"],
  "application/atomdeleted+xml": ["atomdeleted"],
  "application/atomsvc+xml": ["atomsvc"],
  "application/atsc-dwd+xml": ["dwd"],
  "application/atsc-held+xml": ["held"],
  "application/atsc-rsat+xml": ["rsat"],
  "application/automationml-aml+xml": ["aml"],
  "application/automationml-amlx+zip": ["amlx"],
  "application/bdoc": ["bdoc"],
  "application/calendar+xml": ["xcs"],
  "application/ccxml+xml": ["ccxml"],
  "application/cdfx+xml": ["cdfx"],
  "application/cdmi-capability": ["cdmia"],
  "application/cdmi-container": ["cdmic"],
  "application/cdmi-domain": ["cdmid"],
  "application/cdmi-object": ["cdmio"],
  "application/cdmi-queue": ["cdmiq"],
  "application/cpl+xml": ["cpl"],
  "application/cu-seeme": ["cu"],
  "application/cwl": ["cwl"],
  "application/dash+xml": ["mpd"],
  "application/dash-patch+xml": ["mpp"],
  "application/davmount+xml": ["davmount"],
  "application/dicom": ["dcm"],
  "application/docbook+xml": ["dbk"],
  "application/dssc+der": ["dssc"],
  "application/dssc+xml": ["xdssc"],
  "application/ecmascript": ["ecma"],
  "application/emma+xml": ["emma"],
  "application/emotionml+xml": ["emotionml"],
  "application/epub+zip": ["epub"],
  "application/exi": ["exi"],
  "application/express": ["exp"],
  "application/fdf": ["fdf"],
  "application/fdt+xml": ["fdt"],
  "application/font-tdpfr": ["pfr"],
  "application/geo+json": ["geojson"],
  "application/gml+xml": ["gml"],
  "application/gpx+xml": ["gpx"],
  "application/gxf": ["gxf"],
  "application/gzip": ["gz"],
  "application/hjson": ["hjson"],
  "application/hyperstudio": ["stk"],
  "application/inkml+xml": ["ink", "inkml"],
  "application/ipfix": ["ipfix"],
  "application/its+xml": ["its"],
  "application/java-archive": ["jar", "war", "ear"],
  "application/java-serialized-object": ["ser"],
  "application/java-vm": ["class"],
  "application/javascript": ["*js"],
  "application/json": ["json", "map"],
  "application/json5": ["json5"],
  "application/jsonml+json": ["jsonml"],
  "application/ld+json": ["jsonld"],
  "application/lgr+xml": ["lgr"],
  "application/lost+xml": ["lostxml"],
  "application/mac-binhex40": ["hqx"],
  "application/mac-compactpro": ["cpt"],
  "application/mads+xml": ["mads"],
  "application/manifest+json": ["webmanifest"],
  "application/marc": ["mrc"],
  "application/marcxml+xml": ["mrcx"],
  "application/mathematica": ["ma", "nb", "mb"],
  "application/mathml+xml": ["mathml"],
  "application/mbox": ["mbox"],
  "application/media-policy-dataset+xml": ["mpf"],
  "application/mediaservercontrol+xml": ["mscml"],
  "application/metalink+xml": ["metalink"],
  "application/metalink4+xml": ["meta4"],
  "application/mets+xml": ["mets"],
  "application/mmt-aei+xml": ["maei"],
  "application/mmt-usd+xml": ["musd"],
  "application/mods+xml": ["mods"],
  "application/mp21": ["m21", "mp21"],
  "application/mp4": ["*mp4", "*mpg4", "mp4s", "m4p"],
  "application/msix": ["msix"],
  "application/msixbundle": ["msixbundle"],
  "application/msword": ["doc", "dot"],
  "application/mxf": ["mxf"],
  "application/n-quads": ["nq"],
  "application/n-triples": ["nt"],
  "application/node": ["cjs"],
  "application/octet-stream": [
    "bin",
    "dms",
    "lrf",
    "mar",
    "so",
    "dist",
    "distz",
    "pkg",
    "bpk",
    "dump",
    "elc",
    "deploy",
    "exe",
    "dll",
    "deb",
    "dmg",
    "iso",
    "img",
    "msi",
    "msp",
    "msm",
    "buffer"
  ],
  "application/oda": ["oda"],
  "application/oebps-package+xml": ["opf"],
  "application/ogg": ["ogx"],
  "application/omdoc+xml": ["omdoc"],
  "application/onenote": [
    "onetoc",
    "onetoc2",
    "onetmp",
    "onepkg",
    "one",
    "onea"
  ],
  "application/oxps": ["oxps"],
  "application/p2p-overlay+xml": ["relo"],
  "application/patch-ops-error+xml": ["xer"],
  "application/pdf": ["pdf"],
  "application/pgp-encrypted": ["pgp"],
  "application/pgp-keys": ["asc"],
  "application/pgp-signature": ["sig", "*asc"],
  "application/pics-rules": ["prf"],
  "application/pkcs10": ["p10"],
  "application/pkcs7-mime": ["p7m", "p7c"],
  "application/pkcs7-signature": ["p7s"],
  "application/pkcs8": ["p8"],
  "application/pkix-attr-cert": ["ac"],
  "application/pkix-cert": ["cer"],
  "application/pkix-crl": ["crl"],
  "application/pkix-pkipath": ["pkipath"],
  "application/pkixcmp": ["pki"],
  "application/pls+xml": ["pls"],
  "application/postscript": ["ai", "eps", "ps"],
  "application/provenance+xml": ["provx"],
  "application/pskc+xml": ["pskcxml"],
  "application/raml+yaml": ["raml"],
  "application/rdf+xml": ["rdf", "owl"],
  "application/reginfo+xml": ["rif"],
  "application/relax-ng-compact-syntax": ["rnc"],
  "application/resource-lists+xml": ["rl"],
  "application/resource-lists-diff+xml": ["rld"],
  "application/rls-services+xml": ["rs"],
  "application/route-apd+xml": ["rapd"],
  "application/route-s-tsid+xml": ["sls"],
  "application/route-usd+xml": ["rusd"],
  "application/rpki-ghostbusters": ["gbr"],
  "application/rpki-manifest": ["mft"],
  "application/rpki-roa": ["roa"],
  "application/rsd+xml": ["rsd"],
  "application/rss+xml": ["rss"],
  "application/rtf": ["rtf"],
  "application/sbml+xml": ["sbml"],
  "application/scvp-cv-request": ["scq"],
  "application/scvp-cv-response": ["scs"],
  "application/scvp-vp-request": ["spq"],
  "application/scvp-vp-response": ["spp"],
  "application/sdp": ["sdp"],
  "application/senml+xml": ["senmlx"],
  "application/sensml+xml": ["sensmlx"],
  "application/set-payment-initiation": ["setpay"],
  "application/set-registration-initiation": ["setreg"],
  "application/shf+xml": ["shf"],
  "application/sieve": ["siv", "sieve"],
  "application/smil+xml": ["smi", "smil"],
  "application/sparql-query": ["rq"],
  "application/sparql-results+xml": ["srx"],
  "application/sql": ["sql"],
  "application/srgs": ["gram"],
  "application/srgs+xml": ["grxml"],
  "application/sru+xml": ["sru"],
  "application/ssdl+xml": ["ssdl"],
  "application/ssml+xml": ["ssml"],
  "application/swid+xml": ["swidtag"],
  "application/tei+xml": ["tei", "teicorpus"],
  "application/thraud+xml": ["tfi"],
  "application/timestamped-data": ["tsd"],
  "application/toml": ["toml"],
  "application/trig": ["trig"],
  "application/ttml+xml": ["ttml"],
  "application/ubjson": ["ubj"],
  "application/urc-ressheet+xml": ["rsheet"],
  "application/urc-targetdesc+xml": ["td"],
  "application/voicexml+xml": ["vxml"],
  "application/wasm": ["wasm"],
  "application/watcherinfo+xml": ["wif"],
  "application/widget": ["wgt"],
  "application/winhlp": ["hlp"],
  "application/wsdl+xml": ["wsdl"],
  "application/wspolicy+xml": ["wspolicy"],
  "application/xaml+xml": ["xaml"],
  "application/xcap-att+xml": ["xav"],
  "application/xcap-caps+xml": ["xca"],
  "application/xcap-diff+xml": ["xdf"],
  "application/xcap-el+xml": ["xel"],
  "application/xcap-ns+xml": ["xns"],
  "application/xenc+xml": ["xenc"],
  "application/xfdf": ["xfdf"],
  "application/xhtml+xml": ["xhtml", "xht"],
  "application/xliff+xml": ["xlf"],
  "application/xml": ["xml", "xsl", "xsd", "rng"],
  "application/xml-dtd": ["dtd"],
  "application/xop+xml": ["xop"],
  "application/xproc+xml": ["xpl"],
  "application/xslt+xml": ["*xsl", "xslt"],
  "application/xspf+xml": ["xspf"],
  "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"],
  "application/yang": ["yang"],
  "application/yin+xml": ["yin"],
  "application/zip": ["zip"],
  "application/zip+dotlottie": ["lottie"],
  "audio/3gpp": ["*3gpp"],
  "audio/aac": ["adts", "aac"],
  "audio/adpcm": ["adp"],
  "audio/amr": ["amr"],
  "audio/basic": ["au", "snd"],
  "audio/midi": ["mid", "midi", "kar", "rmi"],
  "audio/mobile-xmf": ["mxmf"],
  "audio/mp3": ["*mp3"],
  "audio/mp4": ["m4a", "mp4a", "m4b"],
  "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"],
  "audio/ogg": ["oga", "ogg", "spx", "opus"],
  "audio/s3m": ["s3m"],
  "audio/silk": ["sil"],
  "audio/wav": ["wav"],
  "audio/wave": ["*wav"],
  "audio/webm": ["weba"],
  "audio/xm": ["xm"],
  "font/collection": ["ttc"],
  "font/otf": ["otf"],
  "font/ttf": ["ttf"],
  "font/woff": ["woff"],
  "font/woff2": ["woff2"],
  "image/aces": ["exr"],
  "image/apng": ["apng"],
  "image/avci": ["avci"],
  "image/avcs": ["avcs"],
  "image/avif": ["avif"],
  "image/bmp": ["bmp", "dib"],
  "image/cgm": ["cgm"],
  "image/dicom-rle": ["drle"],
  "image/dpx": ["dpx"],
  "image/emf": ["emf"],
  "image/fits": ["fits"],
  "image/g3fax": ["g3"],
  "image/gif": ["gif"],
  "image/heic": ["heic"],
  "image/heic-sequence": ["heics"],
  "image/heif": ["heif"],
  "image/heif-sequence": ["heifs"],
  "image/hej2k": ["hej2"],
  "image/ief": ["ief"],
  "image/jaii": ["jaii"],
  "image/jais": ["jais"],
  "image/jls": ["jls"],
  "image/jp2": ["jp2", "jpg2"],
  "image/jpeg": ["jpg", "jpeg", "jpe"],
  "image/jph": ["jph"],
  "image/jphc": ["jhc"],
  "image/jpm": ["jpm", "jpgm"],
  "image/jpx": ["jpx", "jpf"],
  "image/jxl": ["jxl"],
  "image/jxr": ["jxr"],
  "image/jxra": ["jxra"],
  "image/jxrs": ["jxrs"],
  "image/jxs": ["jxs"],
  "image/jxsc": ["jxsc"],
  "image/jxsi": ["jxsi"],
  "image/jxss": ["jxss"],
  "image/ktx": ["ktx"],
  "image/ktx2": ["ktx2"],
  "image/pjpeg": ["jfif"],
  "image/png": ["png"],
  "image/sgi": ["sgi"],
  "image/svg+xml": ["svg", "svgz"],
  "image/t38": ["t38"],
  "image/tiff": ["tif", "tiff"],
  "image/tiff-fx": ["tfx"],
  "image/webp": ["webp"],
  "image/wmf": ["wmf"],
  "message/disposition-notification": ["disposition-notification"],
  "message/global": ["u8msg"],
  "message/global-delivery-status": ["u8dsn"],
  "message/global-disposition-notification": ["u8mdn"],
  "message/global-headers": ["u8hdr"],
  "message/rfc822": ["eml", "mime", "mht", "mhtml"],
  "model/3mf": ["3mf"],
  "model/gltf+json": ["gltf"],
  "model/gltf-binary": ["glb"],
  "model/iges": ["igs", "iges"],
  "model/jt": ["jt"],
  "model/mesh": ["msh", "mesh", "silo"],
  "model/mtl": ["mtl"],
  "model/obj": ["obj"],
  "model/prc": ["prc"],
  "model/step": ["step", "stp", "stpnc", "p21", "210"],
  "model/step+xml": ["stpx"],
  "model/step+zip": ["stpz"],
  "model/step-xml+zip": ["stpxz"],
  "model/stl": ["stl"],
  "model/u3d": ["u3d"],
  "model/vrml": ["wrl", "vrml"],
  "model/x3d+binary": ["*x3db", "x3dbz"],
  "model/x3d+fastinfoset": ["x3db"],
  "model/x3d+vrml": ["*x3dv", "x3dvz"],
  "model/x3d+xml": ["x3d", "x3dz"],
  "model/x3d-vrml": ["x3dv"],
  "text/cache-manifest": ["appcache", "manifest"],
  "text/calendar": ["ics", "ifb"],
  "text/coffeescript": ["coffee", "litcoffee"],
  "text/css": ["css"],
  "text/csv": ["csv"],
  "text/html": ["html", "htm", "shtml"],
  "text/jade": ["jade"],
  "text/javascript": ["js", "mjs"],
  "text/jsx": ["jsx"],
  "text/less": ["less"],
  "text/markdown": ["md", "markdown"],
  "text/mathml": ["mml"],
  "text/mdx": ["mdx"],
  "text/n3": ["n3"],
  "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"],
  "text/richtext": ["rtx"],
  "text/rtf": ["*rtf"],
  "text/sgml": ["sgml", "sgm"],
  "text/shex": ["shex"],
  "text/slim": ["slim", "slm"],
  "text/spdx": ["spdx"],
  "text/stylus": ["stylus", "styl"],
  "text/tab-separated-values": ["tsv"],
  "text/troff": ["t", "tr", "roff", "man", "me", "ms"],
  "text/turtle": ["ttl"],
  "text/uri-list": ["uri", "uris", "urls"],
  "text/vcard": ["vcard"],
  "text/vtt": ["vtt"],
  "text/wgsl": ["wgsl"],
  "text/xml": ["*xml"],
  "text/yaml": ["yaml", "yml"],
  "video/3gpp": ["3gp", "3gpp"],
  "video/3gpp2": ["3g2"],
  "video/h261": ["h261"],
  "video/h263": ["h263"],
  "video/h264": ["h264"],
  "video/iso.segment": ["m4s"],
  "video/jpeg": ["jpgv"],
  "video/jpm": ["*jpm", "*jpgm"],
  "video/mj2": ["mj2", "mjp2"],
  "video/mp2t": ["ts", "m2t", "m2ts", "mts"],
  "video/mp4": ["mp4", "mp4v", "mpg4"],
  "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"],
  "video/ogg": ["ogv"],
  "video/quicktime": ["qt", "mov"],
  "video/webm": ["webm"]
};
Object.freeze(types);
var standard_default = types;

// packages/core/node_modules/mime/dist/src/Mime.js
init_esbuild_shims();
var __classPrivateFieldGet = function(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _Mime_extensionToType;
var _Mime_typeToExtension;
var _Mime_typeToExtensions;
var Mime = class {
  static {
    __name(this, "Mime");
  }
  constructor(...args) {
    _Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
    _Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
    _Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
    for (const arg of args) {
      this.define(arg);
    }
  }
  define(typeMap, force = false) {
    for (let [type, extensions] of Object.entries(typeMap)) {
      type = type.toLowerCase();
      extensions = extensions.map((ext) => ext.toLowerCase());
      if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
        __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
      }
      const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
      let first = true;
      for (let extension of extensions) {
        const starred = extension.startsWith("*");
        extension = starred ? extension.slice(1) : extension;
        allExtensions?.add(extension);
        if (first) {
          __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
        }
        first = false;
        if (starred)
          continue;
        const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
        if (currentType && currentType != type && !force) {
          throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
        }
        __classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
      }
    }
    return this;
  }
  getType(path11) {
    if (typeof path11 !== "string")
      return null;
    const last = path11.replace(/^.*[/\\]/s, "").toLowerCase();
    const ext = last.replace(/^.*\./s, "").toLowerCase();
    const hasPath = last.length < path11.length;
    const hasDot = ext.length < last.length - 1;
    if (!hasDot && hasPath)
      return null;
    return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
  }
  getExtension(type) {
    if (typeof type !== "string")
      return null;
    type = type?.split?.(";")[0];
    return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
  }
  getAllExtensions(type) {
    if (typeof type !== "string")
      return null;
    return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
  }
  _freeze() {
    this.define = () => {
      throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
    };
    Object.freeze(this);
    for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
      Object.freeze(extensions);
    }
    return this;
  }
  _getTestState() {
    return {
      types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
      extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f")
    };
  }
};
_Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
var Mime_default = Mime;

// packages/core/node_modules/mime/dist/src/index_lite.js
var index_lite_default = new Mime_default(standard_default)._freeze();

// packages/core/src/utils/iconvHelper.ts
init_esbuild_shims();
var import_iconv_lite = __toESM(require_lib(), 1);
var iconvLite = import_iconv_lite.default;
function iconvDecode(buffer, encoding) {
  return iconvLite.decode(buffer, encoding);
}
__name(iconvDecode, "iconvDecode");
function iconvEncode(content, encoding) {
  return iconvLite.encode(content, encoding);
}
__name(iconvEncode, "iconvEncode");
function iconvEncodingExists(encoding) {
  return iconvLite.encodingExists(encoding);
}
__name(iconvEncodingExists, "iconvEncodingExists");
function isUtf8CompatibleEncoding(encoding) {
  const lower = encoding.toLowerCase().replace(/[^a-z0-9]/g, "");
  return lower === "utf8" || lower === "ascii" || lower === "usascii";
}
__name(isUtf8CompatibleEncoding, "isUtf8CompatibleEncoding");

// packages/core/src/utils/ignorePatterns.ts
init_esbuild_shims();
import path from "node:path";

// packages/core/src/memory/const.ts
init_esbuild_shims();
var DEFAULT_CONTEXT_FILENAME = "QWEN.md";
var AGENT_CONTEXT_FILENAME = "AGENTS.md";
var LOCAL_CONTEXT_FILENAME = "QWEN.local.md";
var MEMORY_SECTION_HEADER = "## Qwen Added Memories";
var currentGeminiMdFilename = [
  DEFAULT_CONTEXT_FILENAME,
  AGENT_CONTEXT_FILENAME
];
function setGeminiMdFilename(newFilename) {
  if (Array.isArray(newFilename)) {
    if (newFilename.length > 0) {
      currentGeminiMdFilename = newFilename.map((name) => name.trim());
    }
  } else if (newFilename && newFilename.trim() !== "") {
    currentGeminiMdFilename = newFilename.trim();
  }
}
__name(setGeminiMdFilename, "setGeminiMdFilename");
function getCurrentGeminiMdFilename() {
  if (Array.isArray(currentGeminiMdFilename)) {
    for (const entry of currentGeminiMdFilename) {
      if (typeof entry === "string" && entry.trim() !== "") {
        return entry.trim();
      }
    }
    return DEFAULT_CONTEXT_FILENAME;
  }
  return currentGeminiMdFilename;
}
__name(getCurrentGeminiMdFilename, "getCurrentGeminiMdFilename");
function getAllGeminiMdFilenames() {
  if (Array.isArray(currentGeminiMdFilename)) {
    return currentGeminiMdFilename;
  }
  return [currentGeminiMdFilename];
}
__name(getAllGeminiMdFilenames, "getAllGeminiMdFilenames");

// packages/core/src/utils/ignorePatterns.ts
var COMMON_IGNORE_PATTERNS = [
  "**/node_modules/**",
  "**/.git/**",
  "**/bower_components/**",
  "**/.svn/**",
  "**/.hg/**"
];
var BINARY_FILE_PATTERNS = [
  "**/*.bin",
  "**/*.exe",
  "**/*.dll",
  "**/*.so",
  "**/*.dylib",
  "**/*.class",
  "**/*.jar",
  "**/*.war",
  "**/*.zip",
  "**/*.tar",
  "**/*.gz",
  "**/*.bz2",
  "**/*.rar",
  "**/*.7z",
  "**/*.doc",
  "**/*.docx",
  "**/*.xls",
  "**/*.xlsx",
  "**/*.ppt",
  "**/*.pptx",
  "**/*.odt",
  "**/*.ods",
  "**/*.odp"
];
var MEDIA_FILE_PATTERNS = [
  "**/*.pdf",
  "**/*.png",
  "**/*.jpg",
  "**/*.jpeg",
  "**/*.gif",
  "**/*.webp",
  "**/*.bmp",
  "**/*.svg"
];
var COMMON_DIRECTORY_EXCLUDES = [
  "**/.vscode/**",
  "**/.idea/**",
  "**/dist/**",
  "**/build/**",
  "**/coverage/**",
  "**/__pycache__/**"
];
var PYTHON_EXCLUDES = ["**/*.pyc", "**/*.pyo"];
var SYSTEM_FILE_EXCLUDES = ["**/.DS_Store", "**/.env"];
var DEFAULT_FILE_EXCLUDES = [
  ...COMMON_IGNORE_PATTERNS,
  ...COMMON_DIRECTORY_EXCLUDES,
  ...BINARY_FILE_PATTERNS,
  ...PYTHON_EXCLUDES,
  ...SYSTEM_FILE_EXCLUDES
];
var FileExclusions = class {
  constructor(config) {
    this.config = config;
  }
  static {
    __name(this, "FileExclusions");
  }
  /**
   * Gets core ignore patterns for basic file operations like glob.
   * These are the minimal essential patterns that should almost always be excluded.
   */
  getCoreIgnorePatterns() {
    return [...COMMON_IGNORE_PATTERNS];
  }
  /**
   * Gets comprehensive default exclusion patterns for operations like read-many-files.
   * Includes all standard exclusions: directories, binary files, system files, etc.
   */
  getDefaultExcludePatterns(options = {}) {
    const {
      includeDefaults = true,
      customPatterns = [],
      runtimePatterns = [],
      includeDynamicPatterns = true
    } = options;
    const patterns = [];
    if (includeDefaults) {
      patterns.push(...DEFAULT_FILE_EXCLUDES);
    }
    if (includeDynamicPatterns) {
      for (const filename of getAllGeminiMdFilenames()) {
        patterns.push(`**/${filename}`);
      }
    }
    if (this.config) {
      const configCustomExcludes = this.config.getCustomExcludes?.() ?? [];
      patterns.push(...configCustomExcludes);
    }
    patterns.push(...customPatterns);
    patterns.push(...runtimePatterns);
    return patterns;
  }
  /**
   * Gets exclude patterns for read-many-files tool with legacy compatibility.
   * This maintains the same behavior as the previous getDefaultExcludes() function.
   */
  getReadManyFilesExcludes(additionalExcludes = []) {
    return this.getDefaultExcludePatterns({
      includeDefaults: true,
      runtimePatterns: additionalExcludes,
      includeDynamicPatterns: true
    });
  }
  /**
   * Gets exclude patterns for glob tool operations.
   * Uses core patterns by default but can be extended with additional patterns.
   */
  getGlobExcludes(additionalExcludes = []) {
    const corePatterns = this.getCoreIgnorePatterns();
    const configPatterns = this.config?.getCustomExcludes?.() ?? [];
    return [...corePatterns, ...configPatterns, ...additionalExcludes];
  }
  /**
   * Builds exclude patterns with full customization options.
   * This is the most flexible method for advanced use cases.
   */
  buildExcludePatterns(options) {
    return this.getDefaultExcludePatterns(options);
  }
};
function extractExtensionsFromPatterns(patterns) {
  const extensions = new Set(
    patterns.filter((pattern) => pattern.includes("*.")).flatMap((pattern) => {
      const extPart = pattern.substring(pattern.lastIndexOf("*.") + 1);
      if (extPart.startsWith(".{") && extPart.endsWith("}")) {
        const inner = extPart.slice(2, -1);
        return inner.split(",").map((ext) => `.${ext.trim()}`).filter((ext) => ext !== ".");
      }
      if (extPart.startsWith(".") && !extPart.includes("/") && !extPart.includes("{") && !extPart.includes("}")) {
        const extracted = path.extname(`dummy${extPart}`);
        const result = extracted || extPart;
        return result && result !== "." && !result.substring(1).includes(".") ? [result] : [];
      }
      return [];
    })
  );
  return Array.from(extensions).sort();
}
__name(extractExtensionsFromPatterns, "extractExtensionsFromPatterns");
var BINARY_EXTENSIONS = [
  ...extractExtensionsFromPatterns([
    ...BINARY_FILE_PATTERNS,
    ...MEDIA_FILE_PATTERNS,
    ...PYTHON_EXCLUDES
  ]),
  // Additional binary extensions not in the main patterns
  ".obj",
  ".o",
  ".a",
  ".lib",
  ".wasm"
].sort();

// packages/core/src/utils/systemEncoding.ts
init_esbuild_shims();
var import_chardet = __toESM(require_lib2(), 1);
import { isUtf8 } from "node:buffer";
import { execSync } from "node:child_process";
import os from "node:os";
var debugLogger = createDebugLogger("ENCODING");
var cachedSystemEncoding = void 0;
function resetEncodingCache() {
  cachedSystemEncoding = void 0;
}
__name(resetEncodingCache, "resetEncodingCache");
function getCachedEncodingForBuffer(buffer) {
  if (isUtf8(buffer)) {
    return "utf-8";
  }
  const detected = detectEncodingFromBuffer(buffer);
  if (detected) {
    return detected;
  }
  if (cachedSystemEncoding === void 0) {
    cachedSystemEncoding = getSystemEncoding();
  }
  if (cachedSystemEncoding) {
    return cachedSystemEncoding;
  }
  return "utf-8";
}
__name(getCachedEncodingForBuffer, "getCachedEncodingForBuffer");
function getSystemEncoding() {
  if (os.platform() === "win32") {
    try {
      const output = execSync("chcp", { encoding: "utf8" });
      const match2 = output.match(/:\s*(\d+)/);
      if (match2) {
        const codePage = parseInt(match2[1], 10);
        if (!isNaN(codePage)) {
          return windowsCodePageToEncoding(codePage);
        }
      }
      throw new Error(
        `Unable to parse Windows code page from 'chcp' output "${output.trim()}". `
      );
    } catch (error) {
      debugLogger.warn(
        `Failed to get Windows code page using 'chcp' command: ${error instanceof Error ? error.message : String(error)}. Will attempt to detect encoding from command output instead.`
      );
    }
    return null;
  }
  const env = process.env;
  let locale = env["LC_ALL"] || env["LC_CTYPE"] || env["LANG"] || "";
  if (!locale) {
    try {
      locale = execSync("locale charmap", { encoding: "utf8" }).toString().trim();
    } catch (_e) {
      debugLogger.warn("Failed to get locale charmap.");
      return null;
    }
  }
  const match = locale.match(/\.(.+)/);
  if (match && match[1]) {
    return match[1].toLowerCase();
  }
  if (locale && !locale.includes(".")) {
    return locale.toLowerCase();
  }
  return null;
}
__name(getSystemEncoding, "getSystemEncoding");
function windowsCodePageToEncoding(cp) {
  const map = {
    437: "cp437",
    850: "cp850",
    852: "cp852",
    866: "cp866",
    874: "windows-874",
    932: "shift_jis",
    936: "gbk",
    949: "euc-kr",
    950: "big5",
    1200: "utf-16le",
    1201: "utf-16be",
    1250: "windows-1250",
    1251: "windows-1251",
    1252: "windows-1252",
    1253: "windows-1253",
    1254: "windows-1254",
    1255: "windows-1255",
    1256: "windows-1256",
    1257: "windows-1257",
    1258: "windows-1258",
    65001: "utf-8"
  };
  if (map[cp]) {
    return map[cp];
  }
  debugLogger.warn(`Unable to determine encoding for windows code page ${cp}.`);
  return null;
}
__name(windowsCodePageToEncoding, "windowsCodePageToEncoding");
function detectEncodingFromBuffer(buffer) {
  try {
    const detected = (0, import_chardet.detect)(buffer);
    if (detected && typeof detected === "string") {
      return detected.toLowerCase();
    }
  } catch (error) {
    debugLogger.warn("Failed to detect encoding with chardet:", error);
  }
  return null;
}
__name(detectEncodingFromBuffer, "detectEncodingFromBuffer");

// packages/core/src/utils/pdf.ts
init_esbuild_shims();
import { execFile } from "node:child_process";
var MAX_PDF_TEXT_OUTPUT_CHARS = 1e5;
var MAX_PDF_PAGE_NUMBER = 1e6;
function execCommand(command, args, options = {}) {
  return new Promise((resolve2) => {
    execFile(
      command,
      args,
      { encoding: "utf8", ...options },
      (error, stdout, stderr) => {
        if (error) {
          const errAny = error;
          const maxBufferExceeded = errAny.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
          const timedOut = !maxBufferExceeded && (errAny.code === "ETIMEDOUT" || errAny.killed === true && (errAny.signal === "SIGTERM" || errAny.signal === void 0 || errAny.signal === null));
          resolve2({
            stdout: String(stdout ?? ""),
            stderr: String(stderr ?? ""),
            code: typeof error.code === "number" ? error.code : 1,
            maxBufferExceeded,
            timedOut
          });
          return;
        }
        resolve2({
          stdout: String(stdout ?? ""),
          stderr: String(stderr ?? ""),
          code: 0,
          maxBufferExceeded: false,
          timedOut: false
        });
      }
    );
  });
}
__name(execCommand, "execCommand");
function parsePDFPageRange(pages) {
  const trimmed = pages.trim();
  if (!trimmed) {
    return null;
  }
  const inRange = /* @__PURE__ */ __name((n) => Number.isFinite(n) && n >= 1 && n <= MAX_PDF_PAGE_NUMBER, "inRange");
  const openEnded = /^(\d+)\s*-$/.exec(trimmed);
  if (openEnded) {
    const first = Number(openEnded[1]);
    if (!inRange(first)) return null;
    return { firstPage: first, lastPage: Infinity };
  }
  const range = /^(\d+)\s*-\s*(\d+)$/.exec(trimmed);
  if (range) {
    const first = Number(range[1]);
    const last = Number(range[2]);
    if (!inRange(first) || !inRange(last) || last < first) return null;
    return { firstPage: first, lastPage: last };
  }
  const single = /^(\d+)$/.exec(trimmed);
  if (single) {
    const page = Number(single[1]);
    if (!inRange(page)) return null;
    return { firstPage: page, lastPage: page };
  }
  return null;
}
__name(parsePDFPageRange, "parsePDFPageRange");
var pdftotextAvailable;
var pdftotextAvailablePromise;
async function isPdftotextAvailable() {
  if (pdftotextAvailable !== void 0) return pdftotextAvailable;
  if (pdftotextAvailablePromise) return pdftotextAvailablePromise;
  pdftotextAvailablePromise = (async () => {
    try {
      const { code } = await execCommand("pdftotext", ["-v"], {
        timeout: 5e3
      });
      return code === 0;
    } catch {
      return false;
    }
  })().then((result) => {
    pdftotextAvailable = result;
    return result;
  }).finally(() => {
    pdftotextAvailablePromise = void 0;
  });
  return pdftotextAvailablePromise;
}
__name(isPdftotextAvailable, "isPdftotextAvailable");
async function extractPDFText(filePath, options) {
  const available = await isPdftotextAvailable();
  if (!available) {
    return {
      success: false,
      error: "pdftotext is not installed. Install poppler-utils to enable PDF text extraction (e.g. `apt-get install poppler-utils` or `brew install poppler`)."
    };
  }
  const args = ["-layout"];
  if (options?.firstPage) {
    args.push("-f", String(options.firstPage));
  }
  if (options?.lastPage && options.lastPage !== Infinity) {
    args.push("-l", String(options.lastPage));
  }
  args.push("--", filePath, "-");
  try {
    const { stdout, stderr, code, maxBufferExceeded, timedOut } = await execCommand("pdftotext", args, {
      timeout: 3e4,
      // Keep the buffer just above MAX_PDF_TEXT_OUTPUT_CHARS — anything
      // past that is going to be truncated anyway, and capping the child
      // prevents unbounded memory use on pathological text-dense PDFs.
      maxBuffer: MAX_PDF_TEXT_OUTPUT_CHARS * 2
    });
    if (timedOut) {
      return {
        success: false,
        error: `pdftotext timed out after 30s. The PDF may be unusually large or complex; try the 'pages' parameter to narrow the range.`
      };
    }
    if (maxBufferExceeded && stdout.length >= MAX_PDF_TEXT_OUTPUT_CHARS) {
      return {
        success: true,
        text: stdout.substring(0, MAX_PDF_TEXT_OUTPUT_CHARS) + `

... [text truncated at ${MAX_PDF_TEXT_OUTPUT_CHARS} characters. Use the 'pages' parameter to read specific page ranges.]`
      };
    }
    if (code !== 0 || maxBufferExceeded) {
      if (/password/i.test(stderr)) {
        return {
          success: false,
          error: "PDF is password-protected. Please provide an unprotected version."
        };
      }
      if (/damaged|corrupt|invalid/i.test(stderr)) {
        return {
          success: false,
          error: "PDF file is corrupted or invalid."
        };
      }
      return {
        success: false,
        error: `pdftotext failed: ${stderr || "(no stderr)"}`
      };
    }
    if (!stdout.trim()) {
      return {
        success: false,
        error: "pdftotext produced no text output. The PDF may contain only images."
      };
    }
    if (stdout.length > MAX_PDF_TEXT_OUTPUT_CHARS) {
      return {
        success: true,
        text: stdout.substring(0, MAX_PDF_TEXT_OUTPUT_CHARS) + `

... [text truncated at ${MAX_PDF_TEXT_OUTPUT_CHARS} characters. Use the 'pages' parameter to read specific page ranges.]`
      };
    }
    return { success: true, text: stdout };
  } catch (e) {
    return {
      success: false,
      error: `pdftotext execution failed: ${e instanceof Error ? e.message : String(e)}`
    };
  }
}
__name(extractPDFText, "extractPDFText");

// packages/core/src/utils/notebook.ts
init_esbuild_shims();
import fs from "node:fs";
var LARGE_OUTPUT_THRESHOLD = 1e4;
var MAX_NOTEBOOK_OUTPUT_CHARS = 1e5;
var ANSI_ESCAPE_RE = /\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P_^X][^\x1B]*\x1B\\|[@-Z\\-_])/g;
function stripAnsi(input) {
  return input.replace(ANSI_ESCAPE_RE, "");
}
__name(stripAnsi, "stripAnsi");
var MIME_TYPE_RE = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:\+[A-Za-z0-9!#$&^_.+-]+)?$/;
function sanitizeMimeTypes(keys) {
  return keys.filter((k) => MIME_TYPE_RE.test(k));
}
__name(sanitizeMimeTypes, "sanitizeMimeTypes");
function normalizeSource(source) {
  return Array.isArray(source) ? source.join("") : source;
}
__name(normalizeSource, "normalizeSource");
function parseNotebook(content) {
  const jsonContent = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
  const parsed = JSON.parse(jsonContent);
  if (!parsed || typeof parsed !== "object") {
    throw new Error("Invalid notebook: expected a JSON object");
  }
  const notebook = parsed;
  if (!Array.isArray(notebook.cells)) {
    throw new Error("Invalid notebook: missing cells array");
  }
  for (let i = 0; i < notebook.cells.length; i++) {
    const cell = notebook.cells[i];
    if (!cell || typeof cell !== "object" || Array.isArray(cell)) {
      throw new Error(`Invalid notebook: cell at index ${i} is not an object`);
    }
  }
  return notebook;
}
__name(parseNotebook, "parseNotebook");
function inferNotebookJsonFormat(content) {
  const lineMatch = content.match(/\n([ \t]+)"/);
  const indent = lineMatch?.[1];
  let inferredIndent;
  if (indent !== void 0) {
    inferredIndent = /^ +$/.test(indent) ? indent.length : indent;
  }
  return {
    indent: inferredIndent,
    trailingNewline: content.endsWith("\n")
  };
}
__name(inferNotebookJsonFormat, "inferNotebookJsonFormat");
function serializeNotebook(notebook, format = { indent: 1, trailingNewline: true }) {
  const serialized = JSON.stringify(notebook, null, format.indent);
  return format.trailingNewline ? `${serialized}
` : serialized;
}
__name(serializeNotebook, "serializeNotebook");
function getCellDisplayId(cell, index) {
  return typeof cell.id === "string" && cell.id.length > 0 ? cell.id : `cell-${index}`;
}
__name(getCellDisplayId, "getCellDisplayId");
function hasStableCellIds(notebook) {
  return notebook.cells.every(
    (cell) => typeof cell.id === "string" && cell.id.length > 0
  );
}
__name(hasStableCellIds, "hasStableCellIds");
function findCellIndexesByDisplayId(notebook, cellId) {
  const indexes = [];
  notebook.cells.forEach((cell, index) => {
    if (getCellDisplayId(cell, index) === cellId) {
      indexes.push(index);
    }
  });
  return indexes;
}
__name(findCellIndexesByDisplayId, "findCellIndexesByDisplayId");
function isAmbiguousCellId(notebook, cellId) {
  return findCellIndexesByDisplayId(notebook, cellId).length > 1;
}
__name(isAmbiguousCellId, "isAmbiguousCellId");
function findCellIndex(notebook, cellId) {
  const indexes = findCellIndexesByDisplayId(notebook, cellId);
  return indexes.length === 1 ? indexes[0] : -1;
}
__name(findCellIndex, "findCellIndex");
function getNotebookLanguage(notebook) {
  return notebook.metadata?.language_info?.name ?? notebook.metadata?.kernelspec?.language ?? "python";
}
__name(getNotebookLanguage, "getNotebookLanguage");
function shouldGenerateCellIds(notebook) {
  return (notebook.nbformat ?? 0) > 4 || (notebook.nbformat ?? 0) === 4 && (notebook.nbformat_minor ?? 0) >= 5;
}
__name(shouldGenerateCellIds, "shouldGenerateCellIds");
function makeCellId(notebook) {
  if (!shouldGenerateCellIds(notebook)) {
    return void 0;
  }
  const existingDisplayIds = new Set(
    notebook.cells.map((cell, index) => getCellDisplayId(cell, index))
  );
  let fallbackIndex = 1;
  let fallback = `qwen-cell-${fallbackIndex}`;
  while (existingDisplayIds.has(fallback)) {
    fallbackIndex++;
    fallback = `qwen-cell-${fallbackIndex}`;
  }
  return fallback;
}
__name(makeCellId, "makeCellId");
function inferNotebookSourceArrayStyle(notebook) {
  const sourceCell = notebook.cells.find((cell) => cell.source !== void 0);
  return sourceCell ? Array.isArray(sourceCell.source) : true;
}
__name(inferNotebookSourceArrayStyle, "inferNotebookSourceArrayStyle");
function inferInsertedCellSourceArrayStyle(notebook, insertAt) {
  const previousCell = notebook.cells[insertAt - 1];
  if (previousCell?.source !== void 0) {
    return Array.isArray(previousCell.source);
  }
  const nextCell = notebook.cells[insertAt];
  if (nextCell?.source !== void 0) {
    return Array.isArray(nextCell.source);
  }
  return inferNotebookSourceArrayStyle(notebook);
}
__name(inferInsertedCellSourceArrayStyle, "inferInsertedCellSourceArrayStyle");
function toNotebookSource(source, preferArray) {
  if (!preferArray) {
    return source;
  }
  if (source.length === 0) {
    return [];
  }
  const lines = [];
  let start = 0;
  for (let i = 0; i < source.length; i++) {
    if (source[i] === "\n") {
      lines.push(source.slice(start, i + 1));
      start = i + 1;
    }
  }
  if (start < source.length) {
    lines.push(source.slice(start));
  }
  return lines;
}
__name(toNotebookSource, "toNotebookSource");
function normalizeEditedCell(cell, finalType) {
  cell.cell_type = finalType;
  cell.metadata ??= {};
  if (finalType === "code") {
    cell.execution_count = null;
    cell.outputs = [];
    return;
  }
  delete cell.execution_count;
  delete cell.outputs;
}
__name(normalizeEditedCell, "normalizeEditedCell");
function processOutputText(text) {
  if (!text) return "";
  return Array.isArray(text) ? text.join("") : text;
}
__name(processOutputText, "processOutputText");
function processOutput(output) {
  switch (output.output_type) {
    case "stream":
      return stripAnsi(processOutputText(output.text));
    case "execute_result":
    case "display_data": {
      const textData = output.data?.["text/plain"];
      if (typeof textData === "string") return stripAnsi(textData);
      if (Array.isArray(textData)) return stripAnsi(textData.join(""));
      const mimeTypes = output.data ? sanitizeMimeTypes(Object.keys(output.data)) : [];
      if (mimeTypes.length > 0) {
        return `[non-text output: ${mimeTypes.join(", ")}]`;
      }
      return "";
    }
    case "error": {
      const parts = [];
      if (output.ename) parts.push(output.ename);
      if (output.evalue) parts.push(output.evalue);
      if (output.traceback?.length) {
        parts.push(output.traceback.join("\n"));
      }
      return stripAnsi(parts.join(": "));
    }
    default:
      return "";
  }
}
__name(processOutput, "processOutput");
function processCell(cell, index, language) {
  const cellId = getCellDisplayId(cell, index);
  const source = normalizeSource(cell.source);
  const parts = [];
  switch (cell.cell_type) {
    case "code": {
      const execLabel = cell.execution_count != null ? ` [${cell.execution_count}]` : "";
      parts.push(`--- Code Cell ${cellId}${execLabel} ---`);
      parts.push(`\`\`\`${language}`);
      parts.push(source);
      parts.push("```");
      if (cell.outputs?.length) {
        const outputTexts = cell.outputs.map(processOutput).filter((t) => t.length > 0);
        if (outputTexts.length > 0) {
          let combined = outputTexts.join("\n");
          if (combined.length > LARGE_OUTPUT_THRESHOLD) {
            combined = combined.substring(0, LARGE_OUTPUT_THRESHOLD) + `
... [output truncated, total ${combined.length} chars. Use shell: cat <notebook_path> | jq '.cells[${index}].outputs']`;
          }
          parts.push("Output:");
          parts.push(combined);
        }
      }
      break;
    }
    case "markdown":
      parts.push(`--- Markdown Cell ${cellId} ---`);
      parts.push(source);
      break;
    case "raw":
      parts.push(`--- Raw Cell ${cellId} ---`);
      parts.push(source);
      break;
    default:
      parts.push(`--- Cell ${cellId} ---`);
      parts.push(source);
      break;
  }
  return parts.join("\n");
}
__name(processCell, "processCell");
async function readNotebookWithMetadata(filePath) {
  const raw = await fs.promises.readFile(filePath, "utf-8");
  const notebook = parseNotebook(raw);
  const language = getNotebookLanguage(notebook);
  if (!notebook.cells || notebook.cells.length === 0) {
    return { content: "(empty notebook)", isTruncated: false };
  }
  const header = `Jupyter Notebook (${language}, ${notebook.cells.length} cells)`;
  const cellTexts = [];
  let totalLength = header.length;
  let isTruncated = false;
  for (let i = 0; i < notebook.cells.length; i++) {
    const cellText = processCell(notebook.cells[i], i, language);
    totalLength += cellText.length + 2;
    if (totalLength > MAX_NOTEBOOK_OUTPUT_CHARS) {
      isTruncated = true;
      cellTexts.push(
        `... [${notebook.cells.length - i} remaining cells truncated, total ${notebook.cells.length} cells. Use shell to inspect: cat <path> | jq '.cells[${i}:]']`
      );
      break;
    }
    cellTexts.push(cellText);
  }
  return {
    content: `${header}

${cellTexts.join("\n\n")}`,
    isTruncated
  };
}
__name(readNotebookWithMetadata, "readNotebookWithMetadata");

// packages/core/src/utils/fileUtils.ts
var debugLogger2 = createDebugLogger("FILE_UTILS");
var DEFAULT_ENCODING = "utf-8";
var PDF_EXTRACTION_MAX_MB = 100;
function detectBOM(buf) {
  if (buf.length >= 4) {
    if (buf[0] === 255 && buf[1] === 254 && buf[2] === 0 && buf[3] === 0) {
      return { encoding: "utf32le", bomLength: 4 };
    }
    if (buf[0] === 0 && buf[1] === 0 && buf[2] === 254 && buf[3] === 255) {
      return { encoding: "utf32be", bomLength: 4 };
    }
  }
  if (buf.length >= 3) {
    if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) {
      return { encoding: "utf8", bomLength: 3 };
    }
  }
  if (buf.length >= 2) {
    if (buf[0] === 255 && buf[1] === 254 && (buf.length < 4 || buf[2] !== 0 || buf[3] !== 0)) {
      return { encoding: "utf16le", bomLength: 2 };
    }
    if (buf[0] === 254 && buf[1] === 255) {
      return { encoding: "utf16be", bomLength: 2 };
    }
  }
  return null;
}
__name(detectBOM, "detectBOM");
function decodeUTF16BE(buf) {
  if (buf.length === 0) return "";
  const swapped = Buffer.from(buf);
  swapped.swap16();
  return swapped.toString("utf16le");
}
__name(decodeUTF16BE, "decodeUTF16BE");
function decodeUTF32(buf, littleEndian) {
  if (buf.length < 4) return "";
  const usable = buf.length - buf.length % 4;
  let out = "";
  for (let i = 0; i < usable; i += 4) {
    const cp = littleEndian ? (buf[i] | buf[i + 1] << 8 | buf[i + 2] << 16 | buf[i + 3] << 24) >>> 0 : (buf[i + 3] | buf[i + 2] << 8 | buf[i + 1] << 16 | buf[i] << 24) >>> 0;
    if (cp <= 1114111 && !(cp >= 55296 && cp <= 57343)) {
      out += String.fromCodePoint(cp);
    } else {
      out += "\uFFFD";
    }
  }
  return out;
}
__name(decodeUTF32, "decodeUTF32");
function isValidUtf8(buffer) {
  try {
    new TextDecoder("utf-8", { fatal: true }).decode(buffer);
    return true;
  } catch {
    return false;
  }
}
__name(isValidUtf8, "isValidUtf8");
function decodeBufferWithEncodingInfo(full) {
  if (full.length === 0) {
    return { content: "", encoding: "utf-8", bom: false };
  }
  const bomInfo = detectBOM(full);
  if (bomInfo) {
    return {
      content: decodeBOMBuffer(full, bomInfo),
      encoding: bomEncodingToName(bomInfo.encoding),
      // Mark bom: true for all Unicode BOM variants (UTF-8/16/32) so that
      // the BOM is re-written on save and the file's original format is preserved.
      bom: true
    };
  }
  if (isValidUtf8(full)) {
    return { content: full.toString("utf8"), encoding: "utf-8", bom: false };
  }
  const detected = detectEncodingFromBuffer(full);
  if (detected && !isUtf8CompatibleEncoding(detected)) {
    try {
      if (iconvEncodingExists(detected)) {
        return {
          content: iconvDecode(full, detected),
          encoding: detected,
          bom: false
        };
      }
    } catch (e) {
      debugLogger2.warn(
        `Failed to decode buffer as ${detected}: ${e instanceof Error ? e.message : String(e)}`
      );
    }
  }
  return { content: full.toString("utf8"), encoding: "utf-8", bom: false };
}
__name(decodeBufferWithEncodingInfo, "decodeBufferWithEncodingInfo");
function decodeBOMBuffer(buf, bomInfo) {
  const content = buf.subarray(bomInfo.bomLength);
  switch (bomInfo.encoding) {
    case "utf8":
      return content.toString("utf8");
    case "utf16le":
      return content.toString("utf16le");
    case "utf16be":
      return decodeUTF16BE(content);
    case "utf32le":
      return decodeUTF32(content, true);
    case "utf32be":
      return decodeUTF32(content, false);
    default:
      return content.toString("utf8");
  }
}
__name(decodeBOMBuffer, "decodeBOMBuffer");
function bomEncodingToName(bomEncoding) {
  switch (bomEncoding) {
    case "utf8":
      return "utf-8";
    case "utf16le":
      return "utf-16le";
    case "utf16be":
      return "utf-16be";
    case "utf32le":
      return "utf-32le";
    case "utf32be":
      return "utf-32be";
    default:
      return "utf-8";
  }
}
__name(bomEncodingToName, "bomEncodingToName");
async function readFileWithEncodingInfo(filePath) {
  const full = await fs2.promises.readFile(filePath);
  return decodeBufferWithEncodingInfo(full);
}
__name(readFileWithEncodingInfo, "readFileWithEncodingInfo");
async function readFileWithEncoding(filePath) {
  const result = await readFileWithEncodingInfo(filePath);
  return result.content;
}
__name(readFileWithEncoding, "readFileWithEncoding");
async function countFileLines(filePath) {
  const result = await readFileWithEncodingInfo(filePath);
  return result.content.split("\n").length;
}
__name(countFileLines, "countFileLines");
async function readFileWithLineAndLimit(params) {
  const { path: filePath, limit, line } = params;
  const { content, encoding, bom } = await readFileWithEncodingInfo(filePath);
  const lines = content.split("\n");
  const originalLineCount = lines.length;
  const startLine = line || 0;
  const endLine = Math.min(startLine + limit, originalLineCount);
  const actualStartLine = Math.min(startLine, originalLineCount);
  const selectedLines = lines.slice(actualStartLine, endLine);
  return {
    content: selectedLines.join("\n"),
    bom,
    encoding,
    originalLineCount
  };
}
__name(readFileWithLineAndLimit, "readFileWithLineAndLimit");
async function detectFileEncoding(filePath) {
  let fh = null;
  try {
    fh = await fs2.promises.open(filePath, "r");
    const stats = await fh.stat();
    if (stats.size === 0) return "utf-8";
    const sampleSize = Math.min(8192, stats.size);
    const buf = Buffer.alloc(sampleSize);
    const { bytesRead } = await fh.read(buf, 0, sampleSize, 0);
    if (bytesRead === 0) return "utf-8";
    const sample = buf.subarray(0, bytesRead);
    const bom = detectBOM(sample);
    if (bom) {
      switch (bom.encoding) {
        case "utf8":
          return "utf-8";
        case "utf16le":
          return "utf-16le";
        case "utf16be":
          return "utf-16be";
        case "utf32le":
          return "utf-32le";
        case "utf32be":
          return "utf-32be";
        default:
          return "utf-8";
      }
    }
    if (isValidUtf8(sample)) return "utf-8";
    const detected = detectEncodingFromBuffer(sample);
    if (detected && !isUtf8CompatibleEncoding(detected)) {
      return detected;
    }
    return "utf-8";
  } catch {
    return "utf-8";
  } finally {
    if (fh) {
      try {
        await fh.close();
      } catch {
      }
    }
  }
}
__name(detectFileEncoding, "detectFileEncoding");
function getSpecificMimeType(filePath) {
  const lookedUpMime = index_lite_default.getType(filePath);
  return typeof lookedUpMime === "string" ? lookedUpMime : void 0;
}
__name(getSpecificMimeType, "getSpecificMimeType");
function isWithinRoot(pathToCheck, rootDirectory) {
  const normalizedPathToCheck = path2.resolve(pathToCheck);
  const normalizedRootDirectory = path2.resolve(rootDirectory);
  const rootWithSeparator = normalizedRootDirectory === path2.sep || normalizedRootDirectory.endsWith(path2.sep) ? normalizedRootDirectory : normalizedRootDirectory + path2.sep;
  return normalizedPathToCheck === normalizedRootDirectory || normalizedPathToCheck.startsWith(rootWithSeparator);
}
__name(isWithinRoot, "isWithinRoot");
async function isBinaryFile(filePath) {
  let fh = null;
  try {
    fh = await fs2.promises.open(filePath, "r");
    const stats = await fh.stat();
    const fileSize = stats.size;
    if (fileSize === 0) return false;
    const sampleSize = Math.min(4096, fileSize);
    const buf = Buffer.alloc(sampleSize);
    const { bytesRead } = await fh.read(buf, 0, sampleSize, 0);
    if (bytesRead === 0) return false;
    const bom = detectBOM(buf.subarray(0, Math.min(4, bytesRead)));
    if (bom) return false;
    let nonPrintableCount = 0;
    for (let i = 0; i < bytesRead; i++) {
      if (buf[i] === 0) return true;
      if (buf[i] < 9 || buf[i] > 13 && buf[i] < 32) {
        nonPrintableCount++;
      }
    }
    return nonPrintableCount / bytesRead > 0.3;
  } catch (error) {
    debugLogger2.warn(
      `Failed to check if file is binary: ${filePath}`,
      error instanceof Error ? error.message : String(error)
    );
    return false;
  } finally {
    if (fh) {
      try {
        await fh.close();
      } catch (closeError) {
        debugLogger2.warn(
          `Failed to close file handle for: ${filePath}`,
          closeError instanceof Error ? closeError.message : String(closeError)
        );
      }
    }
  }
}
__name(isBinaryFile, "isBinaryFile");
var KNOWN_TEXT_APPLICATION_MIMES = /* @__PURE__ */ new Set([
  "application/javascript",
  "application/ecmascript",
  "application/node",
  "application/json",
  "application/xml",
  "application/toml"
]);
var KNOWN_TEXT_EXTENSIONS = /* @__PURE__ */ new Set([
  // C / C++
  ".c",
  ".cc",
  ".cpp",
  ".cxx",
  ".h",
  ".hh",
  ".hpp",
  ".hxx",
  ".inl",
  ".tpp",
  // Python
  ".py",
  ".pyi",
  ".pyw",
  ".pyx",
  // Rust
  ".rs",
  // Go
  ".go",
  // JVM
  ".gradle",
  ".groovy",
  ".java",
  ".kt",
  ".kts",
  ".sc",
  ".scala",
  // .NET
  ".cs",
  ".fs",
  ".fsi",
  ".fsx",
  ".vb",
  // Apple platforms
  ".m",
  ".mm",
  ".swift",
  // Functional
  ".cljc",
  ".cljs",
  ".clj",
  ".edn",
  ".erl",
  ".ex",
  ".exs",
  ".hrl",
  ".hs",
  ".lhs",
  ".ml",
  ".mli",
  // Web frontend (`.tsx` is handled by the early-return at the top
  // of detectFileType alongside `.ts` / `.mts` / `.cts` to keep all
  // TypeScript-family extensions in one place).
  ".astro",
  ".jsx",
  ".svelte",
  ".vue",
  // Scripting
  ".bash",
  ".dart",
  ".fish",
  ".lua",
  ".php",
  ".pl",
  ".pm",
  ".ps1",
  ".r",
  ".rb",
  ".sh",
  ".zsh",
  // Newer / niche source languages
  ".cr",
  ".nim",
  ".sol",
  ".zig",
  // Schema / IDL / queries
  ".gql",
  ".graphql",
  ".proto",
  ".sql",
  ".thrift",
  // Markup / typesetting
  ".adoc",
  ".bib",
  ".org",
  ".rst",
  ".tex",
  // Config / build
  ".cfg",
  ".cmake",
  ".conf",
  ".containerfile",
  ".dockerfile",
  ".hcl",
  ".ini",
  ".mk",
  ".nomad",
  ".properties",
  ".tf",
  ".tfvars",
  ".toml"
]);
var KNOWN_TEXT_BASENAMES = /* @__PURE__ */ new Set([
  "Dockerfile",
  "Containerfile",
  "Makefile",
  "GNUmakefile",
  "Jenkinsfile",
  "Vagrantfile",
  "Rakefile",
  "Gemfile",
  "Procfile",
  "BUILD",
  "WORKSPACE",
  "CMakeLists.txt",
  // also caught by .txt but pin explicitly
  "go.mod",
  "go.sum",
  "go.work",
  "Cargo.lock",
  "Pipfile",
  "Pipfile.lock",
  "poetry.lock",
  "package-lock.json",
  "yarn.lock",
  "pnpm-lock.yaml",
  "requirements.txt",
  ".gitignore",
  ".gitattributes",
  ".dockerignore",
  ".npmignore",
  ".editorconfig",
  ".env",
  ".bashrc",
  ".zshrc",
  ".profile",
  "LICENSE",
  "COPYING",
  "AUTHORS",
  "CHANGELOG",
  "README",
  "NOTICE"
]);
function isTextMime(lookedUpMimeType) {
  if (lookedUpMimeType.startsWith("text/")) {
    return true;
  }
  if (lookedUpMimeType.endsWith("+xml") || lookedUpMimeType.endsWith("+json")) {
    return true;
  }
  return KNOWN_TEXT_APPLICATION_MIMES.has(lookedUpMimeType);
}
__name(isTextMime, "isTextMime");
async function detectFileType(filePath) {
  const ext = path2.extname(filePath).toLowerCase();
  if ([".ts", ".mts", ".cts", ".tsx"].includes(ext)) {
    return "text";
  }
  if (ext === ".svg") {
    return "svg";
  }
  if (ext === ".ipynb") {
    return "notebook";
  }
  const lookedUpMimeType = index_lite_default.getType(filePath);
  if (lookedUpMimeType) {
    if (lookedUpMimeType.startsWith("image/")) {
      return "image";
    }
    if (lookedUpMimeType.startsWith("audio/")) {
      return "audio";
    }
    if (lookedUpMimeType.startsWith("video/")) {
      return "video";
    }
    if (lookedUpMimeType === "application/pdf") {
      return "pdf";
    }
    if (isTextMime(lookedUpMimeType)) {
      debugLogger2.debug(
        `detectFileType: ${filePath} \u2192 text (mime-trust: ${lookedUpMimeType})`
      );
      return "text";
    }
  }
  if (BINARY_EXTENSIONS.includes(ext)) {
    return "binary";
  }
  if (KNOWN_TEXT_EXTENSIONS.has(ext)) {
    debugLogger2.debug(
      `detectFileType: ${filePath} \u2192 text (extension-override, mime ${lookedUpMimeType ?? "null"})`
    );
    return "text";
  }
  if (KNOWN_TEXT_BASENAMES.has(path2.basename(filePath))) {
    debugLogger2.debug(
      `detectFileType: ${filePath} \u2192 text (basename-override, mime ${lookedUpMimeType ?? "null"})`
    );
    return "text";
  }
  if (await isBinaryFile(filePath)) {
    return "binary";
  }
  return "text";
}
__name(detectFileType, "detectFileType");
function mediaModalityKey(fileType) {
  if (fileType === "image" || fileType === "pdf" || fileType === "audio" || fileType === "video") {
    return fileType;
  }
  return void 0;
}
__name(mediaModalityKey, "mediaModalityKey");
function unsupportedModalityMessage(modality, displayName) {
  const hint = `This model does not support ${modality} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`;
  return `[Unsupported ${modality} file: "${displayName}". ${hint}]`;
}
__name(unsupportedModalityMessage, "unsupportedModalityMessage");
async function processSingleFileContent(filePath, config, optionsOrOffset, legacyLimit, legacyPages) {
  const options = typeof optionsOrOffset === "object" && optionsOrOffset !== null ? optionsOrOffset : {
    offset: optionsOrOffset,
    limit: legacyLimit,
    pages: legacyPages
  };
  const { offset, limit, pages, preserveUnsupportedImage = false } = options;
  const rootDirectory = config.getTargetDir();
  try {
    let stats;
    try {
      stats = await fs2.promises.stat(filePath);
    } catch (error) {
      if (isNodeError(error) && error.code === "ENOENT") {
        return {
          llmContent: "Could not read file because no file was found at the specified path.",
          returnDisplay: "File not found.",
          error: `File not found: ${filePath}`,
          errorType: "file_not_found" /* FILE_NOT_FOUND */
        };
      }
      throw error;
    }
    if (stats.isDirectory()) {
      return {
        llmContent: "Could not read file because the provided path is a directory, not a file.",
        returnDisplay: "Path is a directory.",
        error: `Path is a directory, not a file: ${filePath}`,
        errorType: "target_is_directory" /* TARGET_IS_DIRECTORY */
      };
    }
    if (!stats.isFile()) {
      return {
        llmContent: `Cannot read file: ${path2.basename(filePath)} is not a regular file (e.g. device, socket, or pipe).`,
        returnDisplay: "Not a regular file.",
        error: `Not a regular file: ${filePath}`,
        errorType: "read_content_failure" /* READ_CONTENT_FAILURE */
      };
    }
    const fileType = await detectFileType(filePath);
    const relativePathForDisplay = path2.relative(rootDirectory, filePath).replace(/\\/g, "/");
    const displayName = path2.basename(filePath);
    const modalities = config.getContentGeneratorConfig?.()?.modalities ?? {};
    const fileSizeInMB = stats.size / (1024 * 1024);
    const willExtractPdfText = fileType === "pdf" && (pages !== void 0 || !modalities.pdf);
    if (willExtractPdfText && fileSizeInMB > PDF_EXTRACTION_MAX_MB) {
      return {
        llmContent: `PDF file is too large for text extraction: ${fileSizeInMB.toFixed(2)}MB exceeds the ${PDF_EXTRACTION_MAX_MB}MB limit. Use the 'pages' parameter to read a narrower range, or split the document.`,
        returnDisplay: `PDF file too large (${fileSizeInMB.toFixed(2)}MB > ${PDF_EXTRACTION_MAX_MB}MB).`,
        error: `PDF exceeds extraction size limit: ${filePath} (${fileSizeInMB.toFixed(2)}MB)`,
        errorType: "file_too_large" /* FILE_TOO_LARGE */
      };
    }
    if (fileSizeInMB > 9.9 && !willExtractPdfText) {
      return {
        llmContent: "File size exceeds the 10MB limit.",
        returnDisplay: "File size exceeds the 10MB limit.",
        error: `File size exceeds the 10MB limit: ${filePath} (${fileSizeInMB.toFixed(2)}MB)`,
        errorType: "file_too_large" /* FILE_TOO_LARGE */
      };
    }
    const modality = mediaModalityKey(fileType);
    if (modality && modality !== "pdf") {
      if (!modalities[modality]) {
        const bridgeWillHandleImage = modality === "image" && preserveUnsupportedImage;
        if (!bridgeWillHandleImage) {
          const message = unsupportedModalityMessage(modality, displayName);
          debugLogger2.warn(
            `Model '${config.getModel()}' does not support ${modality} input. Skipping file: ${relativePathForDisplay}`
          );
          return {
            llmContent: message,
            returnDisplay: `Skipped ${fileType} file: ${relativePathForDisplay} (model doesn't support ${modality} input)`
          };
        }
        debugLogger2.debug(
          `Preserving unsupported image for vision bridge: ${relativePathForDisplay}`
        );
      }
    }
    switch (fileType) {
      case "binary": {
        return {
          llmContent: `Cannot display content of binary file: ${relativePathForDisplay}`,
          returnDisplay: `Skipped binary file: ${relativePathForDisplay}`,
          stats
        };
      }
      case "svg": {
        const SVG_MAX_SIZE_BYTES = 1 * 1024 * 1024;
        if (stats.size > SVG_MAX_SIZE_BYTES) {
          return {
            llmContent: `Cannot display content of SVG file larger than 1MB: ${relativePathForDisplay}`,
            returnDisplay: `Skipped large SVG file (>1MB): ${relativePathForDisplay}`,
            stats
          };
        }
        const content = await readFileWithEncoding(filePath);
        return {
          llmContent: content,
          returnDisplay: `Read SVG as text: ${relativePathForDisplay}`,
          originalLineCount: content.split("\n").length,
          isTruncated: false,
          stats
        };
      }
      case "text": {
        const { content, _meta } = await config.getFileSystemService().readTextFile({
          path: filePath,
          limit: limit ?? config.getTruncateToolOutputLines(),
          line: offset
        });
        const originalLineCount = _meta?.originalLineCount ?? await countFileLines(filePath);
        const selectedLines = content.split("\n").map((line) => line.trimEnd());
        const startLine = offset || 0;
        const configCharLimit = config.getTruncateToolOutputThreshold();
        let llmContent = "";
        let contentLengthTruncated = false;
        let linesIncluded = 0;
        if (Number.isFinite(configCharLimit)) {
          const formattedLines = [];
          let currentLength = 0;
          for (const line of selectedLines) {
            const sep = linesIncluded > 0 ? 1 : 0;
            linesIncluded++;
            const projectedLength = currentLength + line.length + sep;
            if (projectedLength <= configCharLimit) {
              formattedLines.push(line);
              currentLength = projectedLength;
            } else {
              const remaining = Math.max(
                configCharLimit - currentLength - sep,
                10
              );
              formattedLines.push(
                line.substring(0, remaining) + "... [truncated]"
              );
              contentLengthTruncated = true;
              break;
            }
          }
          llmContent = formattedLines.join("\n");
        } else {
          llmContent = selectedLines.join("\n");
          linesIncluded = selectedLines.length;
        }
        const actualEndLine = startLine + linesIncluded;
        const contentRangeTruncated = startLine > 0 || actualEndLine < originalLineCount;
        const isTruncated = contentRangeTruncated || contentLengthTruncated;
        let returnDisplay = "";
        if (isTruncated) {
          returnDisplay = `Read lines ${startLine + 1}-${actualEndLine} of ${originalLineCount} from ${relativePathForDisplay}`;
          if (contentLengthTruncated) {
            returnDisplay += " (truncated)";
          }
        }
        return {
          llmContent,
          returnDisplay,
          isTruncated,
          originalLineCount,
          linesShown: [startLine + 1, actualEndLine],
          stats
        };
      }
      case "image":
      case "audio":
      case "video": {
        const contentBuffer = await fs2.promises.readFile(filePath);
        const base64Data = contentBuffer.toString("base64");
        const base64SizeInMB = base64Data.length / (1024 * 1024);
        if (base64SizeInMB > 9.9) {
          return {
            llmContent: `File exceeds the 10MB data URI limit after base64 encoding (${base64SizeInMB.toFixed(2)}MB encoded).`,
            returnDisplay: `File exceeds the 10MB data URI limit after base64 encoding.`,
            error: `File exceeds the 10MB data URI limit after base64 encoding: ${filePath} (${base64SizeInMB.toFixed(2)}MB encoded)`,
            errorType: "file_too_large" /* FILE_TOO_LARGE */
          };
        }
        return {
          llmContent: {
            inlineData: {
              data: base64Data,
              mimeType: index_lite_default.getType(filePath) || "application/octet-stream",
              displayName
            }
          },
          returnDisplay: `Read ${fileType} file: ${relativePathForDisplay}`
        };
      }
      case "pdf": {
        if (!pages && modalities.pdf) {
          const contentBuffer = await fs2.promises.readFile(filePath);
          const base64Data = contentBuffer.toString("base64");
          const base64SizeInMB = base64Data.length / (1024 * 1024);
          if (base64SizeInMB > 9.9) {
            return {
              llmContent: `File exceeds the 10MB data URI limit after base64 encoding (${base64SizeInMB.toFixed(2)}MB encoded).`,
              returnDisplay: `File exceeds the 10MB data URI limit after base64 encoding.`,
              error: `File exceeds the 10MB data URI limit after base64 encoding: ${filePath} (${base64SizeInMB.toFixed(2)}MB encoded)`,
              errorType: "file_too_large" /* FILE_TOO_LARGE */
            };
          }
          return {
            llmContent: {
              inlineData: {
                data: base64Data,
                mimeType: "application/pdf",
                displayName
              }
            },
            returnDisplay: `Read pdf file: ${relativePathForDisplay}`
          };
        }
        const pageRange = pages ? parsePDFPageRange(pages) : void 0;
        const pdfResult = await extractPDFText(
          filePath,
          pageRange ?? void 0
        );
        if (pdfResult.success) {
          const pagesLabel = pages ? ` (pages ${pages})` : "";
          return {
            llmContent: pdfResult.text,
            returnDisplay: `Read pdf as text${pagesLabel}: ${relativePathForDisplay}`
          };
        }
        return {
          llmContent: `[Cannot extract text from PDF: "${displayName}". ${pdfResult.error}]`,
          returnDisplay: `Failed to read pdf: ${relativePathForDisplay}`,
          error: pdfResult.error,
          errorType: "read_content_failure" /* READ_CONTENT_FAILURE */
        };
      }
      case "notebook": {
        try {
          const { content, isTruncated } = await readNotebookWithMetadata(filePath);
          return {
            llmContent: content,
            returnDisplay: `Read notebook: ${relativePathForDisplay}`,
            isTruncated,
            stats
          };
        } catch (e) {
          const msg = getErrorMessage(e);
          return {
            llmContent: `Error parsing notebook ${relativePathForDisplay}: ${msg}`,
            returnDisplay: `Error reading notebook: ${relativePathForDisplay}`,
            error: `Error parsing notebook ${filePath}: ${msg}`,
            errorType: "read_content_failure" /* READ_CONTENT_FAILURE */
          };
        }
      }
      default: {
        const exhaustiveCheck = fileType;
        return {
          llmContent: `Unhandled file type: ${exhaustiveCheck}`,
          returnDisplay: `Skipped unhandled file type: ${relativePathForDisplay}`,
          error: `Unhandled file type for ${filePath}`
        };
      }
    }
  } catch (error) {
    const errorMessage2 = getErrorMessage(error);
    const displayPath = path2.relative(rootDirectory, filePath).replace(/\\/g, "/");
    return {
      llmContent: `Error reading file ${displayPath}: ${errorMessage2}`,
      returnDisplay: `Error reading file ${displayPath}: ${errorMessage2}`,
      error: `Error reading file ${filePath}: ${errorMessage2}`,
      errorType: "read_content_failure" /* READ_CONTENT_FAILURE */
    };
  }
}
__name(processSingleFileContent, "processSingleFileContent");
async function fileExists(filePath) {
  try {
    await fsPromises.access(filePath, fs2.constants.F_OK);
    return true;
  } catch (_) {
    return false;
  }
}
__name(fileExists, "fileExists");

// packages/core/src/telemetry/metrics.ts
init_esbuild_shims();
init_esm();

// packages/core/src/telemetry/constants.ts
init_esbuild_shims();
var SERVICE_NAME = "qwen-code";
var EVENT_USER_PROMPT = "qwen-code.user_prompt";
var EVENT_USER_RETRY = "qwen-code.user_retry";
var EVENT_TOOL_CALL = "qwen-code.tool_call";
var EVENT_API_REQUEST = "qwen-code.api_request";
var EVENT_API_ERROR = "qwen-code.api_error";
var EVENT_API_CANCEL = "qwen-code.api_cancel";
var EVENT_API_RESPONSE = "qwen-code.api_response";
var EVENT_CLI_CONFIG = "qwen-code.config";
var EVENT_EXTENSION_DISABLE = "qwen-code.extension_disable";
var EVENT_EXTENSION_ENABLE = "qwen-code.extension_enable";
var EVENT_EXTENSION_INSTALL = "qwen-code.extension_install";
var EVENT_EXTENSION_UNINSTALL = "qwen-code.extension_uninstall";
var EVENT_EXTENSION_UPDATE = "qwen-code.extension_update";
var EVENT_FLASH_FALLBACK = "qwen-code.flash_fallback";
var EVENT_RIPGREP_FALLBACK = "qwen-code.ripgrep_fallback";
var EVENT_NEXT_SPEAKER_CHECK = "qwen-code.next_speaker_check";
var EVENT_SLASH_COMMAND = "qwen-code.slash_command";
var EVENT_IDE_CONNECTION = "qwen-code.ide_connection";
var EVENT_CHAT_COMPRESSION = "qwen-code.chat_compression";
var EVENT_CONTENT_RETRY = "qwen-code.chat.content_retry";
var EVENT_CONTENT_RETRY_FAILURE = "qwen-code.chat.content_retry_failure";
var EVENT_API_RETRY = "qwen-code.api_retry";
var EVENT_CONVERSATION_FINISHED = "qwen-code.conversation_finished";
var EVENT_FILE_OPERATION = "qwen-code.file_operation";
var EVENT_MODEL_SLASH_COMMAND = "qwen-code.slash_command.model";
var EVENT_SUBAGENT_EXECUTION = "qwen-code.subagent_execution";
var EVENT_SKILL_LAUNCH = "qwen-code.skill_launch";
var EVENT_AUTH = "qwen-code.auth";
var EVENT_USER_FEEDBACK = "qwen-code.user_feedback";
var EVENT_TOOL_OUTPUT_TRUNCATED = "qwen-code.tool_output_truncated";
var DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH = 1024 * 1024;
var SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT = 100 * 1024 * 1024;
function isValidSensitiveSpanAttributeMaxLength(value) {
  return Number.isSafeInteger(value) && value >= 1 && value <= SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT;
}
__name(isValidSensitiveSpanAttributeMaxLength, "isValidSensitiveSpanAttributeMaxLength");
var EVENT_PROMPT_SUGGESTION = "qwen-code.prompt_suggestion";
var EVENT_SPECULATION = "qwen-code.speculation";
var EVENT_WORKFLOW_KEYWORD = "qwen-code.workflow_keyword";
var EVENT_WORKFLOW_RUN = "qwen-code.workflow_run";
var EVENT_ARENA_SESSION_STARTED = "qwen-code.arena_session_started";
var EVENT_ARENA_AGENT_COMPLETED = "qwen-code.arena_agent_completed";
var EVENT_ARENA_SESSION_ENDED = "qwen-code.arena_session_ended";
var EVENT_MEMORY_EXTRACT = "qwen-code.memory.extract";
var EVENT_MEMORY_DREAM = "qwen-code.memory.dream";
var EVENT_MEMORY_RECALL = "qwen-code.memory.recall";
var SPAN_INTERACTION = "qwen-code.interaction";
var SPAN_LLM_REQUEST = "qwen-code.llm_request";
var SPAN_TOOL = "qwen-code.tool";
var SPAN_TOOL_EXECUTION = "qwen-code.tool.execution";
var SPAN_TOOL_BLOCKED_ON_USER = "qwen-code.tool.blocked_on_user";
var SPAN_HOOK = "qwen-code.hook";
var SPAN_SUBAGENT = "qwen-code.subagent";

// packages/core/src/telemetry/metrics.ts
var TOOL_CALL_COUNT = `${SERVICE_NAME}.tool.call.count`;
var TOOL_CALL_LATENCY = `${SERVICE_NAME}.tool.call.latency`;
var API_REQUEST_COUNT = `${SERVICE_NAME}.api.request.count`;
var API_REQUEST_LATENCY = `${SERVICE_NAME}.api.request.latency`;
var TOKEN_USAGE = `${SERVICE_NAME}.token.usage`;
var SESSION_COUNT = `${SERVICE_NAME}.session.count`;
var FILE_OPERATION_COUNT = `${SERVICE_NAME}.file.operation.count`;
var INVALID_CHUNK_COUNT = `${SERVICE_NAME}.chat.invalid_chunk.count`;
var CONTENT_RETRY_COUNT = `${SERVICE_NAME}.chat.content_retry.count`;
var CONTENT_RETRY_FAILURE_COUNT = `${SERVICE_NAME}.chat.content_retry_failure.count`;
var API_RETRY_COUNT = `${SERVICE_NAME}.api.retry.count`;
var MODEL_SLASH_COMMAND_CALL_COUNT = `${SERVICE_NAME}.slash_command.model.call_count`;
var SUBAGENT_EXECUTION_COUNT = `${SERVICE_NAME}.subagent.execution.count`;
var ARENA_SESSION_COUNT = `${SERVICE_NAME}.arena.session.count`;
var ARENA_SESSION_DURATION = `${SERVICE_NAME}.arena.session.duration`;
var ARENA_AGENT_COUNT = `${SERVICE_NAME}.arena.agent.count`;
var ARENA_AGENT_DURATION = `${SERVICE_NAME}.arena.agent.duration`;
var ARENA_AGENT_TOKENS = `${SERVICE_NAME}.arena.agent.tokens`;
var ARENA_RESULT_SELECTED = `${SERVICE_NAME}.arena.result.selected`;
var STARTUP_TIME = `${SERVICE_NAME}.startup.duration`;
var MEMORY_USAGE = `${SERVICE_NAME}.memory.usage`;
var CPU_USAGE = `${SERVICE_NAME}.cpu.usage`;
var TOOL_QUEUE_DEPTH = `${SERVICE_NAME}.tool.queue.depth`;
var TOOL_EXECUTION_BREAKDOWN = `${SERVICE_NAME}.tool.execution.breakdown`;
var TOKEN_EFFICIENCY = `${SERVICE_NAME}.token.efficiency`;
var API_REQUEST_BREAKDOWN = `${SERVICE_NAME}.api.request.breakdown`;
var PERFORMANCE_SCORE = `${SERVICE_NAME}.performance.score`;
var REGRESSION_DETECTION = `${SERVICE_NAME}.performance.regression`;
var REGRESSION_PERCENTAGE_CHANGE = `${SERVICE_NAME}.performance.regression.percentage_change`;
var BASELINE_COMPARISON = `${SERVICE_NAME}.performance.baseline.comparison`;
var MEMORY_EXTRACT_COUNT = `${SERVICE_NAME}.memory.extract.count`;
var MEMORY_EXTRACT_DURATION = `${SERVICE_NAME}.memory.extract.duration`;
var MEMORY_DREAM_COUNT = `${SERVICE_NAME}.memory.dream.count`;
var MEMORY_DREAM_DURATION = `${SERVICE_NAME}.memory.dream.duration`;
var MEMORY_RECALL_COUNT = `${SERVICE_NAME}.memory.recall.count`;
var MEMORY_RECALL_DURATION = `${SERVICE_NAME}.memory.recall.duration`;
var baseMetricDefinition = {
  // session.id on metrics is opt-in: each session is a new value, so
  // attaching it by default would create unbounded time-series fan-out on
  // every metric backend. Operators who need session-level metric slicing
  // can enable QWEN_TELEMETRY_METRICS_INCLUDE_SESSION_ID or
  // telemetry.metrics.includeSessionId. Spans and logs always carry
  // session.id for trace/log correlation.
  getCommonAttributes: /* @__PURE__ */ __name((config) => {
    const out = {};
    if (config.getTelemetryMetricsIncludeSessionId()) {
      out["session.id"] = config.getSessionId();
    }
    return out;
  }, "getCommonAttributes")
};
var COUNTER_DEFINITIONS = {
  [TOOL_CALL_COUNT]: {
    description: "Counts tool calls, tagged by function name and success.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => toolCallCounter = c, "assign"),
    attributes: {}
  },
  [API_REQUEST_COUNT]: {
    description: "Counts API requests, tagged by model and status.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => apiRequestCounter = c, "assign"),
    attributes: {}
  },
  [TOKEN_USAGE]: {
    description: "Counts the total number of tokens used.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => tokenUsageCounter = c, "assign"),
    attributes: {}
  },
  [SESSION_COUNT]: {
    description: "Count of CLI sessions started.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => sessionCounter = c, "assign"),
    attributes: {}
  },
  [FILE_OPERATION_COUNT]: {
    description: "Counts file operations (create, read, update).",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => fileOperationCounter = c, "assign"),
    attributes: {}
  },
  [INVALID_CHUNK_COUNT]: {
    description: "Counts invalid chunks received from a stream.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => invalidChunkCounter = c, "assign"),
    attributes: {}
  },
  [CONTENT_RETRY_COUNT]: {
    description: "Counts retries due to content errors (e.g., empty stream).",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => contentRetryCounter = c, "assign"),
    attributes: {}
  },
  [CONTENT_RETRY_FAILURE_COUNT]: {
    description: "Counts occurrences of all content retries failing.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => contentRetryFailureCounter = c, "assign"),
    attributes: {}
  },
  [API_RETRY_COUNT]: {
    description: "Counts HTTP-status retries (429/5xx) at LLM call sites, emitted by retryWithBackoff onRetry callback.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => apiRetryCounter = c, "assign"),
    attributes: {}
  },
  [MODEL_SLASH_COMMAND_CALL_COUNT]: {
    description: "Counts model slash command calls.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => modelSlashCommandCallCounter = c, "assign"),
    attributes: {}
  },
  [EVENT_CHAT_COMPRESSION]: {
    description: "Counts chat compression events.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => chatCompressionCounter = c, "assign"),
    attributes: {}
  }
};
var HISTOGRAM_DEFINITIONS = {
  [TOOL_CALL_LATENCY]: {
    description: "Latency of tool calls in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((h) => toolCallLatencyHistogram = h, "assign"),
    attributes: {}
  },
  [API_REQUEST_LATENCY]: {
    description: "Latency of API requests in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((h) => apiRequestLatencyHistogram = h, "assign"),
    attributes: {}
  }
};
var PERFORMANCE_COUNTER_DEFINITIONS = {
  [REGRESSION_DETECTION]: {
    description: "Performance regression detection events.",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((c) => regressionDetectionCounter = c, "assign"),
    attributes: {}
  }
};
var PERFORMANCE_HISTOGRAM_DEFINITIONS = {
  [STARTUP_TIME]: {
    description: "CLI startup time in milliseconds, broken down by initialization phase.",
    unit: "ms",
    valueType: ValueType.DOUBLE,
    assign: /* @__PURE__ */ __name((h) => startupTimeHistogram = h, "assign"),
    attributes: {}
  },
  [MEMORY_USAGE]: {
    description: "Memory usage in bytes.",
    unit: "bytes",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((h) => memoryUsageGauge = h, "assign"),
    attributes: {}
  },
  [CPU_USAGE]: {
    description: "CPU usage percentage.",
    unit: "percent",
    valueType: ValueType.DOUBLE,
    assign: /* @__PURE__ */ __name((h) => cpuUsageGauge = h, "assign"),
    attributes: {}
  },
  [TOOL_QUEUE_DEPTH]: {
    description: "Number of tools in execution queue.",
    unit: "count",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((h) => toolQueueDepthGauge = h, "assign"),
    attributes: {}
  },
  [TOOL_EXECUTION_BREAKDOWN]: {
    description: "Tool execution time breakdown by phase in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((h) => toolExecutionBreakdownHistogram = h, "assign"),
    attributes: {}
  },
  [TOKEN_EFFICIENCY]: {
    description: "Token efficiency metrics (tokens per operation, cache hit rate, etc.).",
    unit: "ratio",
    valueType: ValueType.DOUBLE,
    assign: /* @__PURE__ */ __name((h) => tokenEfficiencyHistogram = h, "assign"),
    attributes: {}
  },
  [API_REQUEST_BREAKDOWN]: {
    description: "API request time breakdown by phase in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT,
    assign: /* @__PURE__ */ __name((h) => apiRequestBreakdownHistogram = h, "assign"),
    attributes: {}
  },
  [PERFORMANCE_SCORE]: {
    description: "Composite performance score (0-100).",
    unit: "score",
    valueType: ValueType.DOUBLE,
    assign: /* @__PURE__ */ __name((h) => performanceScoreGauge = h, "assign"),
    attributes: {}
  },
  [REGRESSION_PERCENTAGE_CHANGE]: {
    description: "Percentage change compared to baseline for detected regressions.",
    unit: "percent",
    valueType: ValueType.DOUBLE,
    assign: /* @__PURE__ */ __name((h) => regressionPercentageChangeHistogram = h, "assign"),
    attributes: {}
  },
  [BASELINE_COMPARISON]: {
    description: "Performance comparison to established baseline (percentage change).",
    unit: "percent",
    valueType: ValueType.DOUBLE,
    assign: /* @__PURE__ */ __name((h) => baselineComparisonHistogram = h, "assign"),
    attributes: {}
  }
};
var FileOperation = /* @__PURE__ */ ((FileOperation2) => {
  FileOperation2["CREATE"] = "create";
  FileOperation2["READ"] = "read";
  FileOperation2["UPDATE"] = "update";
  return FileOperation2;
})(FileOperation || {});
var PerformanceMetricType = /* @__PURE__ */ ((PerformanceMetricType2) => {
  PerformanceMetricType2["STARTUP"] = "startup";
  PerformanceMetricType2["MEMORY"] = "memory";
  PerformanceMetricType2["CPU"] = "cpu";
  PerformanceMetricType2["TOOL_EXECUTION"] = "tool_execution";
  PerformanceMetricType2["API_REQUEST"] = "api_request";
  PerformanceMetricType2["TOKEN_EFFICIENCY"] = "token_efficiency";
  return PerformanceMetricType2;
})(PerformanceMetricType || {});
var MemoryMetricType = /* @__PURE__ */ ((MemoryMetricType2) => {
  MemoryMetricType2["HEAP_USED"] = "heap_used";
  MemoryMetricType2["HEAP_TOTAL"] = "heap_total";
  MemoryMetricType2["EXTERNAL"] = "external";
  MemoryMetricType2["RSS"] = "rss";
  return MemoryMetricType2;
})(MemoryMetricType || {});
var ToolExecutionPhase = /* @__PURE__ */ ((ToolExecutionPhase2) => {
  ToolExecutionPhase2["VALIDATION"] = "validation";
  ToolExecutionPhase2["PREPARATION"] = "preparation";
  ToolExecutionPhase2["EXECUTION"] = "execution";
  ToolExecutionPhase2["RESULT_PROCESSING"] = "result_processing";
  return ToolExecutionPhase2;
})(ToolExecutionPhase || {});
var ApiRequestPhase = /* @__PURE__ */ ((ApiRequestPhase2) => {
  ApiRequestPhase2["REQUEST_PREPARATION"] = "request_preparation";
  ApiRequestPhase2["NETWORK_LATENCY"] = "network_latency";
  ApiRequestPhase2["RESPONSE_PROCESSING"] = "response_processing";
  ApiRequestPhase2["TOKEN_PROCESSING"] = "token_processing";
  return ApiRequestPhase2;
})(ApiRequestPhase || {});
var cliMeter;
var toolCallCounter;
var toolCallLatencyHistogram;
var apiRequestCounter;
var apiRequestLatencyHistogram;
var tokenUsageCounter;
var sessionCounter;
var fileOperationCounter;
var chatCompressionCounter;
var invalidChunkCounter;
var contentRetryCounter;
var contentRetryFailureCounter;
var apiRetryCounter;
var subagentExecutionCounter;
var modelSlashCommandCallCounter;
var startupTimeHistogram;
var memoryUsageGauge;
var cpuUsageGauge;
var toolQueueDepthGauge;
var toolExecutionBreakdownHistogram;
var tokenEfficiencyHistogram;
var apiRequestBreakdownHistogram;
var performanceScoreGauge;
var regressionDetectionCounter;
var regressionPercentageChangeHistogram;
var baselineComparisonHistogram;
var arenaSessionCounter;
var arenaSessionDurationHistogram;
var arenaAgentCounter;
var arenaAgentDurationHistogram;
var arenaAgentTokensCounter;
var arenaResultSelectedCounter;
var memoryExtractCounter;
var memoryExtractDurationHistogram;
var memoryDreamCounter;
var memoryDreamDurationHistogram;
var memoryRecallCounter;
var memoryRecallDurationHistogram;
var isMetricsInitialized = false;
var isPerformanceMonitoringEnabled = false;
function getMeter() {
  if (!cliMeter) {
    cliMeter = metrics.getMeter(SERVICE_NAME);
  }
  return cliMeter;
}
__name(getMeter, "getMeter");
function initializeMetrics(config) {
  if (isMetricsInitialized) return;
  const meter = getMeter();
  if (!meter) return;
  Object.entries(COUNTER_DEFINITIONS).forEach(
    ([name, { description, valueType, assign }]) => {
      assign(meter.createCounter(name, { description, valueType }));
    }
  );
  subagentExecutionCounter = meter.createCounter(SUBAGENT_EXECUTION_COUNT, {
    description: "Counts subagent execution events, tagged by status and subagent name.",
    valueType: ValueType.INT
  });
  arenaSessionCounter = meter.createCounter(ARENA_SESSION_COUNT, {
    description: "Counts arena sessions by status and display backend.",
    valueType: ValueType.INT
  });
  arenaSessionDurationHistogram = meter.createHistogram(
    ARENA_SESSION_DURATION,
    {
      description: "Duration of arena sessions in milliseconds.",
      unit: "ms",
      valueType: ValueType.INT
    }
  );
  arenaAgentCounter = meter.createCounter(ARENA_AGENT_COUNT, {
    description: "Counts arena agent completions by status and model.",
    valueType: ValueType.INT
  });
  arenaAgentDurationHistogram = meter.createHistogram(ARENA_AGENT_DURATION, {
    description: "Duration of arena agent execution in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT
  });
  arenaAgentTokensCounter = meter.createCounter(ARENA_AGENT_TOKENS, {
    description: "Token usage by arena agents.",
    valueType: ValueType.INT
  });
  arenaResultSelectedCounter = meter.createCounter(ARENA_RESULT_SELECTED, {
    description: "Counts arena result selections by model.",
    valueType: ValueType.INT
  });
  Object.entries(HISTOGRAM_DEFINITIONS).forEach(
    ([name, { description, unit, valueType, assign }]) => {
      assign(meter.createHistogram(name, { description, unit, valueType }));
    }
  );
  sessionCounter?.add(1, baseMetricDefinition.getCommonAttributes(config));
  memoryExtractCounter = meter.createCounter(MEMORY_EXTRACT_COUNT, {
    description: "Counts auto-memory extraction runs, tagged by trigger and status.",
    valueType: ValueType.INT
  });
  memoryExtractDurationHistogram = meter.createHistogram(
    MEMORY_EXTRACT_DURATION,
    {
      description: "Duration of auto-memory extraction in milliseconds.",
      unit: "ms",
      valueType: ValueType.INT
    }
  );
  memoryDreamCounter = meter.createCounter(MEMORY_DREAM_COUNT, {
    description: "Counts auto-memory dream (consolidation) runs, tagged by trigger and status.",
    valueType: ValueType.INT
  });
  memoryDreamDurationHistogram = meter.createHistogram(MEMORY_DREAM_DURATION, {
    description: "Duration of auto-memory dream runs in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT
  });
  memoryRecallCounter = meter.createCounter(MEMORY_RECALL_COUNT, {
    description: "Counts auto-memory recall operations, tagged by strategy.",
    valueType: ValueType.INT
  });
  memoryRecallDurationHistogram = meter.createHistogram(
    MEMORY_RECALL_DURATION,
    {
      description: "Duration of auto-memory recall operations in milliseconds.",
      unit: "ms",
      valueType: ValueType.INT
    }
  );
  initializePerformanceMonitoring(config);
  isMetricsInitialized = true;
}
__name(initializeMetrics, "initializeMetrics");
function recordChatCompressionMetrics(config, attributes) {
  if (!chatCompressionCounter || !isMetricsInitialized) return;
  chatCompressionCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  });
}
__name(recordChatCompressionMetrics, "recordChatCompressionMetrics");
function recordToolCallMetrics(config, durationMs, attributes) {
  if (!toolCallCounter || !toolCallLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  toolCallCounter.add(1, metricAttributes);
  toolCallLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config),
    function_name: attributes.function_name
  });
}
__name(recordToolCallMetrics, "recordToolCallMetrics");
function recordTokenUsageMetrics(config, tokenCount, attributes) {
  if (!tokenUsageCounter || !isMetricsInitialized) return;
  tokenUsageCounter.add(tokenCount, {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  });
}
__name(recordTokenUsageMetrics, "recordTokenUsageMetrics");
function recordApiResponseMetrics(config, durationMs, attributes) {
  if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model,
    status_code: attributes.status_code ?? "ok"
  };
  apiRequestCounter.add(1, metricAttributes);
  apiRequestLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model
  });
}
__name(recordApiResponseMetrics, "recordApiResponseMetrics");
function recordApiErrorMetrics(config, durationMs, attributes) {
  if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model,
    status_code: attributes.status_code ?? "error",
    error_type: attributes.error_type ?? "unknown"
  };
  apiRequestCounter.add(1, metricAttributes);
  apiRequestLatencyHistogram.record(durationMs, {
    ...baseMetricDefinition.getCommonAttributes(config),
    model: attributes.model
  });
}
__name(recordApiErrorMetrics, "recordApiErrorMetrics");
function recordFileOperationMetric(config, attributes) {
  if (!fileOperationCounter || !isMetricsInitialized) return;
  fileOperationCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  });
}
__name(recordFileOperationMetric, "recordFileOperationMetric");
function recordInvalidChunk(config) {
  if (!invalidChunkCounter || !isMetricsInitialized) return;
  invalidChunkCounter.add(1, baseMetricDefinition.getCommonAttributes(config));
}
__name(recordInvalidChunk, "recordInvalidChunk");
function recordContentRetry(config) {
  if (!contentRetryCounter || !isMetricsInitialized) return;
  contentRetryCounter.add(1, baseMetricDefinition.getCommonAttributes(config));
}
__name(recordContentRetry, "recordContentRetry");
function recordContentRetryFailure(config) {
  if (!contentRetryFailureCounter || !isMetricsInitialized) return;
  contentRetryFailureCounter.add(
    1,
    baseMetricDefinition.getCommonAttributes(config)
  );
}
__name(recordContentRetryFailure, "recordContentRetryFailure");
function recordApiRetry(config, attributes) {
  if (!apiRetryCounter || !isMetricsInitialized) return;
  apiRetryCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  });
}
__name(recordApiRetry, "recordApiRetry");
function recordModelSlashCommand(config, event) {
  if (!modelSlashCommandCallCounter || !isMetricsInitialized) return;
  modelSlashCommandCallCounter.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    "slash_command.model.model_name": event.model_name
  });
}
__name(recordModelSlashCommand, "recordModelSlashCommand");
function initializePerformanceMonitoring(config) {
  const meter = getMeter();
  if (!meter) return;
  isPerformanceMonitoringEnabled = config.getTelemetryEnabled();
  if (!isPerformanceMonitoringEnabled) return;
  Object.entries(PERFORMANCE_COUNTER_DEFINITIONS).forEach(
    ([name, { description, valueType, assign }]) => {
      assign(meter.createCounter(name, { description, valueType }));
    }
  );
  Object.entries(PERFORMANCE_HISTOGRAM_DEFINITIONS).forEach(
    ([name, { description, unit, valueType, assign }]) => {
      assign(meter.createHistogram(name, { description, unit, valueType }));
    }
  );
}
__name(initializePerformanceMonitoring, "initializePerformanceMonitoring");
function recordStartupPerformance(config, durationMs, attributes) {
  if (!startupTimeHistogram || !isPerformanceMonitoringEnabled) return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    phase: attributes.phase,
    ...attributes.details
  };
  startupTimeHistogram.record(durationMs, metricAttributes);
}
__name(recordStartupPerformance, "recordStartupPerformance");
function recordMemoryUsage(config, bytes, attributes) {
  if (!memoryUsageGauge || !isPerformanceMonitoringEnabled) return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  memoryUsageGauge.record(bytes, metricAttributes);
}
__name(recordMemoryUsage, "recordMemoryUsage");
function recordCpuUsage(config, percentage, attributes) {
  if (!cpuUsageGauge || !isPerformanceMonitoringEnabled) return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  cpuUsageGauge.record(percentage, metricAttributes);
}
__name(recordCpuUsage, "recordCpuUsage");
function recordToolQueueDepth(config, queueDepth) {
  if (!toolQueueDepthGauge || !isPerformanceMonitoringEnabled) return;
  const attributes = {
    ...baseMetricDefinition.getCommonAttributes(config)
  };
  toolQueueDepthGauge.record(queueDepth, attributes);
}
__name(recordToolQueueDepth, "recordToolQueueDepth");
function recordToolExecutionBreakdown(config, durationMs, attributes) {
  if (!toolExecutionBreakdownHistogram || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  toolExecutionBreakdownHistogram.record(durationMs, metricAttributes);
}
__name(recordToolExecutionBreakdown, "recordToolExecutionBreakdown");
function recordTokenEfficiency(config, value, attributes) {
  if (!tokenEfficiencyHistogram || !isPerformanceMonitoringEnabled) return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  tokenEfficiencyHistogram.record(value, metricAttributes);
}
__name(recordTokenEfficiency, "recordTokenEfficiency");
function recordApiRequestBreakdown(config, durationMs, attributes) {
  if (!apiRequestBreakdownHistogram || !isPerformanceMonitoringEnabled) return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  apiRequestBreakdownHistogram.record(durationMs, metricAttributes);
}
__name(recordApiRequestBreakdown, "recordApiRequestBreakdown");
function recordPerformanceScore(config, score, attributes) {
  if (!performanceScoreGauge || !isPerformanceMonitoringEnabled) return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  performanceScoreGauge.record(score, metricAttributes);
}
__name(recordPerformanceScore, "recordPerformanceScore");
function recordPerformanceRegression(config, attributes) {
  if (!regressionDetectionCounter || !isPerformanceMonitoringEnabled) return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  regressionDetectionCounter.add(1, metricAttributes);
  if (attributes.baseline_value !== 0 && regressionPercentageChangeHistogram) {
    const percentageChange = (attributes.current_value - attributes.baseline_value) / attributes.baseline_value * 100;
    regressionPercentageChangeHistogram.record(
      percentageChange,
      metricAttributes
    );
  }
}
__name(recordPerformanceRegression, "recordPerformanceRegression");
function recordBaselineComparison(config, attributes) {
  if (!baselineComparisonHistogram || !isPerformanceMonitoringEnabled) return;
  if (attributes.baseline_value === 0) {
    diag.warn("Baseline value is zero, skipping comparison.");
    return;
  }
  const percentageChange = (attributes.current_value - attributes.baseline_value) / attributes.baseline_value * 100;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    ...attributes
  };
  baselineComparisonHistogram.record(percentageChange, metricAttributes);
}
__name(recordBaselineComparison, "recordBaselineComparison");
function isPerformanceMonitoringActive() {
  return isPerformanceMonitoringEnabled && isMetricsInitialized;
}
__name(isPerformanceMonitoringActive, "isPerformanceMonitoringActive");
function recordSubagentExecutionMetrics(config, subagentName, status, terminateReason) {
  if (!subagentExecutionCounter || !isMetricsInitialized) return;
  const attributes = {
    ...baseMetricDefinition.getCommonAttributes(config),
    subagent_name: subagentName,
    status
  };
  if (terminateReason) {
    attributes["terminate_reason"] = terminateReason;
  }
  subagentExecutionCounter.add(1, attributes);
}
__name(recordSubagentExecutionMetrics, "recordSubagentExecutionMetrics");
function recordArenaSessionStartedMetrics(config) {
  if (!isMetricsInitialized) return;
  arenaSessionCounter?.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config),
    status: "started"
  });
}
__name(recordArenaSessionStartedMetrics, "recordArenaSessionStartedMetrics");
function recordArenaAgentCompletedMetrics(config, modelId, status, durationMs, inputTokens, outputTokens) {
  if (!isMetricsInitialized) return;
  const common = baseMetricDefinition.getCommonAttributes(config);
  arenaAgentCounter?.add(1, {
    ...common,
    status,
    model_id: modelId
  });
  arenaAgentDurationHistogram?.record(durationMs, {
    ...common,
    model_id: modelId
  });
  if (inputTokens > 0) {
    arenaAgentTokensCounter?.add(inputTokens, {
      ...common,
      model_id: modelId,
      type: "input"
    });
  }
  if (outputTokens > 0) {
    arenaAgentTokensCounter?.add(outputTokens, {
      ...common,
      model_id: modelId,
      type: "output"
    });
  }
}
__name(recordArenaAgentCompletedMetrics, "recordArenaAgentCompletedMetrics");
function recordArenaSessionEndedMetrics(config, status, displayBackend, durationMs, winnerModelId) {
  if (!isMetricsInitialized) return;
  const common = baseMetricDefinition.getCommonAttributes(config);
  arenaSessionCounter?.add(1, {
    ...common,
    status,
    ...displayBackend ? { display_backend: displayBackend } : {}
  });
  if (durationMs !== void 0 && arenaSessionDurationHistogram) {
    arenaSessionDurationHistogram.record(durationMs, {
      ...common,
      status
    });
  }
  if (winnerModelId) {
    arenaResultSelectedCounter?.add(1, {
      ...common,
      model_id: winnerModelId
    });
  }
}
__name(recordArenaSessionEndedMetrics, "recordArenaSessionEndedMetrics");
function recordMemoryExtractMetrics(config, durationMs, attrs) {
  if (!isMetricsInitialized) return;
  const common = baseMetricDefinition.getCommonAttributes(config);
  memoryExtractCounter?.add(1, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
  memoryExtractDurationHistogram?.record(durationMs, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
}
__name(recordMemoryExtractMetrics, "recordMemoryExtractMetrics");
function recordMemoryDreamMetrics(config, durationMs, attrs) {
  if (!isMetricsInitialized) return;
  const common = baseMetricDefinition.getCommonAttributes(config);
  memoryDreamCounter?.add(1, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
  memoryDreamDurationHistogram?.record(durationMs, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
}
__name(recordMemoryDreamMetrics, "recordMemoryDreamMetrics");
function recordMemoryRecallMetrics(config, durationMs, attrs) {
  if (!isMetricsInitialized) return;
  const common = baseMetricDefinition.getCommonAttributes(config);
  memoryRecallCounter?.add(1, { ...common, strategy: attrs.strategy });
  memoryRecallDurationHistogram?.record(durationMs, {
    ...common,
    strategy: attrs.strategy
  });
}
__name(recordMemoryRecallMetrics, "recordMemoryRecallMetrics");

// packages/core/src/telemetry/telemetry-utils.ts
init_esbuild_shims();

// packages/core/src/utils/language-detection.ts
init_esbuild_shims();
import * as path3 from "node:path";
var extensionToLanguageMap = {
  ".ts": "TypeScript",
  ".js": "JavaScript",
  ".mjs": "JavaScript",
  ".cjs": "JavaScript",
  ".jsx": "JavaScript",
  ".tsx": "TypeScript",
  ".py": "Python",
  ".java": "Java",
  ".go": "Go",
  ".rb": "Ruby",
  ".php": "PHP",
  ".phtml": "PHP",
  ".cs": "C#",
  ".cpp": "C++",
  ".cxx": "C++",
  ".cc": "C++",
  ".c": "C",
  ".h": "C/C++",
  ".hpp": "C++",
  ".swift": "Swift",
  ".kt": "Kotlin",
  ".rs": "Rust",
  ".m": "Objective-C",
  ".mm": "Objective-C",
  ".pl": "Perl",
  ".pm": "Perl",
  ".lua": "Lua",
  ".r": "R",
  ".scala": "Scala",
  ".sc": "Scala",
  ".sh": "Shell",
  ".ps1": "PowerShell",
  ".bat": "Batch",
  ".cmd": "Batch",
  ".sql": "SQL",
  ".html": "HTML",
  ".htm": "HTML",
  ".css": "CSS",
  ".less": "Less",
  ".sass": "Sass",
  ".scss": "Sass",
  ".json": "JSON",
  ".xml": "XML",
  ".yaml": "YAML",
  ".yml": "YAML",
  ".md": "Markdown",
  ".markdown": "Markdown",
  ".dockerfile": "Dockerfile",
  ".vim": "Vim script",
  ".vb": "Visual Basic",
  ".fs": "F#",
  ".clj": "Clojure",
  ".cljs": "Clojure",
  ".dart": "Dart",
  ".ex": "Elixir",
  ".erl": "Erlang",
  ".hs": "Haskell",
  ".lisp": "Lisp",
  ".rkt": "Racket",
  ".groovy": "Groovy",
  ".jl": "Julia",
  ".tex": "LaTeX",
  ".ino": "Arduino",
  ".asm": "Assembly",
  ".s": "Assembly",
  ".toml": "TOML",
  ".vue": "Vue",
  ".svelte": "Svelte",
  ".gohtml": "Go Template",
  ".hbs": "Handlebars",
  ".ejs": "EJS",
  ".erb": "ERB",
  ".jsp": "JSP",
  ".dockerignore": "Docker",
  ".gitignore": "Git",
  ".npmignore": "npm",
  ".editorconfig": "EditorConfig",
  ".prettierrc": "Prettier",
  ".eslintrc": "ESLint",
  ".babelrc": "Babel",
  ".tsconfig": "TypeScript",
  ".flow": "Flow",
  ".graphql": "GraphQL",
  ".proto": "Protocol Buffers"
};
function getLanguageFromFilePath(filePath) {
  const extension = path3.extname(filePath).toLowerCase();
  if (extension) {
    return extensionToLanguageMap[extension];
  }
  const filename = path3.basename(filePath).toLowerCase();
  return extensionToLanguageMap[`.${filename}`];
}
__name(getLanguageFromFilePath, "getLanguageFromFilePath");

// packages/core/src/telemetry/telemetry-utils.ts
function getProgrammingLanguage(args) {
  const filePath = args["file_path"] || args["path"];
  if (typeof filePath === "string") {
    return getLanguageFromFilePath(filePath);
  }
  return void 0;
}
__name(getProgrammingLanguage, "getProgrammingLanguage");

// packages/core/src/telemetry/loggers.ts
init_esbuild_shims();
var import_api_logs2 = __toESM(require_src2(), 1);
init_esm2();

// packages/core/src/utils/internalPromptIds.ts
init_esbuild_shims();
var INTERNAL_PROMPT_IDS = /* @__PURE__ */ new Set([
  "prompt_suggestion",
  "forked_query",
  "speculation"
]);
var SIDE_QUERY_PROMPT_PREFIX = "side-query:";
function isInternalPromptId(promptId) {
  if (!promptId) return false;
  return INTERNAL_PROMPT_IDS.has(promptId) || promptId.startsWith(SIDE_QUERY_PROMPT_PREFIX);
}
__name(isInternalPromptId, "isInternalPromptId");

// packages/core/src/utils/safeJsonStringify.ts
init_esbuild_shims();
function safeJsonStringify(obj, space) {
  const ancestors = [];
  return JSON.stringify(
    obj,
    function(_key, value) {
      if (typeof value !== "object" || value === null) {
        return value;
      }
      while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {
        ancestors.pop();
      }
      if (ancestors.includes(value)) {
        return "[Circular]";
      }
      ancestors.push(value);
      return value;
    },
    space
  );
}
__name(safeJsonStringify, "safeJsonStringify");

// packages/core/src/telemetry/qwen-logger/qwen-logger.ts
init_esbuild_shims();
var import_https_proxy_agent = __toESM(require_dist(), 1);
import { Buffer as Buffer2 } from "buffer";
import * as https2 from "https";
import * as os3 from "node:os";
import fs6 from "node:fs";
import path7 from "node:path";

// packages/core/src/telemetry/sanitize.ts
init_esbuild_shims();
function sanitizeHookName(hookName) {
  if (!hookName || !hookName.trim()) {
    return "unknown-command";
  }
  const parts = hookName.trim().split(/\s+/);
  if (parts.length === 0) {
    return "unknown-command";
  }
  const command = parts[0];
  if (!command) {
    return "unknown-command";
  }
  if (command.includes("/") || command.includes("\\")) {
    const pathParts = command.split(/[/\\]/);
    const basename3 = pathParts[pathParts.length - 1];
    return basename3 || "unknown-command";
  }
  return command;
}
__name(sanitizeHookName, "sanitizeHookName");

// node_modules/mnemonist/index.mjs
init_esbuild_shims();
var import_fibonacci_heap = __toESM(require_fibonacci_heap(), 1);
var import_heap = __toESM(require_heap(), 1);
var import_suffix_array = __toESM(require_suffix_array(), 1);
var import_vector = __toESM(require_vector(), 1);
var import_fixed_deque = __toESM(require_fixed_deque(), 1);
var MinFibonacciHeap = import_fibonacci_heap.default.MinFibonacciHeap;
var MaxFibonacciHeap = import_fibonacci_heap.default.MaxFibonacciHeap;
var MinHeap = import_heap.default.MinHeap;
var MaxHeap = import_heap.default.MaxHeap;
var GeneralizedSuffixArray = import_suffix_array.default.GeneralizedSuffixArray;
var Uint8Vector = import_vector.default.Uint8Vector;
var Uint8ClampedVector = import_vector.default.Uint8ClampedVector;
var Int8Vector = import_vector.default.Int8Vector;
var Uint16Vector = import_vector.default.Uint16Vector;
var Int16Vector = import_vector.default.Int16Vector;
var Uint32Vector = import_vector.default.Uint32Vector;
var Int32Vector = import_vector.default.Int32Vector;
var Float32Vector = import_vector.default.Float32Vector;
var Float64Vector = import_vector.default.Float64Vector;
var PointerVector = import_vector.default.PointerVector;

// packages/core/src/core/contentGenerator.ts
init_esbuild_shims();

// packages/core/src/core/loggingContentGenerator/index.ts
init_esbuild_shims();

// packages/core/src/core/loggingContentGenerator/loggingContentGenerator.ts
init_esbuild_shims();
init_esm();

// packages/core/src/telemetry/types.ts
init_esbuild_shims();

// packages/core/src/tools/mcp-tool.ts
init_esbuild_shims();

// packages/core/src/utils/truncation.ts
init_esbuild_shims();
import * as fs3 from "node:fs/promises";
import * as path4 from "node:path";
import * as crypto2 from "node:crypto";
var debugLogger3 = createDebugLogger("TRUNCATION");
var PREVIEW_SIZE_CHARS = 2e3;
var MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024;
var MAX_SESSION_BYTES = 500 * 1024 * 1024;
var TOOL_OUTPUT_TRUNCATED_PREFIX = "Tool output was too large and has been truncated";
async function truncateAndSaveToFile(content, fileName, projectTempDir, threshold, truncateLines, keep = "both") {
  if (content.length <= threshold && !Number.isFinite(truncateLines)) {
    return { content };
  }
  const lines = content.split("\n");
  if (content.length <= threshold && lines.length <= truncateLines) {
    return { content };
  }
  const effectiveLines = Math.min(truncateLines, lines.length);
  let headCount;
  let tailCount;
  if (keep === "head") {
    headCount = effectiveLines;
    tailCount = 0;
  } else if (keep === "tail") {
    headCount = 0;
    tailCount = effectiveLines;
  } else {
    headCount = Math.max(Math.floor(effectiveLines / 5), 1);
    tailCount = effectiveLines - headCount;
  }
  const separator = "\n\n---\n... [CONTENT TRUNCATED] ...\n---\n\n";
  const ellipsis = "...";
  const headBudget = keep === "head" ? threshold : keep === "tail" ? 0 : Math.floor(threshold / 5);
  const beginning = [];
  let headChars = 0;
  for (let i = 0; i < Math.min(headCount, lines.length); i++) {
    const remaining = headBudget - headChars;
    if (remaining <= 0) break;
    if (lines[i].length + 1 > remaining) {
      const sliceLen = Math.max(remaining - ellipsis.length, 0);
      beginning.push(lines[i].slice(0, sliceLen) + ellipsis);
      headChars = headBudget;
      break;
    }
    beginning.push(lines[i]);
    headChars += lines[i].length + 1;
  }
  const tailBudget = keep === "head" ? 0 : Math.max(threshold - headChars - separator.length, 0);
  const end = [];
  let tailChars = 0;
  const tailStart = Math.max(lines.length - tailCount, beginning.length);
  for (let i = lines.length - 1; i >= tailStart; i--) {
    const remaining = tailBudget - tailChars;
    if (remaining <= 0) break;
    if (lines[i].length + 1 > remaining) {
      const sliceLen = Math.max(remaining - ellipsis.length, 0);
      end.unshift(ellipsis + (sliceLen > 0 ? lines[i].slice(-sliceLen) : ""));
      tailChars = tailBudget;
      break;
    }
    end.unshift(lines[i]);
    tailChars += lines[i].length + 1;
  }
  const truncatedContent = keep === "head" ? beginning.join("\n") + separator : keep === "tail" ? separator + end.join("\n") : beginning.join("\n") + separator + end.join("\n");
  const safeFileName = `${path4.basename(fileName)}.output`;
  const outputFile = path4.join(projectTempDir, safeFileName);
  const wrappedMessage = `${TOOL_OUTPUT_TRUNCATED_PREFIX}.
The full output has been saved to: ${outputFile}
To read the complete output, use the ${ReadFileTool.Name} tool with the absolute file path above.
The truncated output below shows the beginning and end of the content. The marker '... [CONTENT TRUNCATED] ...' indicates where content was removed.

Truncated part of the output:
${truncatedContent}`;
  if (wrappedMessage.length >= content.length) {
    return { content };
  }
  try {
    await fs3.mkdir(projectTempDir, { recursive: true });
    await fs3.writeFile(outputFile, content, { mode: 384 });
    return {
      content: wrappedMessage,
      outputFile
    };
  } catch (error) {
    debugLogger3.warn(
      `Failed to save truncated output to ${outputFile}:`,
      error
    );
    return {
      content: truncatedContent + `
[Note: Could not save full output to file]`
    };
  }
}
__name(truncateAndSaveToFile, "truncateAndSaveToFile");
async function truncateToolOutput(config, toolName, content, limits, promptId) {
  const threshold = limits?.threshold ?? config.getTruncateToolOutputThreshold();
  const lines = limits?.lines ?? config.getTruncateToolOutputLines();
  const keep = limits?.keep ?? "both";
  if (threshold <= 0 || lines <= 0) {
    return { content };
  }
  if (content.length <= threshold && !Number.isFinite(lines)) {
    return { content };
  }
  const originalLength = content.length;
  const fileName = `${toolName}_${crypto2.randomBytes(6).toString("hex")}`;
  const result = await truncateAndSaveToFile(
    content,
    fileName,
    config.storage.getProjectTempDir(),
    threshold,
    lines,
    keep
  );
  if (result.outputFile) {
    try {
      logToolOutputTruncated(
        config,
        new ToolOutputTruncatedEvent(promptId ?? "", {
          toolName,
          originalContentLength: originalLength,
          truncatedContentLength: result.content.length,
          threshold,
          lines
        })
      );
    } catch {
    }
  }
  return result;
}
__name(truncateToolOutput, "truncateToolOutput");
async function truncateLlmContent(config, toolName, content, limits, promptId) {
  if (typeof content === "string") {
    if (content.trim() === "") {
      return { content: `(${toolName} completed with no output)` };
    }
    if (content.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX)) {
      return { content };
    }
    return truncateToolOutput(config, toolName, content, limits, promptId);
  }
  const parts = (Array.isArray(content) ? content : [content]).map(
    (p) => typeof p === "string" ? { text: p } : p
  );
  const textParts = parts.filter((p) => p.text !== void 0);
  const mediaParts = parts.filter((p) => p.text === void 0);
  const combined = textParts.map((p) => p.text).join("\n");
  if (combined.trim() === "" && mediaParts.length === 0) {
    return { content: `(${toolName} completed with no output)` };
  }
  if (textParts.some((p) => p.text?.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX))) {
    return { content };
  }
  const result = await truncateToolOutput(
    config,
    toolName,
    combined,
    limits,
    promptId
  );
  if (result.content === combined) {
    return { content };
  }
  return {
    content: [{ text: result.content }, ...mediaParts],
    outputFile: result.outputFile
  };
}
__name(truncateLlmContent, "truncateLlmContent");
function isAlreadyTruncated(content) {
  return content.includes("... [CONTENT TRUNCATED] ...") || content.startsWith("<persisted-output>");
}
__name(isAlreadyTruncated, "isAlreadyTruncated");
function generatePreview(content) {
  let text = content.length <= PREVIEW_SIZE_CHARS ? content : (() => {
    const slice = content.slice(0, PREVIEW_SIZE_CHARS);
    const lastNewline = slice.lastIndexOf("\n");
    return (lastNewline > 0 ? slice.slice(0, lastNewline) : slice) + "\n...";
  })();
  text = text.replace(/<\/?persisted-output>/g, (m) => `&lt;${m.slice(1, -1)}&gt;`).replace(/<\/?system-reminder>/g, (m) => `&lt;${m.slice(1, -1)}&gt;`);
  return text;
}
__name(generatePreview, "generatePreview");
async function persistAndTruncateToolResult(callId, toolName, content, config) {
  const byteSize = Buffer.byteLength(content, "utf-8");
  if (byteSize > MAX_FILE_SIZE_BYTES) {
    debugLogger3.warn(
      `Tool result for ${toolName} exceeds ${MAX_FILE_SIZE_BYTES} bytes (${byteSize}), skipping disk persistence`
    );
    return {
      content: buildStub(content, byteSize, "(file too large to persist)"),
      bytesWritten: 0
    };
  }
  const budgetUsed = config.getToolResultBytesWritten();
  if (budgetUsed + byteSize > MAX_SESSION_BYTES) {
    debugLogger3.warn(
      `Session tool result budget exhausted (${budgetUsed} + ${byteSize} > ${MAX_SESSION_BYTES}), skipping disk persistence`
    );
    return {
      content: buildStub(content, byteSize, "(session disk budget exhausted)"),
      bytesWritten: 0
    };
  }
  config.trackToolResultBytes(byteSize);
  const safeCallId = path4.basename(callId).replace(/\x00/g, "_");
  if (!safeCallId || safeCallId === "." || safeCallId === "..") {
    debugLogger3.warn(
      `Invalid callId for disk persistence: ${JSON.stringify(callId)}`
    );
    config.trackToolResultBytes(-byteSize);
    return {
      content: buildStub(content, byteSize, "(invalid callId)"),
      bytesWritten: 0
    };
  }
  const toolResultsDir = config.storage.getToolResultsDir();
  const outputFile = path4.join(toolResultsDir, `${safeCallId}.txt`);
  try {
    await fs3.mkdir(toolResultsDir, { recursive: true });
    await atomicWriteFile(outputFile, content, {
      mode: 384,
      forceMode: true,
      noFollow: true,
      flush: false
    });
    return {
      content: buildStub(content, byteSize, outputFile),
      outputFile,
      bytesWritten: byteSize
    };
  } catch (error) {
    config.trackToolResultBytes(-byteSize);
    debugLogger3.warn(`Failed to persist tool result to ${outputFile}:`, error);
    try {
      const fallback = await truncateAndSaveToFile(
        content,
        `${toolName}_${crypto2.randomBytes(6).toString("hex")}`,
        config.storage.getProjectTempDir(),
        config.getTruncateToolOutputThreshold(),
        config.getTruncateToolOutputLines()
      );
      return { content: fallback.content, bytesWritten: 0 };
    } catch (fallbackError) {
      debugLogger3.warn("Fallback truncation also failed:", fallbackError);
      return {
        content: buildStub(content, byteSize, "(disk persistence unavailable)"),
        bytesWritten: 0
      };
    }
  }
}
__name(persistAndTruncateToolResult, "persistAndTruncateToolResult");
function buildStub(content, byteSize, filePathOrNote) {
  const preview = generatePreview(content);
  const sizeKb = Math.round(byteSize / 1024);
  const isFilePath = path4.isAbsolute(filePathOrNote);
  if (isFilePath) {
    return `<persisted-output>
Output too large (${sizeKb} KB). Full output saved to: ${filePathOrNote}
Note: this file may be cleaned up after 24 hours.
To read the complete output, use the ${ReadFileTool.Name} tool with the absolute file path above.

Preview (up to ${PREVIEW_SIZE_CHARS} chars):
${preview}
</persisted-output>`;
  }
  return `Output too large (${sizeKb} KB). ${filePathOrNote}

Preview (up to ${PREVIEW_SIZE_CHARS} chars):
${preview}`;
}
__name(buildStub, "buildStub");

// packages/core/src/tools/mcp-status.ts
init_esbuild_shims();
var MCPServerStatus = /* @__PURE__ */ ((MCPServerStatus2) => {
  MCPServerStatus2["DISCONNECTED"] = "disconnected";
  MCPServerStatus2["CONNECTING"] = "connecting";
  MCPServerStatus2["CONNECTED"] = "connected";
  return MCPServerStatus2;
})(MCPServerStatus || {});
var serverStatuses = /* @__PURE__ */ new Map();
var statusChangeListeners = [];
function addMCPStatusChangeListener(listener) {
  statusChangeListeners.push(listener);
}
__name(addMCPStatusChangeListener, "addMCPStatusChangeListener");
function removeMCPStatusChangeListener(listener) {
  const index = statusChangeListeners.indexOf(listener);
  if (index !== -1) {
    statusChangeListeners.splice(index, 1);
  }
}
__name(removeMCPStatusChangeListener, "removeMCPStatusChangeListener");
function updateMCPServerStatus(serverName, status) {
  serverStatuses.set(serverName, status);
  for (const listener of [...statusChangeListeners]) {
    listener(serverName, status);
  }
}
__name(updateMCPServerStatus, "updateMCPServerStatus");
function removeMCPServerStatus(serverName) {
  if (!serverStatuses.has(serverName)) {
    return;
  }
  serverStatuses.delete(serverName);
  for (const listener of [...statusChangeListeners]) {
    listener(serverName, void 0);
  }
}
__name(removeMCPServerStatus, "removeMCPServerStatus");
function getMCPServerStatus(serverName) {
  return serverStatuses.get(serverName) || "disconnected" /* DISCONNECTED */;
}
__name(getMCPServerStatus, "getMCPServerStatus");
function getAllMCPServerStatuses() {
  return new Map(serverStatuses);
}
__name(getAllMCPServerStatuses, "getAllMCPServerStatuses");

// packages/core/src/tools/mcp-tool.ts
var debugLogger4 = createDebugLogger("MCP_TOOL");
var MCP_CONNECTION_ERROR_PATTERNS = [
  /ECONNREFUSED/i,
  /ENOTFOUND/i,
  /ECONNRESET/i,
  /ETIMEDOUT/i,
  /connection (closed|lost)/i,
  /not connected/i,
  /disconnected/i,
  /transport closed/i
];
var DiscoveredMCPToolInvocation = class _DiscoveredMCPToolInvocation extends BaseToolInvocation {
  constructor(mcpTool, serverName, serverToolName, displayName, trust, params = {}, cliConfig, mcpClient, mcpTimeout, mcpToolIdleTimeoutMs, annotations, retryCount = 0) {
    super(params);
    this.mcpTool = mcpTool;
    this.serverName = serverName;
    this.serverToolName = serverToolName;
    this.displayName = displayName;
    this.trust = trust;
    this.cliConfig = cliConfig;
    this.mcpClient = mcpClient;
    this.mcpTimeout = mcpTimeout;
    this.mcpToolIdleTimeoutMs = mcpToolIdleTimeoutMs;
    this.annotations = annotations;
    this.retryCount = retryCount;
  }
  static {
    __name(this, "DiscoveredMCPToolInvocation");
  }
  static MAX_RECONNECT_RETRIES = 3;
  /**
   * MCP tool default permission based on trust and annotations:
   * - trust: true in a trusted folder → 'allow' (server explicitly trusted by user config)
   * - readOnlyHint → 'allow'
   * - All other MCP tools → 'ask'
   */
  async getDefaultPermission() {
    if (this.trust === true && this.cliConfig?.isTrustedFolder()) {
      return "allow";
    }
    if (this.annotations?.readOnlyHint === true) {
      return "allow";
    }
    return "ask";
  }
  /**
   * Constructs confirmation dialog details for an MCP tool call.
   */
  async getConfirmationDetails(_abortSignal) {
    const permissionRule = `mcp__${this.serverName}__${this.serverToolName}`;
    const confirmationDetails = {
      type: "mcp",
      title: "Confirm MCP Tool Execution",
      serverName: this.serverName,
      toolName: this.serverToolName,
      toolDisplayName: this.displayName,
      permissionRules: [permissionRule],
      onConfirm: /* @__PURE__ */ __name(async (_outcome, _payload) => {
      }, "onConfirm")
    };
    return confirmationDetails;
  }
  // MCP spec: errors are returned inside the CallToolResult, not as exceptions.
  // ref: https://modelcontextprotocol.io/specification/2025-06-18/schema#calltoolresult
  isMCPToolError(rawResponseParts) {
    const functionResponse = rawResponseParts?.[0]?.functionResponse;
    const response = functionResponse?.response;
    if (response) {
      const error = response?.error;
      const isError = error?.isError;
      if (error && (isError === true || isError === "true")) {
        return true;
      }
    }
    return false;
  }
  async attemptReconnect() {
    if (!this.cliConfig) {
      return null;
    }
    try {
      debugLogger4.info(
        `Attempting to reconnect MCP server '${this.serverName}'...`
      );
      const toolRegistry = this.cliConfig.getToolRegistry();
      await toolRegistry.discoverToolsForServer(this.serverName);
      const newTool = await toolRegistry.ensureTool(
        `mcp__${this.serverName}__${this.serverToolName}`
      );
      if (newTool instanceof DiscoveredMCPTool) {
        debugLogger4.info(
          `Successfully reconnected to MCP server '${this.serverName}'`
        );
        return newTool;
      }
      return null;
    } catch (error) {
      debugLogger4.error(
        `Failed to reconnect MCP server '${this.serverName}': ${error}`
      );
      return null;
    }
  }
  async handleReconnectOnError(error, signal, updateOutput) {
    debugLogger4.error(`MCP server error '${this.serverName}': ${error}`);
    if (!this.shouldAttemptReconnect(error)) {
      throw error;
    }
    if (this.retryCount < _DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES) {
      debugLogger4.info(
        `Reconnection attempt ${this.retryCount + 1}/${_DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES} for MCP server '${this.serverName}'`
      );
      const newTool = await this.attemptReconnect();
      if (newTool) {
        const newInvocation = new _DiscoveredMCPToolInvocation(
          newTool["mcpTool"],
          this.serverName,
          this.serverToolName,
          this.displayName,
          this.trust,
          this.params,
          this.cliConfig,
          newTool["mcpClient"],
          this.mcpTimeout,
          this.mcpToolIdleTimeoutMs,
          this.annotations,
          this.retryCount + 1
        );
        return newInvocation.execute(signal, updateOutput);
      }
    } else if (this.retryCount >= _DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES) {
      debugLogger4.error(
        `Max reconnection attempts (${_DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES}) reached for MCP server '${this.serverName}'`
      );
    }
    throw error;
  }
  shouldAttemptReconnect(error) {
    if (isAbortError(error)) {
      return false;
    }
    if (getMCPServerStatus(this.serverName) === "disconnected" /* DISCONNECTED */) {
      return true;
    }
    const message = getErrorMessage(error);
    return MCP_CONNECTION_ERROR_PATTERNS.some(
      (pattern) => pattern.test(message)
    );
  }
  async execute(signal, updateOutput) {
    if (this.mcpClient) {
      return this.executeWithDirectClient(signal, updateOutput);
    }
    return this.executeWithCallableTool(signal);
  }
  /**
   * Execute using the raw MCP SDK Client, which supports progress
   * notifications via the onprogress callback. This enables real-time
   * streaming of progress updates to the user during long-running
   * MCP tool calls (e.g., browser automation).
   */
  async executeWithDirectClient(signal, updateOutput) {
    const idleTimeoutController = new AbortController();
    let idleTimeoutId;
    const combinedSignal = AbortSignal.any([
      signal,
      idleTimeoutController.signal
    ]);
    const resetIdleTimeout = /* @__PURE__ */ __name(() => {
      if (idleTimeoutId) {
        clearTimeout(idleTimeoutId);
      }
      if (this.mcpToolIdleTimeoutMs && this.mcpToolIdleTimeoutMs > 0) {
        const timer = setTimeout(() => {
          const error = new Error(
            `MCP tool '${this.serverToolName}' on server '${this.serverName}' did not respond within ${this.mcpToolIdleTimeoutMs}ms idle timeout`
          );
          error.name = "AbortError";
          idleTimeoutController.abort(error);
        }, this.mcpToolIdleTimeoutMs);
        timer.unref();
        idleTimeoutId = timer;
      }
    }, "resetIdleTimeout");
    try {
      resetIdleTimeout();
      const callToolResult = await this.mcpClient.callTool(
        {
          name: this.serverToolName,
          arguments: this.params
        },
        void 0,
        {
          onprogress: /* @__PURE__ */ __name((progress) => {
            resetIdleTimeout();
            if (updateOutput) {
              const progressData = {
                type: "mcp_tool_progress",
                progress: progress.progress,
                ...progress.total != null && { total: progress.total },
                ...progress.message != null && { message: progress.message }
              };
              updateOutput(progressData);
            }
          }, "onprogress"),
          timeout: this.mcpTimeout,
          signal: combinedSignal
        }
      );
      const rawResponseParts = wrapMcpCallToolResultAsParts(
        this.serverToolName,
        callToolResult
      );
      if (this.isMCPToolError(rawResponseParts)) {
        const errorMessage2 = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify({
          name: this.serverToolName,
          args: this.params
        })} with response: ${safeJsonStringify(rawResponseParts)}`;
        return {
          llmContent: errorMessage2,
          returnDisplay: `Error: MCP tool '${this.serverToolName}' reported an error.`,
          error: {
            message: errorMessage2,
            type: "mcp_tool_error" /* MCP_TOOL_ERROR */
          }
        };
      }
      const transformedParts = transformMcpContentToParts(rawResponseParts);
      const truncatedParts = await this.truncateTextParts(transformedParts);
      return {
        llmContent: truncatedParts,
        returnDisplay: getDisplayFromParts(truncatedParts)
      };
    } catch (error) {
      return this.handleReconnectOnError(error, signal, updateOutput);
    } finally {
      if (idleTimeoutId) {
        clearTimeout(idleTimeoutId);
      }
    }
  }
  /**
   * Fallback: execute using the @google/genai CallableTool wrapper.
   * This path does NOT support progress notifications.
   */
  async executeWithCallableTool(signal) {
    const functionCalls = [
      {
        name: this.serverToolName,
        args: this.params
      }
    ];
    try {
      const rawResponseParts = await new Promise((resolve2, reject) => {
        if (signal.aborted) {
          const error = new Error("Tool call aborted");
          error.name = "AbortError";
          reject(error);
          return;
        }
        const onAbort = /* @__PURE__ */ __name(() => {
          cleanup();
          const error = new Error("Tool call aborted");
          error.name = "AbortError";
          reject(error);
        }, "onAbort");
        const cleanup = /* @__PURE__ */ __name(() => {
          signal.removeEventListener("abort", onAbort);
        }, "cleanup");
        signal.addEventListener("abort", onAbort, { once: true });
        this.mcpTool.callTool(functionCalls).then((res) => {
          cleanup();
          resolve2(res);
        }).catch((err) => {
          cleanup();
          reject(err);
        });
      });
      if (this.isMCPToolError(rawResponseParts)) {
        const errorMessage2 = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify(
          functionCalls[0]
        )} with response: ${safeJsonStringify(rawResponseParts)}`;
        return {
          llmContent: errorMessage2,
          returnDisplay: `Error: MCP tool '${this.serverToolName}' reported an error.`,
          error: {
            message: errorMessage2,
            type: "mcp_tool_error" /* MCP_TOOL_ERROR */
          }
        };
      }
      const transformedParts = transformMcpContentToParts(rawResponseParts);
      const truncatedParts = await this.truncateTextParts(transformedParts);
      return {
        llmContent: truncatedParts,
        returnDisplay: getDisplayFromParts(truncatedParts)
      };
    } catch (error) {
      return this.handleReconnectOnError(error, signal);
    }
  }
  /**
   * Truncates text parts in the transformed result if they exceed the
   * configured threshold. Non-text parts (images, audio, etc.) are preserved.
   */
  async truncateTextParts(parts) {
    if (!this.cliConfig) {
      return parts;
    }
    const result = [];
    for (const part of parts) {
      if (part.text && !part.inlineData) {
        const truncated = await truncateToolOutput(
          this.cliConfig,
          `mcp__${this.serverName}__${this.serverToolName}`,
          part.text,
          // Per-tool char budget; mirrors DiscoveredMCPTool.maxOutputChars
          // (10x the global default, since MCP servers return large structured
          // output). char-only (lines: Infinity) so the global line cap can't
          // undercut the 500k char budget — many short lines (structured JSON,
          // tables) would otherwise truncate while chars remain. Consistent
          // with the shell tool's in-tool truncation.
          { threshold: 5e5, lines: Number.POSITIVE_INFINITY }
        );
        result.push({ text: truncated.content });
      } else {
        result.push(part);
      }
    }
    return result;
  }
  getDescription() {
    return safeJsonStringify(this.params);
  }
};
var DiscoveredMCPTool = class _DiscoveredMCPTool extends BaseDeclarativeTool {
  constructor(mcpTool, serverName, serverToolName, description, parameterSchema, trust, nameOverride, cliConfig, mcpClient, mcpTimeout, mcpToolIdleTimeoutMs, annotations, alwaysLoad = false) {
    super(
      nameOverride ?? generateValidName(`mcp__${serverName}__${serverToolName}`),
      `${serverToolName} (${serverName} MCP Server)`,
      description,
      annotations?.readOnlyHint === true ? "read" /* Read */ : "other" /* Other */,
      parameterSchema,
      true,
      // isOutputMarkdown
      true,
      // canUpdateOutput — enables streaming progress for MCP tools
      true,
      // shouldDefer — MCP tools are discovered via ToolSearch to keep the
      //   initial tool-declaration list small when many MCP servers are attached.
      alwaysLoad,
      // searchHint: server name boosts fuzzy matching when the user references
      // the server in their query ("send a slack message").
      `mcp ${serverName}`
    );
    this.mcpTool = mcpTool;
    this.serverName = serverName;
    this.serverToolName = serverToolName;
    this.parameterSchema = parameterSchema;
    this.trust = trust;
    this.cliConfig = cliConfig;
    this.mcpClient = mcpClient;
    this.mcpTimeout = mcpTimeout;
    this.mcpToolIdleTimeoutMs = mcpToolIdleTimeoutMs;
    this.annotations = annotations;
  }
  static {
    __name(this, "DiscoveredMCPTool");
  }
  // MCP servers often return large structured payloads; allow 10x the global
  // budget (mirrors Claude Code's MCP `maxResultSizeChars`) before the
  // scheduler offloads. truncateTextParts uses the same ceiling per text part.
  get maxOutputChars() {
    return 5e5;
  }
  asFullyQualifiedTool() {
    return new _DiscoveredMCPTool(
      this.mcpTool,
      this.serverName,
      this.serverToolName,
      this.description,
      this.parameterSchema,
      this.trust,
      generateValidName(`mcp__${this.serverName}__${this.serverToolName}`),
      this.cliConfig,
      this.mcpClient,
      this.mcpTimeout,
      this.mcpToolIdleTimeoutMs,
      this.annotations,
      this.alwaysLoad
    );
  }
  /**
   * Return a clone of this tool with a different `trust` value while
   * keeping every other field (including the shared underlying
   * `CallableTool` / MCP transport) identical.
   *
   * pool path: a single shared pool entry produces one
   * `DiscoveredMCPTool` snapshot; each `SessionMcpView` clones with
   * its own per-session trust before registering into its session's
   * `ToolRegistry`. Without this clone, mutating `trust` on the shared
   * instance would cross-contaminate sessions.
   *
   * Trust is the only field that legitimately varies per session;
   * everything else (transport, schema, name) is transport-level.
   */
  withTrust(trust) {
    if (trust === this.trust) return this;
    return new _DiscoveredMCPTool(
      this.mcpTool,
      this.serverName,
      this.serverToolName,
      this.description,
      this.parameterSchema,
      trust,
      // Preserve the original name (do NOT re-call generateValidName)
      // — equal-by-name is the registry's deduplication key, and a
      // different name would race-register two tools in the same
      // session.
      this.name,
      this.cliConfig,
      this.mcpClient,
      this.mcpTimeout,
      this.mcpToolIdleTimeoutMs,
      this.annotations,
      this.alwaysLoad
    );
  }
  createInvocation(params) {
    return new DiscoveredMCPToolInvocation(
      this.mcpTool,
      this.serverName,
      this.serverToolName,
      this.displayName,
      this.trust,
      params,
      this.cliConfig,
      this.mcpClient,
      this.mcpTimeout,
      this.mcpToolIdleTimeoutMs,
      this.annotations
    );
  }
};
function wrapMcpCallToolResultAsParts(toolName, result) {
  const response = result.isError ? { error: result, content: result.content } : result;
  return [
    {
      functionResponse: {
        name: toolName,
        response
      }
    }
  ];
}
__name(wrapMcpCallToolResultAsParts, "wrapMcpCallToolResultAsParts");
function transformTextBlock(block) {
  return { text: block.text };
}
__name(transformTextBlock, "transformTextBlock");
function transformImageAudioBlock(block, toolName) {
  return [
    {
      text: `[Tool '${toolName}' provided the following ${block.type} data with mime-type: ${block.mimeType}]`
    },
    {
      inlineData: {
        mimeType: block.mimeType,
        data: block.data
      }
    }
  ];
}
__name(transformImageAudioBlock, "transformImageAudioBlock");
function transformResourceBlock(block, toolName) {
  const resource = block.resource;
  if (resource?.text) {
    return { text: resource.text };
  }
  if (resource?.blob) {
    const mimeType = resource.mimeType || "application/octet-stream";
    return [
      {
        text: `[Tool '${toolName}' provided the following embedded resource with mime-type: ${mimeType}]`
      },
      {
        inlineData: {
          mimeType,
          data: resource.blob
        }
      }
    ];
  }
  return null;
}
__name(transformResourceBlock, "transformResourceBlock");
function transformResourceLinkBlock(block) {
  return {
    text: `Resource Link: ${block.title || block.name} at ${block.uri}`
  };
}
__name(transformResourceLinkBlock, "transformResourceLinkBlock");
function transformMcpContentToParts(sdkResponse) {
  const funcResponse = sdkResponse?.[0]?.functionResponse;
  const mcpContent = funcResponse?.response?.["content"];
  const toolName = funcResponse?.name || "unknown tool";
  if (!Array.isArray(mcpContent)) {
    return [{ text: "[Error: Could not parse tool response]" }];
  }
  const transformed = mcpContent.flatMap(
    (block) => {
      switch (block.type) {
        case "text":
          return transformTextBlock(block);
        case "image":
        case "audio":
          return transformImageAudioBlock(block, toolName);
        case "resource":
          return transformResourceBlock(block, toolName);
        case "resource_link":
          return transformResourceLinkBlock(block);
        default:
          return null;
      }
    }
  );
  return transformed.filter((part) => part !== null);
}
__name(transformMcpContentToParts, "transformMcpContentToParts");
function getDisplayFromParts(parts) {
  if (parts.length === 0) {
    return "";
  }
  const displayParts = [];
  for (const part of parts) {
    if (part.text !== void 0) {
      displayParts.push(part.text);
    } else if (part.inlineData) {
      displayParts.push(`[${part.inlineData.mimeType}]`);
    }
  }
  return displayParts.join("\n");
}
__name(getDisplayFromParts, "getDisplayFromParts");
function generateValidName(name) {
  let validToolname = name.replace(/[^a-zA-Z0-9_.-]/g, "_");
  if (validToolname.length > 63) {
    validToolname = validToolname.slice(0, 28) + "___" + validToolname.slice(-32);
  }
  return validToolname;
}
__name(generateValidName, "generateValidName");

// packages/core/src/telemetry/tool-call-decision.ts
init_esbuild_shims();
function getDecisionFromOutcome(outcome) {
  switch (outcome) {
    case "proceed_once" /* ProceedOnce */:
    case "restore_previous" /* RestorePrevious */:
      return "accept" /* ACCEPT */;
    case "proceed_always" /* ProceedAlways */:
    case "proceed_always_server" /* ProceedAlwaysServer */:
    case "proceed_always_tool" /* ProceedAlwaysTool */:
    case "proceed_always_project" /* ProceedAlwaysProject */:
    case "proceed_always_user" /* ProceedAlwaysUser */:
      return "auto_accept" /* AUTO_ACCEPT */;
    case "modify_with_editor" /* ModifyWithEditor */:
      return "modify" /* MODIFY */;
    case "cancel" /* Cancel */:
    default:
      return "reject" /* REJECT */;
  }
}
__name(getDecisionFromOutcome, "getDecisionFromOutcome");

// packages/core/src/telemetry/types.ts
var StartSessionEvent = class {
  static {
    __name(this, "StartSessionEvent");
  }
  "event.name";
  "event.timestamp";
  session_id;
  model;
  sandbox_enabled;
  core_tools_enabled;
  approval_mode;
  debug_enabled;
  truncate_tool_output_threshold;
  truncate_tool_output_lines;
  mcp_servers;
  telemetry_enabled;
  file_filtering_respect_git_ignore;
  mcp_servers_count;
  mcp_tools_count;
  mcp_tools;
  output_format;
  hooks;
  ide_enabled;
  interactive_shell_enabled;
  skills;
  subagents;
  constructor(config) {
    const mcpServers = config.getMcpServers();
    const toolRegistry = config.getToolRegistry();
    this["event.name"] = "cli_config";
    this.session_id = config.getSessionId();
    this.model = config.getModel();
    this.sandbox_enabled = typeof config.getSandbox() === "string" || !!config.getSandbox();
    this.core_tools_enabled = (config.getPermissionManager?.()?.getAllowRawStrings() ?? config.getCoreTools() ?? []).join(",");
    this.approval_mode = config.getApprovalMode();
    this.debug_enabled = config.getDebugMode();
    this.truncate_tool_output_threshold = config.getTruncateToolOutputThreshold();
    this.truncate_tool_output_lines = config.getTruncateToolOutputLines();
    this.mcp_servers = mcpServers ? Object.keys(mcpServers).join(",") : "";
    this.telemetry_enabled = config.getTelemetryEnabled();
    this.file_filtering_respect_git_ignore = config.getFileFilteringRespectGitIgnore();
    this.mcp_servers_count = mcpServers ? Object.keys(mcpServers).length : 0;
    this.output_format = config.getOutputFormat();
    this.ide_enabled = config.getIdeMode();
    this.interactive_shell_enabled = config.getShouldUseNodePtyShell();
    const hookSystem = config.getHookSystem();
    if (hookSystem) {
      const allHooks = hookSystem.getAllHooks();
      const uniqueEventNames = [...new Set(allHooks.map((h) => h.eventName))];
      if (uniqueEventNames.length > 0) {
        this.hooks = uniqueEventNames.join(",");
      }
    }
    if (toolRegistry) {
      const mcpTools = toolRegistry.getAllTools().filter((tool) => tool instanceof DiscoveredMCPTool);
      this.mcp_tools_count = mcpTools.length;
      this.mcp_tools = mcpTools.map((tool) => tool.name).join(",");
      const skillTool = toolRegistry.getTool(ToolNames.SKILL);
      const skillNames = skillTool?.getAvailableSkillNames?.();
      if (skillNames && skillNames.length > 0) {
        this.skills = skillNames.join(",");
      }
      const agentTool = toolRegistry.getTool(ToolNames.AGENT);
      const subagentNames = agentTool?.getAvailableSubagentNames?.();
      if (subagentNames && subagentNames.length > 0) {
        this.subagents = subagentNames.join(",");
      }
    }
  }
};
var EndSessionEvent = class {
  static {
    __name(this, "EndSessionEvent");
  }
  "event.name";
  "event.timestamp";
  session_id;
  constructor(config) {
    this["event.name"] = "end_session";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.session_id = config?.getSessionId();
  }
};
var UserPromptEvent = class {
  static {
    __name(this, "UserPromptEvent");
  }
  "event.name";
  "event.timestamp";
  prompt_length;
  prompt_id;
  auth_type;
  prompt;
  /** Model that actually processed the prompt (e.g. an inline override). */
  model;
  constructor(prompt_length, prompt_Id, auth_type, prompt, model) {
    this["event.name"] = "user_prompt";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.prompt_length = prompt_length;
    this.prompt_id = prompt_Id;
    this.auth_type = auth_type;
    this.prompt = prompt;
    this.model = model;
  }
};
var UserRetryEvent = class {
  static {
    __name(this, "UserRetryEvent");
  }
  "event.name";
  "event.timestamp";
  prompt_id;
  constructor(prompt_id) {
    this["event.name"] = "user_retry";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.prompt_id = prompt_id;
  }
};
var ToolCallEvent = class {
  static {
    __name(this, "ToolCallEvent");
  }
  "event.name";
  "event.timestamp";
  function_name;
  function_args;
  duration_ms;
  status;
  success;
  // Keep for backward compatibility
  decision;
  error;
  error_type;
  prompt_id;
  response_id;
  tool_type;
  content_length;
  mcp_server_name;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  metadata;
  constructor(call) {
    this["event.name"] = "tool_call";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.function_name = call.request.name;
    this.function_args = call.request.name === ToolNames.STRUCTURED_OUTPUT ? { ...STRUCTURED_OUTPUT_REDACTED_ARGS } : call.request.args;
    this.duration_ms = call.durationMs ?? 0;
    this.status = call.status;
    this.success = call.status === "success";
    this.decision = call.outcome ? getDecisionFromOutcome(call.outcome) : void 0;
    this.error = call.response.error?.message;
    this.error_type = call.response.errorType;
    this.prompt_id = call.request.prompt_id;
    this.content_length = call.response.contentLength;
    if (typeof call.tool !== "undefined" && call.tool instanceof DiscoveredMCPTool) {
      this.tool_type = "mcp";
      this.mcp_server_name = call.tool.serverName;
    } else {
      this.tool_type = "native";
    }
    this.response_id = call.request.response_id;
    if (call.status === "success" && typeof call.response.resultDisplay === "object" && call.response.resultDisplay !== null && "diffStat" in call.response.resultDisplay) {
      const diffStat = call.response.resultDisplay.diffStat;
      if (diffStat) {
        this.metadata = {
          model_added_lines: diffStat.model_added_lines,
          model_removed_lines: diffStat.model_removed_lines,
          model_added_chars: diffStat.model_added_chars,
          model_removed_chars: diffStat.model_removed_chars,
          user_added_lines: diffStat.user_added_lines,
          user_removed_lines: diffStat.user_removed_lines,
          user_added_chars: diffStat.user_added_chars,
          user_removed_chars: diffStat.user_removed_chars
        };
      }
    }
  }
};
var ApiRequestEvent = class {
  static {
    __name(this, "ApiRequestEvent");
  }
  "event.name";
  "event.timestamp";
  model;
  prompt_id;
  request_text;
  /**
   * Name of the subagent that issued this request, or undefined when the
   * request originates from the main conversation.
   */
  subagent_name;
  constructor(model, prompt_id, request_text, subagent_name) {
    this["event.name"] = "api_request";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.model = model;
    this.prompt_id = prompt_id;
    this.request_text = request_text;
    this.subagent_name = subagent_name;
  }
};
var ApiErrorEvent = class {
  static {
    __name(this, "ApiErrorEvent");
  }
  "event.name";
  "event.timestamp";
  // ISO 8601
  response_id;
  model;
  duration_ms;
  prompt_id;
  auth_type;
  // Human-readable error message (e.g. "Request failed with status 429")
  error_message;
  // Error class or category (e.g. "RateLimitError", "invalid_request_error")
  error_type;
  // HTTP status code from the API response (e.g. 429, 500)
  status_code;
  /**
   * Name of the subagent that issued this request, or undefined when the
   * request originates from the main conversation.
   */
  subagent_name;
  constructor(opts) {
    this["event.name"] = "api_error";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.response_id = opts.responseId;
    this.model = opts.model;
    this.duration_ms = opts.durationMs;
    this.prompt_id = opts.promptId;
    this.auth_type = opts.authType;
    this.error_message = opts.errorMessage;
    this.error_type = opts.errorType;
    this.status_code = opts.statusCode;
    this.subagent_name = opts.subagentName;
  }
};
var ApiCancelEvent = class {
  static {
    __name(this, "ApiCancelEvent");
  }
  "event.name";
  "event.timestamp";
  model;
  prompt_id;
  auth_type;
  // Pending self-paced /loop wakeups dropped by this abort, when any. Lets a
  // user abort that ends a loop be told apart from an ordinary cancellation.
  // Named for wakeups (not "loops") to avoid colliding with loop_type, the
  // unrelated repetition-detection vocabulary in this file.
  loop_wakeups_cancelled;
  constructor(model, prompt_id, auth_type, loop_wakeups_cancelled) {
    this["event.name"] = "api_cancel";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.model = model;
    this.prompt_id = prompt_id;
    this.auth_type = auth_type;
    this.loop_wakeups_cancelled = loop_wakeups_cancelled;
  }
};
var ApiResponseEvent = class {
  static {
    __name(this, "ApiResponseEvent");
  }
  "event.name";
  "event.timestamp";
  // ISO 8601
  response_id;
  model;
  status_code;
  duration_ms;
  input_token_count;
  output_token_count;
  cached_content_token_count;
  thoughts_token_count;
  total_token_count;
  response_text;
  prompt_id;
  auth_type;
  /**
   * Name of the subagent that issued this request, or undefined when the
   * request originates from the main conversation.
   */
  subagent_name;
  constructor(response_id, model, duration_ms, prompt_id, auth_type, usage_data, response_text, subagent_name) {
    this["event.name"] = "api_response";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.response_id = response_id;
    this.model = model;
    this.duration_ms = duration_ms;
    this.status_code = 200;
    this.input_token_count = usage_data?.promptTokenCount ?? 0;
    this.output_token_count = usage_data?.candidatesTokenCount ?? 0;
    this.cached_content_token_count = usage_data?.cachedContentTokenCount ?? 0;
    this.thoughts_token_count = usage_data?.thoughtsTokenCount ?? 0;
    this.total_token_count = usage_data?.totalTokenCount ?? 0;
    this.response_text = response_text;
    this.prompt_id = prompt_id;
    this.auth_type = auth_type;
    this.subagent_name = subagent_name;
  }
};
var FlashFallbackEvent = class {
  static {
    __name(this, "FlashFallbackEvent");
  }
  "event.name";
  "event.timestamp";
  auth_type;
  constructor(auth_type) {
    this["event.name"] = "flash_fallback";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.auth_type = auth_type;
  }
};
var RipgrepFallbackEvent = class {
  static {
    __name(this, "RipgrepFallbackEvent");
  }
  "event.name";
  "event.timestamp";
  use_ripgrep;
  use_builtin_ripgrep;
  error;
  constructor(use_ripgrep, use_builtin_ripgrep, error) {
    this["event.name"] = "ripgrep_fallback";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.use_ripgrep = use_ripgrep;
    this.use_builtin_ripgrep = use_builtin_ripgrep;
    this.error = error;
  }
};
var LoopType = /* @__PURE__ */ ((LoopType2) => {
  LoopType2["CONSECUTIVE_IDENTICAL_TOOL_CALLS"] = "consecutive_identical_tool_calls";
  LoopType2["CHANTING_IDENTICAL_SENTENCES"] = "chanting_identical_sentences";
  LoopType2["REPETITIVE_THOUGHTS"] = "repetitive_thoughts";
  LoopType2["READ_FILE_LOOP"] = "read_file_loop";
  LoopType2["ACTION_STAGNATION"] = "action_stagnation";
  LoopType2["SHELL_COMMAND_STAGNATION"] = "shell_command_stagnation";
  LoopType2["GLOBAL_TOOL_CALL_DUPLICATE"] = "global_tool_call_duplicate";
  LoopType2["ALTERNATING_TOOL_CALL_PATTERN"] = "alternating_tool_call_pattern";
  LoopType2["TURN_TOOL_CALL_CAP"] = "turn_tool_call_cap";
  LoopType2["INVALID_TOOL_PARAMS_STAGNATION"] = "invalid_tool_params_stagnation";
  return LoopType2;
})(LoopType || {});
var LoopDetectedEvent = class {
  static {
    __name(this, "LoopDetectedEvent");
  }
  "event.name";
  "event.timestamp";
  loop_type;
  prompt_id;
  constructor(loop_type, prompt_id) {
    this["event.name"] = "loop_detected";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.loop_type = loop_type;
    this.prompt_id = prompt_id;
  }
};
var LoopDetectionDisabledEvent = class {
  static {
    __name(this, "LoopDetectionDisabledEvent");
  }
  "event.name";
  "event.timestamp";
  prompt_id;
  constructor(prompt_id) {
    this["event.name"] = "loop_detection_disabled";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.prompt_id = prompt_id;
  }
};
var NextSpeakerCheckEvent = class {
  static {
    __name(this, "NextSpeakerCheckEvent");
  }
  "event.name";
  "event.timestamp";
  prompt_id;
  finish_reason;
  result;
  constructor(prompt_id, finish_reason, result) {
    this["event.name"] = "next_speaker_check";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.prompt_id = prompt_id;
    this.finish_reason = finish_reason;
    this.result = result;
  }
};
function makeSlashCommandEvent({
  command,
  subcommand,
  status
}) {
  return {
    "event.name": "slash_command",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    command,
    subcommand,
    status
  };
}
__name(makeSlashCommandEvent, "makeSlashCommandEvent");
var SlashCommandStatus = /* @__PURE__ */ ((SlashCommandStatus2) => {
  SlashCommandStatus2["SUCCESS"] = "success";
  SlashCommandStatus2["ERROR"] = "error";
  return SlashCommandStatus2;
})(SlashCommandStatus || {});
function makeChatCompressionEvent({
  tokens_before,
  tokens_after,
  compression_input_token_count,
  compression_output_token_count
}) {
  return {
    "event.name": "chat_compression",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    tokens_before,
    tokens_after,
    ...compression_input_token_count !== void 0 ? { compression_input_token_count } : {},
    ...compression_output_token_count !== void 0 ? { compression_output_token_count } : {}
  };
}
__name(makeChatCompressionEvent, "makeChatCompressionEvent");
var IdeConnectionType = /* @__PURE__ */ ((IdeConnectionType2) => {
  IdeConnectionType2["START"] = "start";
  IdeConnectionType2["SESSION"] = "session";
  return IdeConnectionType2;
})(IdeConnectionType || {});
var IdeConnectionEvent = class {
  static {
    __name(this, "IdeConnectionEvent");
  }
  "event.name";
  "event.timestamp";
  connection_type;
  constructor(connection_type) {
    this["event.name"] = "ide_connection";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.connection_type = connection_type;
  }
};
var ConversationFinishedEvent = class {
  static {
    __name(this, "ConversationFinishedEvent");
  }
  "event_name";
  "event.timestamp";
  // ISO 8601;
  approvalMode;
  turnCount;
  constructor(approvalMode, turnCount) {
    this["event_name"] = "conversation_finished";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.approvalMode = approvalMode;
    this.turnCount = turnCount;
  }
};
var KittySequenceOverflowEvent = class {
  static {
    __name(this, "KittySequenceOverflowEvent");
  }
  "event.name";
  "event.timestamp";
  // ISO 8601
  sequence_length;
  truncated_sequence;
  constructor(sequence_length, truncated_sequence) {
    this["event.name"] = "kitty_sequence_overflow";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.sequence_length = sequence_length;
    this.truncated_sequence = truncated_sequence.substring(0, 20);
  }
};
var FileOperationEvent = class {
  static {
    __name(this, "FileOperationEvent");
  }
  "event.name";
  "event.timestamp";
  tool_name;
  operation;
  lines;
  mimetype;
  extension;
  programming_language;
  constructor(tool_name, operation, lines, mimetype, extension, programming_language) {
    this["event.name"] = "file_operation";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.tool_name = tool_name;
    this.operation = operation;
    this.lines = lines;
    this.mimetype = mimetype;
    this.extension = extension;
    this.programming_language = programming_language;
  }
};
var ContentRetryEvent = class {
  static {
    __name(this, "ContentRetryEvent");
  }
  "event.name";
  "event.timestamp";
  attempt_number;
  error_type;
  // e.g., 'EmptyStreamError'
  retry_delay_ms;
  model;
  constructor(attempt_number, error_type, retry_delay_ms, model) {
    this["event.name"] = "content_retry";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.attempt_number = attempt_number;
    this.error_type = error_type;
    this.retry_delay_ms = retry_delay_ms;
    this.model = model;
  }
};
var ApiRetryEvent = class {
  static {
    __name(this, "ApiRetryEvent");
  }
  "event.name";
  "event.timestamp";
  // ISO 8601
  model;
  prompt_id;
  attempt_number;
  // 1-based monotonic counter (matches ALS retryContext.attempt)
  error_type;
  error_message;
  status_code;
  retry_delay_ms;
  /**
   * Reports the backoff delay following this failed attempt (NOT the attempt's
   * own duration — that lives on the corresponding `qwen-code.llm_request`
   * span's `duration_ms` attribute). Set equal to `retry_delay_ms` so the
   * LogToSpanProcessor bridge span visualises the sleep window between the
   * failed and next attempt in the trace timeline.
   */
  duration_ms;
  /**
   * Name of the subagent that issued the retrying request, or undefined when
   * the request originates from the main conversation. Read from
   * `subagentNameContext.getStore()` at the caller site (subagentNameContext
   * is still active inside `retry.ts`'s catch block where `onRetry` fires).
   */
  subagent_name;
  constructor(opts) {
    this["event.name"] = "api_retry";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.model = opts.model;
    this.prompt_id = opts.promptId;
    this.attempt_number = opts.attemptNumber;
    this.error_message = opts.error instanceof Error ? opts.error.message : String(opts.error ?? "unknown error");
    this.error_type = opts.error instanceof Error ? opts.error.constructor.name : void 0;
    this.status_code = opts.statusCode;
    this.retry_delay_ms = opts.retryDelayMs;
    this.duration_ms = opts.retryDelayMs;
    this.subagent_name = opts.subagentName;
  }
};
var ContentRetryFailureEvent = class {
  static {
    __name(this, "ContentRetryFailureEvent");
  }
  "event.name";
  "event.timestamp";
  total_attempts;
  final_error_type;
  total_duration_ms;
  // Optional: total time spent retrying
  model;
  constructor(total_attempts, final_error_type, model, total_duration_ms) {
    this["event.name"] = "content_retry_failure";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.total_attempts = total_attempts;
    this.final_error_type = final_error_type;
    this.total_duration_ms = total_duration_ms;
    this.model = model;
  }
};
var ExtensionInstallEvent = class {
  static {
    __name(this, "ExtensionInstallEvent");
  }
  "event.name";
  "event.timestamp";
  extension_name;
  extension_version;
  extension_source;
  status;
  constructor(extension_name, extension_version, extension_source, status) {
    this["event.name"] = "extension_install";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.extension_name = extension_name;
    this.extension_version = extension_version;
    this.extension_source = extension_source;
    this.status = status;
  }
};
var ToolOutputTruncatedEvent = class {
  static {
    __name(this, "ToolOutputTruncatedEvent");
  }
  eventName = "tool_output_truncated";
  "event.timestamp" = (/* @__PURE__ */ new Date()).toISOString();
  "event.name";
  tool_name;
  original_content_length;
  truncated_content_length;
  threshold;
  lines;
  prompt_id;
  constructor(prompt_id, details) {
    this["event.name"] = this.eventName;
    this.prompt_id = prompt_id;
    this.tool_name = details.toolName;
    this.original_content_length = details.originalContentLength;
    this.truncated_content_length = details.truncatedContentLength;
    this.threshold = details.threshold;
    this.lines = details.lines;
  }
};
var ExtensionUninstallEvent = class {
  static {
    __name(this, "ExtensionUninstallEvent");
  }
  "event.name";
  "event.timestamp";
  extension_name;
  status;
  constructor(extension_name, status) {
    this["event.name"] = "extension_uninstall";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.extension_name = extension_name;
    this.status = status;
  }
};
var ExtensionUpdateEvent = class {
  static {
    __name(this, "ExtensionUpdateEvent");
  }
  "event.name";
  "event.timestamp";
  extension_name;
  extension_id;
  extension_previous_version;
  extension_version;
  extension_source;
  status;
  constructor(extension_name, extension_id, extension_version, extension_previous_version, extension_source, status) {
    this["event.name"] = "extension_update";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.extension_name = extension_name;
    this.extension_id = extension_id;
    this.extension_version = extension_version;
    this.extension_previous_version = extension_previous_version;
    this.extension_source = extension_source;
    this.status = status;
  }
};
var ExtensionEnableEvent = class {
  static {
    __name(this, "ExtensionEnableEvent");
  }
  "event.name";
  "event.timestamp";
  extension_name;
  setting_scope;
  constructor(extension_name, settingScope) {
    this["event.name"] = "extension_enable";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.extension_name = extension_name;
    this.setting_scope = settingScope;
  }
};
var ModelSlashCommandEvent = class {
  static {
    __name(this, "ModelSlashCommandEvent");
  }
  "event.name";
  "event.timestamp";
  model_name;
  constructor(model_name) {
    this["event.name"] = "model_slash_command";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.model_name = model_name;
  }
};
var SubagentExecutionEvent = class {
  static {
    __name(this, "SubagentExecutionEvent");
  }
  "event.name";
  "event.timestamp";
  subagent_name;
  status;
  terminate_reason;
  result;
  execution_summary;
  constructor(subagent_name, status, options) {
    this["event.name"] = "subagent_execution";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.subagent_name = subagent_name;
    this.status = status;
    this.terminate_reason = options?.terminate_reason;
    this.result = options?.result;
    this.execution_summary = options?.execution_summary;
  }
};
var AuthEvent = class {
  static {
    __name(this, "AuthEvent");
  }
  "event.name";
  "event.timestamp";
  auth_type;
  action_type;
  status;
  error_message;
  constructor(auth_type, action_type, status, error_message) {
    this["event.name"] = "auth";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.auth_type = auth_type;
    this.action_type = action_type;
    this.status = status;
    this.error_message = error_message;
  }
};
var HookCallEvent = class {
  static {
    __name(this, "HookCallEvent");
  }
  "event.name";
  "event.timestamp";
  hook_event_name;
  hook_type;
  hook_name;
  hook_input;
  hook_output;
  exit_code;
  stdout;
  stderr;
  duration_ms;
  success;
  error;
  constructor(hookEventName, hookType, hookName, hookInput, durationMs, success, hookOutput, exitCode, stdout, stderr, error) {
    this["event.name"] = "hook_call";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.hook_event_name = hookEventName;
    this.hook_type = hookType;
    this.hook_name = hookName;
    this.hook_input = hookInput;
    this.hook_output = hookOutput;
    this.exit_code = exitCode;
    this.stdout = stdout;
    this.stderr = stderr;
    this.duration_ms = durationMs;
    this.success = success;
    this.error = error;
  }
};
var SkillLaunchEvent = class {
  static {
    __name(this, "SkillLaunchEvent");
  }
  "event.name";
  "event.timestamp";
  skill_name;
  success;
  prompt_id;
  constructor(skill_name, success, prompt_id = "") {
    this["event.name"] = "skill_launch";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.skill_name = skill_name;
    this.success = success;
    this.prompt_id = prompt_id;
  }
};
var UserFeedbackRating = /* @__PURE__ */ ((UserFeedbackRating2) => {
  UserFeedbackRating2[UserFeedbackRating2["BAD"] = 1] = "BAD";
  UserFeedbackRating2[UserFeedbackRating2["FINE"] = 2] = "FINE";
  UserFeedbackRating2[UserFeedbackRating2["GOOD"] = 3] = "GOOD";
  return UserFeedbackRating2;
})(UserFeedbackRating || {});
var UserFeedbackEvent = class {
  static {
    __name(this, "UserFeedbackEvent");
  }
  "event.name";
  "event.timestamp";
  session_id;
  rating;
  model;
  approval_mode;
  prompt_id;
  constructor(session_id, rating, model, approval_mode, prompt_id) {
    this["event.name"] = "user_feedback";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.session_id = session_id;
    this.rating = rating;
    this.model = model;
    this.approval_mode = approval_mode;
    this.prompt_id = prompt_id;
  }
};
function makeArenaSessionStartedEvent({
  arena_session_id,
  model_ids,
  task_length
}) {
  return {
    "event.name": "arena_session_started",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    arena_session_id,
    model_ids,
    task_length
  };
}
__name(makeArenaSessionStartedEvent, "makeArenaSessionStartedEvent");
function makeArenaAgentCompletedEvent({
  arena_session_id,
  agent_session_id,
  agent_model_id,
  status,
  duration_ms,
  rounds,
  total_tokens,
  input_tokens,
  output_tokens,
  tool_calls,
  successful_tool_calls,
  failed_tool_calls
}) {
  return {
    "event.name": "arena_agent_completed",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    arena_session_id,
    agent_session_id,
    agent_model_id,
    status,
    duration_ms,
    rounds,
    total_tokens,
    input_tokens,
    output_tokens,
    tool_calls,
    successful_tool_calls,
    failed_tool_calls
  };
}
__name(makeArenaAgentCompletedEvent, "makeArenaAgentCompletedEvent");
function makeArenaSessionEndedEvent({
  arena_session_id,
  status,
  duration_ms,
  display_backend,
  agent_count,
  completed_agents,
  failed_agents,
  cancelled_agents,
  winner_model_id
}) {
  return {
    "event.name": "arena_session_ended",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    arena_session_id,
    status,
    duration_ms,
    display_backend,
    agent_count,
    completed_agents,
    failed_agents,
    cancelled_agents,
    winner_model_id
  };
}
__name(makeArenaSessionEndedEvent, "makeArenaSessionEndedEvent");
var ExtensionDisableEvent = class {
  static {
    __name(this, "ExtensionDisableEvent");
  }
  "event.name";
  "event.timestamp";
  extension_name;
  setting_scope;
  constructor(extension_name, settingScope) {
    this["event.name"] = "extension_disable";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.extension_name = extension_name;
    this.setting_scope = settingScope;
  }
};
var PromptSuggestionEvent = class {
  static {
    __name(this, "PromptSuggestionEvent");
  }
  "event.name";
  "event.timestamp";
  outcome;
  prompt_id;
  accept_method;
  accept_source;
  time_to_accept_ms;
  time_to_ignore_ms;
  time_to_first_keystroke_ms;
  suggestion_length;
  similarity;
  was_focused_when_shown;
  reason;
  constructor(params) {
    this["event.name"] = "qwen-code.prompt_suggestion";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.outcome = params.outcome;
    this.prompt_id = params.prompt_id ?? "user_intent";
    this.accept_method = params.accept_method;
    this.accept_source = params.accept_source;
    this.time_to_accept_ms = params.time_to_accept_ms;
    this.time_to_ignore_ms = params.time_to_ignore_ms;
    this.time_to_first_keystroke_ms = params.time_to_first_keystroke_ms;
    this.suggestion_length = params.suggestion_length;
    this.similarity = params.similarity;
    this.was_focused_when_shown = params.was_focused_when_shown;
    this.reason = params.reason;
  }
};
var SpeculationEvent = class {
  static {
    __name(this, "SpeculationEvent");
  }
  "event.name";
  "event.timestamp";
  outcome;
  turns_used;
  files_written;
  tool_use_count;
  duration_ms;
  boundary_type;
  had_pipelined_suggestion;
  constructor(params) {
    this["event.name"] = "qwen-code.speculation";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.outcome = params.outcome;
    this.turns_used = params.turns_used;
    this.files_written = params.files_written;
    this.tool_use_count = params.tool_use_count;
    this.duration_ms = params.duration_ms;
    this.boundary_type = params.boundary_type;
    this.had_pipelined_suggestion = params.had_pipelined_suggestion;
  }
};
var WorkflowKeywordEvent = class {
  static {
    __name(this, "WorkflowKeywordEvent");
  }
  "event.name";
  "event.timestamp";
  constructor() {
    this["event.name"] = "qwen-code.workflow_keyword";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
  }
};
var WorkflowRunEvent = class {
  static {
    __name(this, "WorkflowRunEvent");
  }
  "event.name";
  "event.timestamp";
  status;
  agents_dispatched;
  agents_completed;
  phase_count;
  tokens_spent;
  duration_ms;
  constructor(params) {
    this["event.name"] = "qwen-code.workflow_run";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.status = params.status;
    this.agents_dispatched = params.agents_dispatched;
    this.agents_completed = params.agents_completed;
    this.phase_count = params.phase_count;
    this.tokens_spent = params.tokens_spent;
    this.duration_ms = params.duration_ms;
  }
};
var MemoryExtractEvent = class {
  static {
    __name(this, "MemoryExtractEvent");
  }
  "event.name";
  "event.timestamp";
  /** 'auto' = triggered by session turn; 'manual' = user-initiated */
  trigger;
  status;
  skipped_reason;
  patches_count;
  touched_topics;
  duration_ms;
  constructor(params) {
    this["event.name"] = "qwen-code.memory.extract";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.trigger = params.trigger;
    this.status = params.status;
    this.skipped_reason = params.skipped_reason;
    this.patches_count = params.patches_count;
    this.touched_topics = params.touched_topics.join(",");
    this.duration_ms = params.duration_ms;
  }
};
var MemoryDreamEvent = class {
  static {
    __name(this, "MemoryDreamEvent");
  }
  "event.name";
  "event.timestamp";
  /** 'auto' = scheduler-triggered; 'manual' = user ran /dream */
  trigger;
  status;
  deduped_entries;
  touched_topics_count;
  touched_topics;
  duration_ms;
  constructor(params) {
    this["event.name"] = "qwen-code.memory.dream";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.trigger = params.trigger;
    this.status = params.status;
    this.deduped_entries = params.deduped_entries;
    this.touched_topics_count = params.touched_topics.length;
    this.touched_topics = params.touched_topics.join(",");
    this.duration_ms = params.duration_ms;
  }
};
var MemoryRecallEvent = class {
  static {
    __name(this, "MemoryRecallEvent");
  }
  "event.name";
  "event.timestamp";
  query_length;
  docs_scanned;
  docs_selected;
  strategy;
  duration_ms;
  constructor(params) {
    this["event.name"] = "qwen-code.memory.recall";
    this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
    this.query_length = params.query_length;
    this.docs_scanned = params.docs_scanned;
    this.docs_selected = params.docs_selected;
    this.strategy = params.strategy;
    this.duration_ms = params.duration_ms;
  }
};

// packages/core/src/utils/subagentNameContext.ts
init_esbuild_shims();
import { AsyncLocalStorage } from "node:async_hooks";
var MAIN_SOURCE = "main";
var subagentNameContext = new AsyncLocalStorage();

// packages/core/src/core/openaiContentGenerator/converter.ts
init_esbuild_shims();

// packages/core/src/core/openaiContentGenerator/taggedThinkingParser.ts
init_esbuild_shims();
var debugLogger5 = createDebugLogger("TAGGED_THINKING_PARSER");
var OPEN_TAGS = ["<think>", "<thinking>"];
var CLOSE_TAGS = ["</think>", "</thinking>"];
var MAX_TAG_LENGTH = Math.max(
  ...OPEN_TAGS.map((t) => t.length),
  ...CLOSE_TAGS.map((t) => t.length)
);
function appendPart(parts, text, mode) {
  if (!text) return;
  parts.push(mode === "thought" ? { text, thought: true } : { text });
}
__name(appendPart, "appendPart");
function isPrefixOfAnyTag(lower, offset, tags) {
  const remainingLen = lower.length - offset;
  if (remainingLen <= 0) return false;
  if (remainingLen > MAX_TAG_LENGTH) return false;
  return tags.some(
    (tag) => tag.startsWith(lower.slice(offset, offset + remainingLen))
  );
}
__name(isPrefixOfAnyTag, "isPrefixOfAnyTag");
function findMatchingTag(lower, offset, tags) {
  return tags.find((tag) => lower.startsWith(tag, offset));
}
__name(findMatchingTag, "findMatchingTag");
var TaggedThinkingParser = class {
  static {
    __name(this, "TaggedThinkingParser");
  }
  mode = "text";
  buffer = "";
  parse(chunk, final = false) {
    this.buffer += chunk;
    const lower = this.buffer.toLowerCase();
    const parts = [];
    let segment = "";
    let index = 0;
    while (index < this.buffer.length) {
      const activeTags = this.mode === "text" ? OPEN_TAGS : CLOSE_TAGS;
      const matchedTag = findMatchingTag(lower, index, activeTags);
      if (matchedTag) {
        debugLogger5.debug(
          `taggedThinking: detected tag "${matchedTag}" at offset ${index}`
        );
        appendPart(parts, segment, this.mode);
        segment = "";
        this.mode = this.mode === "text" ? "thought" : "text";
        index += matchedTag.length;
        continue;
      }
      if (!final && isPrefixOfAnyTag(lower, index, activeTags)) {
        break;
      }
      segment += this.buffer[index];
      index += 1;
    }
    if (index < this.buffer.length) {
      appendPart(parts, segment, this.mode);
      this.buffer = this.buffer.slice(index);
      debugLogger5.debug(
        `taggedThinking: emitted ${parts.length} part(s), buffered ${this.buffer.length} char(s)`
      );
      return parts;
    }
    this.buffer = "";
    if (this.mode === "thought" && segment) {
      debugLogger5.warn(
        `taggedThinking: flushing ${segment.length} chars of unclosed thought on stream end`
      );
    }
    appendPart(parts, segment, this.mode);
    debugLogger5.debug(
      `taggedThinking: emitted ${parts.length} part(s), flush complete`
    );
    return parts;
  }
};
function parseTaggedThinkingText(text) {
  return new TaggedThinkingParser().parse(text, true);
}
__name(parseTaggedThinkingText, "parseTaggedThinkingText");

// packages/core/src/core/openaiContentGenerator/converter.ts
var debugLogger6 = createDebugLogger("CONVERTER");
var SPLIT_TOOL_MEDIA_TEXT = "(attached media from previous tool call)";
var CUMULATIVE_DELTA_EXACT_REPEAT_MIN_LENGTH = 64;
var CUMULATIVE_DETECTION_WINDOW_BYTES = 1024;
function normalizeStreamingTextDelta(rawDelta, state) {
  if (rawDelta.length === 0) {
    return "";
  }
  if (state.emittedText.length === 0) {
    state.emittedText = rawDelta;
    state.emittedLength = rawDelta.length;
    return rawDelta;
  }
  if (state.cumulativeMode) {
    if (rawDelta.startsWith(state.emittedText)) {
      const suffix = rawDelta.slice(state.emittedText.length);
      state.emittedText = rawDelta;
      state.emittedLength = rawDelta.length;
      return suffix;
    }
    if (state.emittedText.startsWith(rawDelta)) {
      debugLogger6.debug(
        `normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${state.emittedText.length}b, chunk=${rawDelta.length}b)`
      );
      return "";
    }
    debugLogger6.debug(
      "normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"
    );
    state.cumulativeMode = false;
    state.emittedText = rawDelta;
    state.emittedLength += rawDelta.length;
    return rawDelta;
  }
  if (rawDelta.length > state.emittedText.length && rawDelta.startsWith(state.emittedText)) {
    const baselineLen = state.emittedText.length;
    const baselineFrozenAtCap = baselineLen >= CUMULATIVE_DETECTION_WINDOW_BYTES && state.emittedLength > baselineLen;
    const sliceFrom = baselineFrozenAtCap ? state.emittedLength : baselineLen;
    if (rawDelta.length > sliceFrom) {
      const suffix = rawDelta.slice(sliceFrom);
      state.emittedText = rawDelta;
      state.emittedLength = rawDelta.length;
      state.cumulativeMode = true;
      debugLogger6.debug(
        `normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${baselineLen}b sliceFrom=${sliceFrom}b -> curr=${rawDelta.length}b)`
      );
      return suffix;
    }
  }
  if (rawDelta === state.emittedText) {
    if (rawDelta.length >= CUMULATIVE_DELTA_EXACT_REPEAT_MIN_LENGTH) {
      state.cumulativeMode = true;
      debugLogger6.debug(
        `normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${rawDelta.length}b)`
      );
      return "";
    }
    state.emittedLength += rawDelta.length;
    return rawDelta;
  }
  if (state.emittedText.length < CUMULATIVE_DETECTION_WINDOW_BYTES) {
    state.emittedText += rawDelta;
  }
  state.emittedLength += rawDelta.length;
  return rawDelta;
}
__name(normalizeStreamingTextDelta, "normalizeStreamingTextDelta");
function convertGeminiToolParametersToOpenAI(parameters) {
  if (!parameters || typeof parameters !== "object") {
    return parameters;
  }
  const converted = JSON.parse(JSON.stringify(parameters));
  const convertTypes = /* @__PURE__ */ __name((obj) => {
    if (typeof obj !== "object" || obj === null) {
      return obj;
    }
    if (Array.isArray(obj)) {
      return obj.map(convertTypes);
    }
    const result = {};
    for (const [key, value] of Object.entries(obj)) {
      if (key === "type" && typeof value === "string") {
        const lowerValue = value.toLowerCase();
        if (lowerValue === "integer") {
          result[key] = "integer";
        } else if (lowerValue === "number") {
          result[key] = "number";
        } else {
          result[key] = lowerValue;
        }
      } else if (key === "minimum" || key === "maximum" || key === "multipleOf") {
        if (typeof value === "string" && !isNaN(Number(value))) {
          result[key] = Number(value);
        } else {
          result[key] = value;
        }
      } else if (key === "minLength" || key === "maxLength" || key === "minItems" || key === "maxItems") {
        const numberValue = typeof value === "string" ? Number(value) : NaN;
        if (typeof value === "string" && value.trim() !== "" && Number.isInteger(numberValue)) {
          result[key] = numberValue;
        } else {
          result[key] = value;
        }
      } else if (typeof value === "object") {
        result[key] = convertTypes(value);
      } else {
        result[key] = value;
      }
    }
    return result;
  }, "convertTypes");
  return convertTypes(converted);
}
__name(convertGeminiToolParametersToOpenAI, "convertGeminiToolParametersToOpenAI");
async function convertGeminiToolsToOpenAI(geminiTools, schemaCompliance = "auto") {
  const openAITools = [];
  for (const tool of geminiTools) {
    let actualTool;
    if ("tool" in tool) {
      actualTool = await tool.tool();
    } else {
      actualTool = tool;
    }
    if (actualTool.functionDeclarations) {
      for (const func of actualTool.functionDeclarations) {
        if (func.name && func.description) {
          let parameters;
          if (func.parametersJsonSchema) {
            const paramsCopy = {
              ...func.parametersJsonSchema
            };
            parameters = paramsCopy;
          } else if (func.parameters) {
            parameters = convertGeminiToolParametersToOpenAI(
              func.parameters
            );
          }
          if (parameters) {
            parameters = convertSchema(parameters, schemaCompliance);
          }
          openAITools.push({
            type: "function",
            function: {
              name: func.name,
              description: func.description,
              parameters
            }
          });
        }
      }
    }
  }
  return openAITools;
}
__name(convertGeminiToolsToOpenAI, "convertGeminiToolsToOpenAI");
function convertGeminiRequestToOpenAI(request4, requestContext, options = { cleanOrphanToolCalls: true }) {
  let messages = [];
  addSystemInstructionMessage(request4, messages);
  processContents(request4.contents, messages, requestContext);
  messages = mergeConsecutiveAssistantMessages(messages);
  if (options.cleanOrphanToolCalls) {
    messages = cleanOrphanedToolCalls(messages);
    messages = mergeConsecutiveAssistantMessages(messages);
  }
  return messages;
}
__name(convertGeminiRequestToOpenAI, "convertGeminiRequestToOpenAI");
function convertGeminiResponseToOpenAI(response, requestContext) {
  const candidate = response.candidates?.[0];
  const parts = candidate?.content?.parts || [];
  const thoughtParts = [];
  const contentParts = [];
  const toolCalls = [];
  let toolCallIndex = 0;
  for (const part of parts) {
    if (typeof part === "string") {
      contentParts.push(part);
    } else if ("text" in part && part.text) {
      if ("thought" in part && part.thought) {
        thoughtParts.push(part.text);
      } else {
        contentParts.push(part.text);
      }
    } else if ("functionCall" in part && part.functionCall) {
      toolCalls.push({
        id: part.functionCall.id || `call_${toolCallIndex}`,
        type: "function",
        function: {
          name: part.functionCall.name || "",
          arguments: JSON.stringify(part.functionCall.args || {})
        }
      });
      toolCallIndex += 1;
    }
  }
  const message = {
    role: "assistant",
    content: contentParts.join("") || null,
    refusal: null
  };
  const reasoningContent = thoughtParts.join("");
  if (reasoningContent) {
    message.reasoning_content = reasoningContent;
  }
  if (toolCalls.length > 0) {
    message.tool_calls = toolCalls;
  }
  const finishReason = mapGeminiFinishReasonToOpenAI(candidate?.finishReason);
  const usageMetadata = response.usageMetadata;
  const usage = {
    prompt_tokens: usageMetadata?.promptTokenCount || 0,
    completion_tokens: usageMetadata?.candidatesTokenCount || 0,
    total_tokens: usageMetadata?.totalTokenCount || 0
  };
  if (usageMetadata?.cachedContentTokenCount !== void 0) {
    usage.prompt_tokens_details = {
      cached_tokens: usageMetadata.cachedContentTokenCount
    };
  }
  const createdMs = response.createTime ? Number(response.createTime) : Date.now();
  const createdSeconds = Number.isFinite(createdMs) ? Math.floor(createdMs / 1e3) : Math.floor(Date.now() / 1e3);
  return {
    id: response.responseId || `gemini-${Date.now()}`,
    object: "chat.completion",
    created: createdSeconds,
    model: response.modelVersion || requestContext.model,
    choices: [
      {
        index: 0,
        message,
        finish_reason: finishReason,
        logprobs: null
      }
    ],
    usage
  };
}
__name(convertGeminiResponseToOpenAI, "convertGeminiResponseToOpenAI");
function addSystemInstructionMessage(request4, messages) {
  if (!request4.config?.systemInstruction) return;
  const systemText = extractTextFromContentUnion(
    request4.config.systemInstruction
  );
  if (systemText) {
    messages.push({
      role: "system",
      content: systemText
    });
  }
}
__name(addSystemInstructionMessage, "addSystemInstructionMessage");
function processContents(contents, messages, requestContext) {
  if (Array.isArray(contents)) {
    for (const content of contents) {
      processContent(content, messages, requestContext);
    }
  } else if (contents) {
    processContent(contents, messages, requestContext);
  }
}
__name(processContents, "processContents");
function processContent(content, messages, requestContext) {
  if (typeof content === "string") {
    messages.push({ role: "user", content });
    return;
  }
  if (!isContentObject(content)) return;
  const parts = content.parts || [];
  const role = content.role === "model" ? "assistant" : "user";
  const contentParts = [];
  const reasoningParts = [];
  const toolCalls = [];
  let toolCallIndex = 0;
  const emittedFunctionCallIds = /* @__PURE__ */ new Set();
  const emittedFunctionResponseIds = /* @__PURE__ */ new Set();
  const accumulatedSplitMedia = [];
  for (const part of parts) {
    if (typeof part === "string") {
      contentParts.push({ type: "text", text: part });
      continue;
    }
    if ("text" in part && "thought" in part && part.thought) {
      if (role === "assistant" && part.text) {
        reasoningParts.push(part.text);
      }
    }
    if ("text" in part && part.text && !("thought" in part && part.thought)) {
      contentParts.push({ type: "text", text: part.text });
    }
    const mediaPart = createMediaContentPart(part, requestContext);
    if (mediaPart && role === "user") {
      contentParts.push(mediaPart);
    }
    if ("functionCall" in part && part.functionCall && role === "assistant") {
      const callId = part.functionCall.id;
      if (callId) {
        if (emittedFunctionCallIds.has(callId)) {
          debugLogger6.debug(
            `Dropping duplicate functionCall id=${callId} while converting content`
          );
          continue;
        }
        emittedFunctionCallIds.add(callId);
      }
      toolCalls.push({
        id: callId || `call_${toolCallIndex}`,
        type: "function",
        function: {
          name: part.functionCall.name || "",
          arguments: JSON.stringify(part.functionCall.args || {})
        }
      });
      toolCallIndex += 1;
    }
    if (part.functionResponse && role === "user") {
      const responseId = part.functionResponse.id;
      if (responseId) {
        if (emittedFunctionResponseIds.has(responseId)) {
          continue;
        }
        emittedFunctionResponseIds.add(responseId);
      }
      const toolMessage = createToolMessage(
        part.functionResponse,
        requestContext
      );
      if (toolMessage) {
        if (requestContext.splitToolMedia && Array.isArray(toolMessage.content)) {
          const mediaParts = [];
          const textParts = [];
          for (const cp of toolMessage.content) {
            if (cp && (cp.type === "image_url" || cp.type === "input_audio" || cp.type === "video_url" || cp.type === "file")) {
              mediaParts.push(cp);
            } else if (cp && cp.type === "text") {
              textParts.push(cp);
            }
          }
          if (mediaParts.length > 0) {
            const textOnly = textParts.map((p) => p.text).join("\n");
            toolMessage.content = textOnly || "[media attached in following user message]";
            accumulatedSplitMedia.push(...mediaParts);
          }
        }
        if (requestContext.toolResultContentFormat === "string" && Array.isArray(toolMessage.content)) {
          const toolContent = toolMessage.content;
          if (toolContent.every(
            (cp) => cp?.type === "text"
          )) {
            toolMessage.content = toolContent.map((cp) => cp.text).join("\n");
          }
        }
        messages.push(toolMessage);
      }
    }
  }
  if (accumulatedSplitMedia.length > 0) {
    messages.push({
      role: "user",
      content: [
        {
          type: "text",
          text: SPLIT_TOOL_MEDIA_TEXT
        },
        ...accumulatedSplitMedia
      ]
    });
  }
  if (role === "assistant") {
    if (contentParts.length === 0 && toolCalls.length === 0 && reasoningParts.length === 0) {
      return;
    }
    const assistantTextContent = contentParts.filter(
      (part) => part.type === "text"
    ).map((part) => part.text).join("");
    const assistantMessage = {
      role: "assistant",
      // When there is reasoning content but no text, use "" instead of null.
      // Some OpenAI-compatible providers (e.g. Ollama) reject content: null
      // when reasoning_content is present, returning HTTP 400.
      // For tool-call-only messages we keep null to stay spec-compliant.
      content: assistantTextContent || (reasoningParts.length > 0 ? "" : null)
    };
    if (toolCalls.length > 0) {
      assistantMessage.tool_calls = toolCalls;
    }
    const reasoningContent = reasoningParts.join("");
    if (reasoningContent) {
      assistantMessage.reasoning_content = reasoningContent;
    }
    messages.push(assistantMessage);
    return;
  }
  if (contentParts.length > 0) {
    messages.push({
      role: "user",
      content: contentParts
    });
  }
}
__name(processContent, "processContent");
function extractFunctionResponseContent(response) {
  if (response === null || response === void 0) {
    return "";
  }
  if (typeof response === "string") {
    return response;
  }
  if (typeof response === "object") {
    const responseObject = response;
    const output = responseObject["output"];
    if (typeof output === "string") {
      return output;
    }
    const error = responseObject["error"];
    if (typeof error === "string") {
      return error;
    }
  }
  try {
    const serialized = JSON.stringify(response);
    return serialized ?? String(response);
  } catch {
    return String(response);
  }
}
__name(extractFunctionResponseContent, "extractFunctionResponseContent");
function createToolMessage(response, requestContext) {
  const textContent = extractFunctionResponseContent(response.response);
  const contentParts = [];
  if (textContent) {
    contentParts.push({ type: "text", text: textContent });
  }
  for (const part of response.parts || []) {
    if ("text" in part && typeof part.text === "string") {
      if (part.text.length > 0) {
        contentParts.push({ type: "text", text: part.text });
      }
      continue;
    }
    const mediaPart = createMediaContentPart(part, requestContext);
    if (mediaPart) {
      contentParts.push(mediaPart);
    }
  }
  if (contentParts.length === 0) {
    return {
      role: "tool",
      tool_call_id: response.id || "",
      content: ""
    };
  }
  return {
    role: "tool",
    tool_call_id: response.id || "",
    content: contentParts
  };
}
__name(createToolMessage, "createToolMessage");
function createMediaContentPart(part, requestContext) {
  const { modalities } = requestContext;
  if (part.inlineData?.mimeType && part.inlineData?.data) {
    const mimeType = part.inlineData.mimeType;
    const mediaType = getMediaType(mimeType);
    const displayName = part.inlineData.displayName || mimeType;
    if (mediaType === "image") {
      if (!modalities.image) {
        return unsupportedModalityPlaceholder(
          "image",
          displayName,
          requestContext
        );
      }
      const dataUrl = `data:${mimeType};base64,${part.inlineData.data}`;
      return {
        type: "image_url",
        image_url: { url: dataUrl }
      };
    }
    if (mimeType === "application/pdf") {
      if (!modalities.pdf) {
        return unsupportedModalityPlaceholder(
          "pdf",
          displayName,
          requestContext
        );
      }
      const filename = part.inlineData.displayName || "document.pdf";
      return {
        type: "file",
        file: {
          filename,
          file_data: `data:${mimeType};base64,${part.inlineData.data}`
        }
      };
    }
    if (mediaType === "audio") {
      if (!modalities.audio) {
        return unsupportedModalityPlaceholder(
          "audio",
          displayName,
          requestContext
        );
      }
      const format = getAudioFormat(mimeType);
      if (format) {
        return {
          type: "input_audio",
          input_audio: {
            data: `data:${mimeType};base64,${part.inlineData.data}`,
            format
          }
        };
      }
    }
    if (mediaType === "video") {
      if (!modalities.video) {
        return unsupportedModalityPlaceholder(
          "video",
          displayName,
          requestContext
        );
      }
      return {
        type: "video_url",
        video_url: {
          url: `data:${mimeType};base64,${part.inlineData.data}`
        }
      };
    }
    return {
      type: "text",
      text: `Unsupported inline media type: ${mimeType} (${displayName}).`
    };
  }
  if (part.fileData?.mimeType && part.fileData?.fileUri) {
    const filename = part.fileData.displayName || "file";
    const fileUri = part.fileData.fileUri;
    const mimeType = part.fileData.mimeType;
    const mediaType = getMediaType(mimeType);
    if (mediaType === "image") {
      if (!modalities.image) {
        return unsupportedModalityPlaceholder(
          "image",
          filename,
          requestContext
        );
      }
      return {
        type: "image_url",
        image_url: { url: fileUri }
      };
    }
    if (mimeType === "application/pdf") {
      if (!modalities.pdf) {
        return unsupportedModalityPlaceholder("pdf", filename, requestContext);
      }
      return {
        type: "file",
        file: {
          filename,
          file_data: fileUri
        }
      };
    }
    if (mediaType === "video") {
      if (!modalities.video) {
        return unsupportedModalityPlaceholder(
          "video",
          filename,
          requestContext
        );
      }
      return {
        type: "video_url",
        video_url: {
          url: fileUri
        }
      };
    }
    const displayNameStr = part.fileData.displayName ? ` (${part.fileData.displayName})` : "";
    return {
      type: "text",
      text: `Unsupported file media type: ${mimeType}${displayNameStr}.`
    };
  }
  return null;
}
__name(createMediaContentPart, "createMediaContentPart");
function unsupportedModalityPlaceholder(modality, displayName, requestContext) {
  debugLogger6.warn(
    `Model '${requestContext.model}' does not support ${modality} input. Replacing with text placeholder: ${displayName}`
  );
  let hint;
  if (modality === "pdf") {
    hint = "This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:\n/extensions install https://github.com/anthropics/skills:document-skills";
  } else {
    hint = `This model does not support ${modality} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`;
  }
  return {
    type: "text",
    text: `[Unsupported ${modality} file: "${displayName}". ${hint}]`
  };
}
__name(unsupportedModalityPlaceholder, "unsupportedModalityPlaceholder");
function getMediaType(mimeType) {
  if (mimeType.startsWith("image/")) return "image";
  if (mimeType.startsWith("audio/")) return "audio";
  if (mimeType.startsWith("video/")) return "video";
  return "file";
}
__name(getMediaType, "getMediaType");
function getAudioFormat(mimeType) {
  if (mimeType.includes("wav")) return "wav";
  if (mimeType.includes("mp3") || mimeType.includes("mpeg")) return "mp3";
  return null;
}
__name(getAudioFormat, "getAudioFormat");
function isContentObject(content) {
  return typeof content === "object" && content !== null && "role" in content && "parts" in content && Array.isArray(content["parts"]);
}
__name(isContentObject, "isContentObject");
function extractTextFromContentUnion(contentUnion) {
  if (typeof contentUnion === "string") {
    return contentUnion;
  }
  if (Array.isArray(contentUnion)) {
    return contentUnion.map((item) => extractTextFromContentUnion(item)).filter(Boolean).join("\n");
  }
  if (typeof contentUnion === "object" && contentUnion !== null) {
    if ("parts" in contentUnion) {
      const content = contentUnion;
      return content.parts?.map((part) => {
        if (typeof part === "string") return part;
        if ("text" in part) return part.text || "";
        return "";
      }).filter(Boolean).join("\n") || "";
    }
  }
  return "";
}
__name(extractTextFromContentUnion, "extractTextFromContentUnion");
function convertOpenAITextToParts(text, requestContext, final = true) {
  if (!requestContext.responseParsingOptions?.taggedThinkingTags) {
    return text ? [{ text }] : [];
  }
  if (requestContext.taggedThinkingParser) {
    return requestContext.taggedThinkingParser.parse(text, final);
  }
  return parseTaggedThinkingText(text);
}
__name(convertOpenAITextToParts, "convertOpenAITextToParts");
function convertOpenAIResponseToGemini(openaiResponse, requestContext) {
  const choice = openaiResponse.choices?.[0];
  const response = new GenerateContentResponse();
  if (choice) {
    const parts = [];
    if (!requestContext.responseParsingOptions?.taggedThinkingTags) {
      const reasoningText = choice.message.reasoning_content ?? choice.message.reasoning;
      if (reasoningText) {
        parts.push({ text: reasoningText, thought: true });
      }
    }
    if (choice.message.content) {
      parts.push(
        ...convertOpenAITextToParts(choice.message.content, requestContext)
      );
    }
    if (choice.message.tool_calls) {
      for (const toolCall of choice.message.tool_calls) {
        if (toolCall.function) {
          let args = {};
          if (toolCall.function.arguments) {
            args = safeJsonParse(toolCall.function.arguments, {});
          }
          parts.push({
            functionCall: {
              id: toolCall.id,
              name: toolCall.function.name,
              args
            }
          });
        }
      }
    }
    response.candidates = [
      {
        content: {
          parts,
          role: "model"
        },
        finishReason: mapOpenAIFinishReasonToGemini(
          choice.finish_reason || "stop"
        ),
        index: 0,
        safetyRatings: []
      }
    ];
  } else {
    response.candidates = [];
  }
  response.responseId = openaiResponse.id;
  response.createTime = openaiResponse.created ? openaiResponse.created.toString() : (/* @__PURE__ */ new Date()).getTime().toString();
  response.modelVersion = requestContext.model;
  response.promptFeedback = { safetyRatings: [] };
  if (openaiResponse.usage) {
    const usage = openaiResponse.usage;
    const promptTokens = usage.prompt_tokens || 0;
    const completionTokens = usage.completion_tokens || 0;
    const totalTokens = usage.total_tokens || 0;
    const extendedUsage = usage;
    const cachedTokens = usage.prompt_tokens_details?.cached_tokens ?? extendedUsage.cached_tokens ?? 0;
    const thinkingTokens = usage.completion_tokens_details?.reasoning_tokens || 0;
    let finalPromptTokens = promptTokens;
    let finalCompletionTokens = completionTokens;
    if (totalTokens > 0 && promptTokens === 0 && completionTokens === 0) {
      finalPromptTokens = Math.round(totalTokens * 0.7);
      finalCompletionTokens = totalTokens - finalPromptTokens;
    }
    response.usageMetadata = {
      promptTokenCount: finalPromptTokens,
      candidatesTokenCount: finalCompletionTokens,
      totalTokenCount: totalTokens,
      cachedContentTokenCount: cachedTokens,
      thoughtsTokenCount: thinkingTokens
    };
  }
  return response;
}
__name(convertOpenAIResponseToGemini, "convertOpenAIResponseToGemini");
function convertOpenAIChunkToGemini(chunk, requestContext) {
  const choice = chunk.choices?.[0];
  const response = new GenerateContentResponse();
  const toolCallParser = requestContext.toolCallParser;
  if (!toolCallParser) {
    throw new Error(
      "convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start."
    );
  }
  if (choice) {
    const parts = [];
    if (!requestContext.responseParsingOptions?.taggedThinkingTags) {
      const reasoningText = choice.delta?.reasoning_content ?? choice.delta?.reasoning;
      if (reasoningText) {
        const normalizedReasoningText = normalizeStreamingTextDelta(
          reasoningText,
          requestContext.reasoningDeltaState ??= {
            emittedText: "",
            emittedLength: 0,
            cumulativeMode: false
          }
        );
        if (normalizedReasoningText) {
          parts.push({ text: normalizedReasoningText, thought: true });
        }
      }
    }
    if (typeof choice.delta?.content === "string") {
      const normalizedContent = normalizeStreamingTextDelta(
        choice.delta.content,
        requestContext.textDeltaState ??= {
          emittedText: "",
          emittedLength: 0,
          cumulativeMode: false
        }
      );
      if (normalizedContent || choice.finish_reason) {
        parts.push(
          ...convertOpenAITextToParts(
            normalizedContent,
            requestContext,
            Boolean(choice.finish_reason)
          )
        );
      }
    } else if (choice.finish_reason) {
      parts.push(...convertOpenAITextToParts("", requestContext, true));
    }
    if (choice.delta?.tool_calls) {
      for (const toolCall of choice.delta.tool_calls) {
        const index = toolCall.index ?? 0;
        if (toolCall.function?.arguments) {
          toolCallParser.addChunk(
            index,
            toolCall.function.arguments,
            toolCall.id,
            toolCall.function.name
          );
        } else {
          toolCallParser.addChunk(
            index,
            "",
            // Empty chunk for metadata-only updates
            toolCall.id,
            toolCall.function?.name
          );
        }
      }
    }
    let toolCallsTruncated = false;
    if (choice.finish_reason) {
      toolCallsTruncated = toolCallParser.hasIncompleteToolCalls();
      const completedToolCalls = toolCallParser.getCompletedToolCalls();
      for (const toolCall of completedToolCalls) {
        if (toolCall.name) {
          parts.push({
            functionCall: {
              id: toolCall.id || `call_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
              name: toolCall.name,
              args: toolCall.args
            }
          });
        }
      }
    }
    const effectiveFinishReason = toolCallsTruncated && choice.finish_reason !== "length" ? "length" : choice.finish_reason;
    const candidate = {
      content: {
        parts,
        role: "model"
      },
      index: 0,
      safetyRatings: []
    };
    if (effectiveFinishReason) {
      candidate.finishReason = mapOpenAIFinishReasonToGemini(
        effectiveFinishReason
      );
    }
    response.candidates = [candidate];
  } else {
    response.candidates = [];
  }
  response.responseId = chunk.id;
  response.createTime = chunk.created ? chunk.created.toString() : (/* @__PURE__ */ new Date()).getTime().toString();
  response.modelVersion = requestContext.model;
  response.promptFeedback = { safetyRatings: [] };
  if (chunk.usage) {
    const usage = chunk.usage;
    const promptTokens = usage.prompt_tokens || 0;
    const completionTokens = usage.completion_tokens || 0;
    const totalTokens = usage.total_tokens || 0;
    const thinkingTokens = usage.completion_tokens_details?.reasoning_tokens || 0;
    const extendedUsage = usage;
    const cachedTokens = usage.prompt_tokens_details?.cached_tokens ?? extendedUsage.cached_tokens ?? 0;
    let finalPromptTokens = promptTokens;
    let finalCompletionTokens = completionTokens;
    if (totalTokens > 0 && promptTokens === 0 && completionTokens === 0) {
      finalPromptTokens = Math.round(totalTokens * 0.7);
      finalCompletionTokens = totalTokens - finalPromptTokens;
    }
    response.usageMetadata = {
      promptTokenCount: finalPromptTokens,
      candidatesTokenCount: finalCompletionTokens,
      thoughtsTokenCount: thinkingTokens,
      totalTokenCount: totalTokens,
      cachedContentTokenCount: cachedTokens
    };
  }
  return response;
}
__name(convertOpenAIChunkToGemini, "convertOpenAIChunkToGemini");
function mapOpenAIFinishReasonToGemini(openaiReason) {
  if (!openaiReason) return FinishReason.FINISH_REASON_UNSPECIFIED;
  const mapping = {
    stop: FinishReason.STOP,
    length: FinishReason.MAX_TOKENS,
    content_filter: FinishReason.SAFETY,
    function_call: FinishReason.STOP,
    tool_calls: FinishReason.STOP
  };
  return mapping[openaiReason] || FinishReason.FINISH_REASON_UNSPECIFIED;
}
__name(mapOpenAIFinishReasonToGemini, "mapOpenAIFinishReasonToGemini");
function mapGeminiFinishReasonToOpenAI(geminiReason) {
  if (!geminiReason) {
    return "stop";
  }
  switch (geminiReason) {
    case FinishReason.STOP:
      return "stop";
    case FinishReason.MAX_TOKENS:
      return "length";
    case FinishReason.SAFETY:
    case FinishReason.RECITATION:
    case FinishReason.BLOCKLIST:
    case FinishReason.PROHIBITED_CONTENT:
    case FinishReason.SPII:
    case FinishReason.IMAGE_SAFETY:
    case FinishReason.IMAGE_RECITATION:
    case FinishReason.IMAGE_PROHIBITED_CONTENT:
    case FinishReason.IMAGE_OTHER:
      return "content_filter";
    case FinishReason.NO_IMAGE:
      return "stop";
    default:
      return "stop";
  }
}
__name(mapGeminiFinishReasonToOpenAI, "mapGeminiFinishReasonToOpenAI");
function hasToolCalls(message) {
  return message.role === "assistant" && "tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0;
}
__name(hasToolCalls, "hasToolCalls");
function isSplitToolMediaMessage(message) {
  if (message.role !== "user" || !("content" in message) || !Array.isArray(message.content)) {
    return false;
  }
  const firstPart = message.content[0];
  return firstPart?.type === "text" && firstPart.text === SPLIT_TOOL_MEDIA_TEXT;
}
__name(isSplitToolMediaMessage, "isSplitToolMediaMessage");
function cleanOrphanedToolCalls(messages) {
  const cleaned = [];
  const validToolCallsByAssistant = /* @__PURE__ */ new Map();
  const validToolResponseIndexesByAssistant = /* @__PURE__ */ new Map();
  const splitMediaIndexesByAssistant = /* @__PURE__ */ new Map();
  const emittedWithAssistant = /* @__PURE__ */ new Set();
  const survivingToolCallIds = /* @__PURE__ */ new Set();
  for (let index = 0; index < messages.length; index += 1) {
    const message = messages[index];
    if (hasToolCalls(message)) {
      const candidateToolCalls = [];
      const candidateToolCallIds = /* @__PURE__ */ new Set();
      for (const toolCall of message.tool_calls) {
        const id = toolCall.id;
        if (!id || survivingToolCallIds.has(id)) {
          continue;
        }
        if (candidateToolCallIds.has(id)) {
          continue;
        }
        candidateToolCallIds.add(id);
        candidateToolCalls.push(toolCall);
      }
      const adjacentToolResponseIds = /* @__PURE__ */ new Set();
      const toolResponseIndexes = [];
      const splitMediaIndexes = [];
      let lastToolResponseMatchesAssistant = false;
      for (let nextIndex = index + 1; nextIndex < messages.length; nextIndex += 1) {
        const nextMessage = messages[nextIndex];
        if (nextMessage.role === "tool" && "tool_call_id" in nextMessage) {
          if (!nextMessage.tool_call_id) {
            lastToolResponseMatchesAssistant = false;
            continue;
          }
          if (candidateToolCallIds.has(nextMessage.tool_call_id) && !adjacentToolResponseIds.has(nextMessage.tool_call_id)) {
            adjacentToolResponseIds.add(nextMessage.tool_call_id);
            toolResponseIndexes.push(nextIndex);
            lastToolResponseMatchesAssistant = true;
          } else {
            lastToolResponseMatchesAssistant = false;
          }
          continue;
        }
        if (isSplitToolMediaMessage(nextMessage)) {
          if (lastToolResponseMatchesAssistant) {
            splitMediaIndexes.push(nextIndex);
          }
          continue;
        }
        if (nextMessage.role === "assistant" && !hasToolCalls(nextMessage)) {
          continue;
        }
        break;
      }
      const validToolCalls = candidateToolCalls.filter(
        (toolCall) => adjacentToolResponseIds.has(toolCall.id)
      );
      for (const toolCall of validToolCalls) {
        survivingToolCallIds.add(toolCall.id);
      }
      validToolCallsByAssistant.set(index, validToolCalls);
      validToolResponseIndexesByAssistant.set(index, toolResponseIndexes);
      splitMediaIndexesByAssistant.set(index, splitMediaIndexes);
    }
  }
  for (let index = 0; index < messages.length; index += 1) {
    if (emittedWithAssistant.has(index)) {
      continue;
    }
    const message = messages[index];
    if (hasToolCalls(message)) {
      const reasoningContent = message.reasoning_content;
      const validToolCalls = validToolCallsByAssistant.get(index) ?? [];
      if (validToolCalls.length > 0) {
        const cleanedMessage = { ...message };
        cleanedMessage.tool_calls = validToolCalls;
        cleaned.push(cleanedMessage);
        for (const toolResponseIndex of validToolResponseIndexesByAssistant.get(
          index
        ) ?? []) {
          const toolResponse = messages[toolResponseIndex];
          if (toolResponse) {
            cleaned.push(toolResponse);
            emittedWithAssistant.add(toolResponseIndex);
          }
        }
        for (const splitMediaIndex of splitMediaIndexesByAssistant.get(index) ?? []) {
          const splitMediaMessage = messages[splitMediaIndex];
          if (splitMediaMessage) {
            cleaned.push(splitMediaMessage);
            emittedWithAssistant.add(splitMediaIndex);
          }
        }
      } else if (typeof message.content === "string" && message.content.trim() || reasoningContent) {
        const cleanedMessage = { ...message };
        delete cleanedMessage.tool_calls;
        cleaned.push(cleanedMessage);
      } else {
        debugLogger6.debug(
          `cleanOrphanedToolCalls: dropping assistant with ${message.tool_calls.length} orphaned tool call(s) and no text/reasoning content`
        );
      }
    } else if (message.role === "tool" && "tool_call_id" in message) {
      debugLogger6.debug(
        `cleanOrphanedToolCalls: dropping orphaned tool response ${message.tool_call_id || "<empty>"}`
      );
    } else if (isSplitToolMediaMessage(message)) {
      debugLogger6.debug(
        "cleanOrphanedToolCalls: dropping orphaned split tool media message"
      );
    } else {
      cleaned.push(message);
    }
  }
  return cleaned;
}
__name(cleanOrphanedToolCalls, "cleanOrphanedToolCalls");
function mergeConsecutiveAssistantMessages(messages) {
  const merged = [];
  for (const message of messages) {
    if (message.role === "assistant" && merged.length > 0) {
      const lastMessage = merged[merged.length - 1];
      if (lastMessage.role === "assistant") {
        const lastToolCalls = "tool_calls" in lastMessage ? lastMessage.tool_calls || [] : [];
        const currentToolCalls = "tool_calls" in message ? message.tool_calls || [] : [];
        const lastContent = lastMessage.content;
        const currentContent = message.content;
        const useArrayFormat = Array.isArray(lastContent) || Array.isArray(currentContent);
        let combinedContent;
        if (useArrayFormat) {
          const lastParts = Array.isArray(lastContent) ? lastContent : typeof lastContent === "string" && lastContent ? [{ type: "text", text: lastContent }] : [];
          const currentParts = Array.isArray(currentContent) ? currentContent : typeof currentContent === "string" && currentContent ? [{ type: "text", text: currentContent }] : [];
          combinedContent = [
            ...lastParts,
            ...currentParts
          ];
        } else {
          const lastText = typeof lastContent === "string" ? lastContent : "";
          const currentText = typeof currentContent === "string" ? currentContent : "";
          const mergedText = [lastText, currentText].filter(Boolean).join("");
          combinedContent = mergedText || null;
        }
        const combinedToolCalls = [...lastToolCalls, ...currentToolCalls];
        lastMessage.content = combinedContent || null;
        if (combinedToolCalls.length > 0) {
          lastMessage.tool_calls = combinedToolCalls;
        }
        const lastReasoning = lastMessage.reasoning_content;
        const currentReasoning = message.reasoning_content;
        const combinedReasoning = [lastReasoning, currentReasoning].filter(Boolean).join("");
        if (combinedReasoning) {
          lastMessage.reasoning_content = combinedReasoning;
        }
        continue;
      }
    }
    merged.push(message);
  }
  return merged;
}
__name(mergeConsecutiveAssistantMessages, "mergeConsecutiveAssistantMessages");
var OpenAIContentConverter = {
  convertGeminiToolParametersToOpenAI,
  convertGeminiToolsToOpenAI,
  convertGeminiRequestToOpenAI,
  convertGeminiResponseToOpenAI,
  convertOpenAIResponseToGemini,
  convertOpenAIChunkToGemini
};

// packages/core/src/core/openaiContentGenerator/requestCaptureContext.ts
init_esbuild_shims();
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
var openaiRequestCaptureContext = new AsyncLocalStorage2();

// packages/core/src/utils/openaiLogger.ts
init_esbuild_shims();
import * as path5 from "node:path";
import { promises as fs4 } from "node:fs";

// node_modules/uuid/dist/esm-node/index.js
init_esbuild_shims();

// node_modules/uuid/dist/esm-node/rng.js
init_esbuild_shims();
import crypto3 from "crypto";
var rnds8Pool = new Uint8Array(256);
var poolPtr = rnds8Pool.length;
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    crypto3.randomFillSync(rnds8Pool);
    poolPtr = 0;
  }
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
__name(rng, "rng");

// node_modules/uuid/dist/esm-node/stringify.js
init_esbuild_shims();
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
  byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
  return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
__name(unsafeStringify, "unsafeStringify");

// node_modules/uuid/dist/esm-node/v4.js
init_esbuild_shims();

// node_modules/uuid/dist/esm-node/native.js
init_esbuild_shims();
import crypto4 from "crypto";
var native_default = {
  randomUUID: crypto4.randomUUID
};

// node_modules/uuid/dist/esm-node/v4.js
function v4(options, buf, offset) {
  if (native_default.randomUUID && !buf && !options) {
    return native_default.randomUUID();
  }
  options = options || {};
  const rnds = options.random || (options.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
__name(v4, "v4");
var v4_default = v4;

// packages/core/src/utils/openaiLogger.ts
import * as os2 from "os";
var debugLogger7 = createDebugLogger("OPENAI_LOGGER");
var MAIN_SESSION_PROMPT_ID_DELIMITER = "########";
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function resolveOpenAILogDir(customLogDir, cwd) {
  const baseCwd = cwd || process.cwd();
  if (!customLogDir) {
    return path5.join(baseCwd, "logs", "openai");
  }
  let resolvedPath = customLogDir;
  if (customLogDir === "~" || customLogDir.startsWith("~/")) {
    resolvedPath = path5.join(os2.homedir(), customLogDir.slice(1));
  } else if (!path5.isAbsolute(customLogDir)) {
    resolvedPath = path5.resolve(baseCwd, customLogDir);
  }
  return path5.normalize(resolvedPath);
}
__name(resolveOpenAILogDir, "resolveOpenAILogDir");
function sanitizeDiagnosticSuffix(suffix) {
  if (!suffix) return void 0;
  const sanitized = suffix.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
  return sanitized || void 0;
}
__name(sanitizeDiagnosticSuffix, "sanitizeDiagnosticSuffix");
function extractSubagentSuffix(promptId) {
  const parts = promptId.split("#");
  if (parts.length !== 3) return void 0;
  const [, subagentId, turn] = parts;
  if (!subagentId || !turn || !/^\d+$/.test(turn)) {
    return void 0;
  }
  return `subagent-${subagentId}`;
}
__name(extractSubagentSuffix, "extractSubagentSuffix");
function promptIdSuffixForFilename(promptId) {
  if (!promptId) return void 0;
  if (isInternalPromptId(promptId)) {
    return sanitizeDiagnosticSuffix(promptId);
  }
  return sanitizeDiagnosticSuffix(extractSubagentSuffix(promptId));
}
__name(promptIdSuffixForFilename, "promptIdSuffixForFilename");
function sessionIdFromPromptId(promptId) {
  if (!promptId) return void 0;
  const mainSessionDelimiterIndex = promptId.indexOf(
    MAIN_SESSION_PROMPT_ID_DELIMITER
  );
  if (mainSessionDelimiterIndex > 0) {
    return promptId.slice(0, mainSessionDelimiterIndex);
  }
  if (UUID_PATTERN.test(promptId)) {
    return promptId;
  }
  const parts = promptId.split("#");
  if (parts.length >= 3 && parts[0]) {
    return parts[0];
  }
  return void 0;
}
__name(sessionIdFromPromptId, "sessionIdFromPromptId");
function contextForPromptId(promptId) {
  const trimmedPromptId = promptId?.trim();
  const sessionId = sessionIdFromPromptId(trimmedPromptId);
  if (!trimmedPromptId && !sessionId) {
    return null;
  }
  return {
    ...trimmedPromptId ? { promptId: trimmedPromptId } : {},
    ...sessionId ? { sessionId } : {}
  };
}
__name(contextForPromptId, "contextForPromptId");
var OpenAILogger = class {
  static {
    __name(this, "OpenAILogger");
  }
  logDir;
  initialized = false;
  /**
   * Creates a new OpenAI logger
   * @param customLogDir Optional custom log directory path (supports relative paths, absolute paths, and ~ expansion)
   * @param cwd Optional working directory for resolving relative paths. Defaults to process.cwd().
   *            In ACP mode, process.cwd() may be '/' (filesystem root), so callers should
   *            pass the project working directory from Config.getWorkingDir().
   */
  constructor(customLogDir, cwd) {
    this.logDir = resolveOpenAILogDir(customLogDir, cwd);
  }
  /**
   * Initialize the logger by creating the log directory if it doesn't exist
   */
  async initialize() {
    if (this.initialized) return;
    try {
      await fs4.mkdir(this.logDir, { recursive: true });
      this.initialized = true;
    } catch (error) {
      debugLogger7.error("Failed to initialize OpenAI logger:", error);
      throw new Error(`Failed to initialize OpenAI logger: ${error}`);
    }
  }
  /**
   * Logs an OpenAI API request and its response
   * @param request The request sent to OpenAI
   * @param response The response received from OpenAI
   * @param error Optional error if the request failed
   * @param promptId Optional prompt id; internal and subagent prompt ids are
   *                 appended to the filename after timestamp and id.
   * @returns The file path where the log was written
   */
  async logInteraction(request4, response, error, promptId) {
    if (!this.initialized) {
      await this.initialize();
    }
    const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
    const id = v4_default().slice(0, 8);
    const promptIdSuffix = promptIdSuffixForFilename(promptId);
    const filename = promptIdSuffix ? `openai-${timestamp}-${id}-${promptIdSuffix}.json` : `openai-${timestamp}-${id}.json`;
    const filePath = path5.join(this.logDir, filename);
    const logData = {
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      request: request4,
      response: response || null,
      error: error ? {
        message: error.message,
        stack: error.stack
      } : null,
      context: contextForPromptId(promptId),
      system: {
        hostname: os2.hostname(),
        platform: os2.platform(),
        release: os2.release(),
        nodeVersion: process.version
      }
    };
    try {
      await fs4.writeFile(filePath, JSON.stringify(logData, null, 2), "utf-8");
      return filePath;
    } catch (writeError) {
      debugLogger7.error("Failed to write OpenAI log file:", writeError);
      throw new Error(`Failed to write OpenAI log file: ${writeError}`);
    }
  }
  /**
   * Get all logged interactions
   * @param limit Optional limit on the number of log files to return (sorted by most recent first)
   * @returns Array of log file paths
   */
  async getLogFiles(limit) {
    if (!this.initialized) {
      await this.initialize();
    }
    try {
      const files = await fs4.readdir(this.logDir);
      const logFiles = files.filter((file) => file.startsWith("openai-") && file.endsWith(".json")).map((file) => path5.join(this.logDir, file)).sort().reverse();
      return limit === void 0 ? logFiles : logFiles.slice(0, limit);
    } catch (error) {
      if (error.code === "ENOENT") {
        return [];
      }
      debugLogger7.error("Failed to read OpenAI log directory:", error);
      return [];
    }
  }
  /**
   * Read a specific log file
   * @param filePath The path to the log file
   * @returns The log file content
   */
  async readLogFile(filePath) {
    try {
      const content = await fs4.readFile(filePath, "utf-8");
      return JSON.parse(content);
    } catch (error) {
      debugLogger7.error(`Failed to read log file ${filePath}:`, error);
      throw new Error(`Failed to read log file: ${error}`);
    }
  }
};
var openaiLogger = new OpenAILogger();

// packages/core/src/telemetry/index.ts
init_esbuild_shims();

// packages/core/src/telemetry/sdk.ts
init_esbuild_shims();
init_esm();
var import_exporter_trace_otlp_grpc = __toESM(require_src11(), 1);
var import_exporter_logs_otlp_grpc = __toESM(require_src12(), 1);
var import_exporter_metrics_otlp_grpc = __toESM(require_src14(), 1);
var import_exporter_trace_otlp_http = __toESM(require_src15(), 1);
var import_exporter_logs_otlp_http = __toESM(require_src16(), 1);
var import_exporter_metrics_otlp_http = __toESM(require_src13(), 1);
init_esm3();
var import_sdk_node = __toESM(require_src29(), 1);
init_esm2();
var import_resources2 = __toESM(require_src8(), 1);
var import_sdk_trace_node = __toESM(require_src20(), 1);
var import_sdk_logs = __toESM(require_src17(), 1);
var import_sdk_metrics2 = __toESM(require_src9(), 1);
var import_instrumentation_http = __toESM(require_src30(), 1);
var import_instrumentation_undici = __toESM(require_src31(), 1);

// packages/core/src/telemetry/file-exporters.ts
init_esbuild_shims();
var import_core3 = __toESM(require_src3(), 1);
var import_sdk_metrics = __toESM(require_src9(), 1);
import * as fs5 from "node:fs";
import * as path6 from "node:path";
var FileExporter = class {
  static {
    __name(this, "FileExporter");
  }
  writeStream;
  constructor(filePath) {
    try {
      fs5.mkdirSync(path6.dirname(filePath), { recursive: true });
    } catch {
    }
    this.writeStream = fs5.createWriteStream(filePath, { flags: "a" });
    this.writeStream.on("error", () => {
    });
  }
  serialize(data) {
    return safeJsonStringify(data, 2) + "\n";
  }
  shutdown() {
    return new Promise((resolve2) => {
      this.writeStream.end(resolve2);
    });
  }
};
var FileSpanExporter = class extends FileExporter {
  static {
    __name(this, "FileSpanExporter");
  }
  export(spans, resultCallback) {
    const data = spans.map((span) => this.serialize(span)).join("");
    this.writeStream.write(data, (err) => {
      resultCallback({
        code: err ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
        error: err || void 0
      });
    });
  }
};
var FileLogExporter = class extends FileExporter {
  static {
    __name(this, "FileLogExporter");
  }
  export(logs3, resultCallback) {
    const data = logs3.map((log) => this.serialize(log)).join("");
    this.writeStream.write(data, (err) => {
      resultCallback({
        code: err ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
        error: err || void 0
      });
    });
  }
};
var FileMetricExporter = class extends FileExporter {
  static {
    __name(this, "FileMetricExporter");
  }
  export(metrics2, resultCallback) {
    const data = this.serialize(metrics2);
    this.writeStream.write(data, (err) => {
      resultCallback({
        code: err ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
        error: err || void 0
      });
    });
  }
  getPreferredAggregationTemporality() {
    return import_sdk_metrics.AggregationTemporality.CUMULATIVE;
  }
  async forceFlush() {
    return Promise.resolve();
  }
};

// packages/core/src/telemetry/log-to-span-processor.ts
init_esbuild_shims();
init_esm();
var import_resources = __toESM(require_src8(), 1);

// packages/core/src/telemetry/trace-id-utils.ts
init_esbuild_shims();
import { createHash } from "node:crypto";
function deriveTraceId(sessionId) {
  return createHash("sha256").update(sessionId).digest("hex").slice(0, 32);
}
__name(deriveTraceId, "deriveTraceId");
function randomSpanId() {
  const bytes = new Uint8Array(8);
  crypto.getRandomValues(bytes);
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
__name(randomSpanId, "randomSpanId");
function randomHexString(length) {
  const bytes = new Uint8Array(Math.ceil(length / 2));
  crypto.getRandomValues(bytes);
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("").slice(0, length);
}
__name(randomHexString, "randomHexString");

// packages/core/src/telemetry/session-tracing.ts
init_esbuild_shims();
init_esm();
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";

// packages/core/src/telemetry/detailed-span-attributes.ts
init_esbuild_shims();
import { createHash as createHash2 } from "node:crypto";
var SYSTEM_PROMPT_PREVIEW_LENGTH = 500;
var SHORT_TRUNCATION_SUFFIX = "...[TRUNCATED]";
var seenHashes = /* @__PURE__ */ new Set();
function areSensitiveSpanAttributesEnabled(config) {
  return isTelemetrySdkInitialized() && config.getTelemetryIncludeSensitiveSpanAttributes();
}
__name(areSensitiveSpanAttributesEnabled, "areSensitiveSpanAttributesEnabled");
function truncateContent(content, maxSize = DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH, originalLength = content.length) {
  if (!Number.isSafeInteger(maxSize) || maxSize < 1) {
    throw new TypeError(
      `maxSize must be a positive safe integer, got ${String(maxSize)}`
    );
  }
  if (!Number.isSafeInteger(originalLength) || originalLength < 0) {
    throw new TypeError(
      `originalLength must be a non-negative safe integer, got ${String(
        originalLength
      )}`
    );
  }
  if (originalLength < content.length) {
    throw new TypeError(
      `originalLength must be greater than or equal to content length, got ${originalLength} for content length ${content.length}`
    );
  }
  if (originalLength <= maxSize && content.length <= maxSize) {
    return { content, truncated: false };
  }
  if (originalLength > content.length && content.length <= maxSize) {
    return { content, truncated: true };
  }
  const suffix = `

[TRUNCATED - Content exceeds configured limit of ${maxSize} characters]`;
  if (suffix.length >= maxSize) {
    if (SHORT_TRUNCATION_SUFFIX.length >= maxSize) {
      return {
        content: SHORT_TRUNCATION_SUFFIX.slice(0, maxSize),
        truncated: true
      };
    }
    return {
      content: content.slice(0, maxSize - SHORT_TRUNCATION_SUFFIX.length) + SHORT_TRUNCATION_SUFFIX,
      truncated: true
    };
  }
  return {
    content: content.slice(0, maxSize - suffix.length) + suffix,
    truncated: true
  };
}
__name(truncateContent, "truncateContent");
function getMaxContentSize(config) {
  return config.getTelemetrySensitiveSpanAttributeMaxLength();
}
__name(getMaxContentSize, "getMaxContentSize");
function truncatePrefixedContent(prefix, content, maxSize) {
  const prefixedContent = `${prefix}${content}`;
  const result = truncateContent(prefixedContent, maxSize);
  return {
    ...result,
    originalLength: content.length
  };
}
__name(truncatePrefixedContent, "truncatePrefixedContent");
function shortHash(content) {
  return createHash2("sha256").update(content).digest("hex").slice(0, 12);
}
__name(shortHash, "shortHash");
function stringifyContentUnion(value) {
  if (typeof value === "string") return value;
  return safeJsonStringify(value) ?? "";
}
__name(stringifyContentUnion, "stringifyContentUnion");
function addUserPromptAttributes(config, span, promptText) {
  if (!areSensitiveSpanAttributesEnabled(config) || !promptText) return;
  const { content, truncated, originalLength } = truncatePrefixedContent(
    `[USER PROMPT]
`,
    promptText,
    getMaxContentSize(config)
  );
  span.setAttributes({
    new_context: content,
    ...truncated && {
      new_context_truncated: true,
      new_context_original_length: originalLength
    }
  });
}
__name(addUserPromptAttributes, "addUserPromptAttributes");
function addSystemPromptAttributes(config, span, systemInstruction) {
  if (!areSensitiveSpanAttributesEnabled(config) || !systemInstruction) return;
  const text = stringifyContentUnion(systemInstruction);
  if (!text) return;
  const hash = `sp_${shortHash(text)}`;
  span.setAttributes({
    system_prompt_hash: hash,
    system_prompt_preview: text.slice(0, SYSTEM_PROMPT_PREVIEW_LENGTH),
    system_prompt_length: text.length
  });
  if (!seenHashes.has(hash)) {
    seenHashes.add(hash);
    const { content, truncated } = truncateContent(
      text,
      getMaxContentSize(config)
    );
    span.setAttribute("system_prompt", content);
    if (truncated) {
      span.setAttribute("system_prompt_truncated", true);
    }
  }
}
__name(addSystemPromptAttributes, "addSystemPromptAttributes");
function addToolSchemaAttributes(config, span, tools) {
  if (!areSensitiveSpanAttributesEnabled(config) || !tools?.length) return;
  const declarations = [];
  for (const tool of tools) {
    const inner = tool["functionDeclarations"];
    if (Array.isArray(inner)) {
      declarations.push(...inner);
    } else {
      declarations.push(tool);
    }
  }
  const summary = [];
  for (const decl of declarations) {
    const declObj = decl;
    const name = typeof declObj["name"] === "string" ? declObj["name"] : "unknown_tool";
    const declJson = safeJsonStringify(decl) ?? `unstringifiable_${name}`;
    const hash = shortHash(declJson);
    summary.push({ name, hash });
    const hashKey = `tool_${hash}`;
    if (!seenHashes.has(hashKey)) {
      seenHashes.add(hashKey);
      const { content, truncated } = truncateContent(
        declJson,
        getMaxContentSize(config)
      );
      span.addEvent("tool_schema", {
        tool_name: name,
        tool_hash: hash,
        tool_definition: content,
        ...truncated && {
          tool_definition_truncated: true,
          tool_definition_original_length: declJson.length
        }
      });
    }
  }
  span.setAttributes({
    tools: safeJsonStringify(summary) ?? "[]",
    tools_count: summary.length
  });
}
__name(addToolSchemaAttributes, "addToolSchemaAttributes");
function addModelOutputAttributes(config, span, responseText, originalLength) {
  if (!areSensitiveSpanAttributesEnabled(config) || !responseText) return;
  const responseTextOriginalLength = originalLength ?? responseText.length;
  const { content, truncated } = truncateContent(
    responseText,
    getMaxContentSize(config),
    responseTextOriginalLength
  );
  span.setAttributes({
    "response.model_output": content,
    ...truncated && {
      "response.model_output_truncated": true,
      "response.model_output_original_length": responseTextOriginalLength
    }
  });
}
__name(addModelOutputAttributes, "addModelOutputAttributes");
function addToolInputAttributes(config, span, toolName, toolInput) {
  if (!areSensitiveSpanAttributesEnabled(config)) return;
  const { content, truncated, originalLength } = truncatePrefixedContent(
    `[TOOL INPUT: ${toolName}]
`,
    toolInput,
    getMaxContentSize(config)
  );
  span.setAttributes({
    tool_input: content,
    ...truncated && {
      tool_input_truncated: true,
      tool_input_original_length: originalLength
    }
  });
}
__name(addToolInputAttributes, "addToolInputAttributes");
function addToolResultAttributes(config, span, toolName, toolResult) {
  if (!areSensitiveSpanAttributesEnabled(config)) return;
  const { content, truncated, originalLength } = truncatePrefixedContent(
    `[TOOL RESULT: ${toolName}]
`,
    toolResult,
    getMaxContentSize(config)
  );
  span.setAttributes({
    tool_result: content,
    ...truncated && {
      tool_result_truncated: true,
      tool_result_original_length: originalLength
    }
  });
}
__name(addToolResultAttributes, "addToolResultAttributes");
function clearDetailedSpanState() {
  seenHashes.clear();
}
__name(clearDetailedSpanState, "clearDetailedSpanState");

// packages/core/src/telemetry/session-tracing.ts
var debugLogger8 = createDebugLogger("SESSION_TRACING");
function resolveParentContext(parent) {
  if (parent) {
    return trace.setSpan(context.active(), parent.span);
  }
  return context.active();
}
__name(resolveParentContext, "resolveParentContext");
var NOOP_SPAN = trace.wrapSpanContext({
  traceId: "0".repeat(32),
  spanId: "0".repeat(16),
  traceFlags: 0
});
var interactionContext = new AsyncLocalStorage3();
var toolContext = new AsyncLocalStorage3();
var subagentContext = new AsyncLocalStorage3();
function isInNativeSubagentSpan() {
  const ctx = subagentContext.getStore();
  return ctx !== void 0 && !ctx.ended;
}
__name(isInNativeSubagentSpan, "isInNativeSubagentSpan");
function resolveSessionId(parentCtx) {
  const fromParent = parentCtx?.attributes?.["session.id"];
  return typeof fromParent === "string" && fromParent ? fromParent : getCurrentSessionId();
}
__name(resolveSessionId, "resolveSessionId");
var activeSpans = /* @__PURE__ */ new Map();
var strongSpans = /* @__PURE__ */ new Map();
var interactionSequence = 0;
var lastInteractionCtx;
var cleanupIntervalStarted = false;
var SPAN_TTL_MS_DEFAULT = 30 * 60 * 1e3;
var SPAN_TTL_MS_LONG = 4 * 60 * 60 * 1e3;
var LONG_TTL_SUBAGENT_KINDS = /* @__PURE__ */ new Set([
  "fork",
  "background"
]);
function ttlFor(ctx) {
  if (ctx.type === "subagent") {
    const kind = ctx.attributes["qwen-code.subagent.invocation_kind"];
    if (typeof kind === "string" && LONG_TTL_SUBAGENT_KINDS.has(kind)) {
      return SPAN_TTL_MS_LONG;
    }
  }
  return SPAN_TTL_MS_DEFAULT;
}
__name(ttlFor, "ttlFor");
function sweepStaleSpans(now) {
  for (const [spanId, weakRef] of activeSpans) {
    const ctx = weakRef.deref();
    if (ctx === void 0) {
      activeSpans.delete(spanId);
      strongSpans.delete(spanId);
      continue;
    }
    if (now - ctx.startTime < ttlFor(ctx)) continue;
    if (!ctx.ended) {
      ctx.ended = true;
      const ageMs = now - ctx.startTime;
      const toolName = ctx.attributes["tool.name"];
      const callId = ctx.attributes["tool.call_id"];
      try {
        ctx.span.setAttributes({
          "qwen-code.span.ttl_expired": true,
          "qwen-code.span.duration_ms": ageMs,
          ...ctx.type === "tool.blocked_on_user" ? {
            decision: "aborted",
            source: "system"
          } : {},
          ...ctx.type === "subagent" ? {
            "qwen-code.subagent.status": "aborted",
            "qwen-code.subagent.terminate_reason": "ttl_swept",
            // Mirror the subagent-specific duration_ms key that
            // endSubagentSpan stamps so dashboards querying that
            // namespace see TTL-swept spans too (they currently
            // only get the generic qwen-code.span.duration_ms
            // above). wenshao @ #4410.
            "qwen-code.subagent.duration_ms": ageMs
          } : {}
        });
      } catch (error) {
        debugLogger8.warn(
          `Failed to stamp TTL attrs on stale span ${spanId}: ${error instanceof Error ? error.message : String(error)}`
        );
      }
      const ctxLabel = toolName && callId ? `${ctx.type} (tool.name=${toolName}, tool.call_id=${callId})` : ctx.type;
      debugLogger8.warn(
        `Stale ${ctxLabel} span ended by TTL safety net (age=${ageMs}ms, spanId=${spanId})`
      );
      try {
        ctx.span.end();
      } catch (error) {
        debugLogger8.warn(
          `Failed to end stale span ${spanId}: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
    activeSpans.delete(spanId);
    strongSpans.delete(spanId);
  }
}
__name(sweepStaleSpans, "sweepStaleSpans");
function ensureCleanupInterval() {
  if (cleanupIntervalStarted) return;
  cleanupIntervalStarted = true;
  const interval = setInterval(() => sweepStaleSpans(Date.now()), 6e4);
  if (typeof interval.unref === "function") {
    interval.unref();
  }
}
__name(ensureCleanupInterval, "ensureCleanupInterval");
function getSpanId(span) {
  return span.spanContext().spanId || "";
}
__name(getSpanId, "getSpanId");
var SPAN_ERROR_MAX_CHARS = 1024;
function truncateSpanError(s) {
  if (s.length <= SPAN_ERROR_MAX_CHARS) return s;
  let end = SPAN_ERROR_MAX_CHARS;
  const code = s.charCodeAt(end - 1);
  if (code >= 55296 && code <= 56319) end--;
  return s.slice(0, end) + "\u2026[truncated]";
}
__name(truncateSpanError, "truncateSpanError");
function getTracer() {
  return trace.getTracer(SERVICE_NAME, "1.0.0");
}
__name(getTracer, "getTracer");
function startInteractionSpan(config, options) {
  if (!isTelemetrySdkInitialized()) return;
  ensureCleanupInterval();
  interactionSequence++;
  const attributes = {
    "session.id": config.getSessionId(),
    "qwen-code.prompt_id": options.promptId,
    "qwen-code.message_type": options.messageType,
    "qwen-code.model": options.model,
    "qwen-code.approval_mode": config.getApprovalMode(),
    "interaction.sequence": interactionSequence
  };
  const span = getTracer().startSpan(
    SPAN_INTERACTION,
    { kind: SpanKind.INTERNAL, attributes },
    ROOT_CONTEXT
  );
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes,
    type: "interaction"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  lastInteractionCtx = spanContextObj;
  interactionContext.enterWith(spanContextObj);
}
__name(startInteractionSpan, "startInteractionSpan");
function endInteractionSpan(status, metadata) {
  const spanCtx = interactionContext.getStore() ?? lastInteractionCtx;
  if (!spanCtx) return;
  if (spanCtx.ended) {
    debugLogger8.debug(
      `endInteractionSpan: span ${getSpanId(spanCtx.span)} already ended (possible TTL sweep race)`
    );
    return;
  }
  spanCtx.ended = true;
  lastInteractionCtx = void 0;
  const duration = Date.now() - spanCtx.startTime;
  spanCtx.span.setAttributes({
    "interaction.duration_ms": duration,
    "qwen-code.turn_status": status
  });
  if (status === "error") {
    spanCtx.span.setStatus({
      code: SpanStatusCode.ERROR,
      message: metadata?.errorMessage ?? "unknown error"
    });
  } else {
    spanCtx.span.setStatus({ code: SpanStatusCode.OK });
  }
  spanCtx.span.end();
  const spanId = getSpanId(spanCtx.span);
  activeSpans.delete(spanId);
  strongSpans.delete(spanId);
  interactionContext.enterWith(void 0);
}
__name(endInteractionSpan, "endInteractionSpan");
async function withInteractionSpan(config, options, fn, getResultStatus) {
  if (!isTelemetrySdkInitialized()) return await fn();
  ensureCleanupInterval();
  interactionSequence++;
  const attributes = {
    "session.id": config.getSessionId(),
    "qwen-code.prompt_id": options.promptId,
    "qwen-code.message_type": options.messageType,
    "qwen-code.model": options.model,
    "qwen-code.approval_mode": config.getApprovalMode(),
    "interaction.sequence": interactionSequence
  };
  const parentContext = options.parentContext ?? ROOT_CONTEXT;
  const span = getTracer().startSpan(
    SPAN_INTERACTION,
    {
      kind: SpanKind.INTERNAL,
      attributes
    },
    parentContext
  );
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes,
    type: "interaction"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  const activeContext = trace.setSpan(parentContext, span);
  return await context.with(
    activeContext,
    async () => interactionContext.run(spanContextObj, async () => {
      let terminalStatus = "ok";
      let errorStatusSet = false;
      try {
        const result = await fn();
        terminalStatus = getResultStatus?.(result) ?? "ok";
        return result;
      } catch (error) {
        terminalStatus = "error";
        span.setStatus({
          code: SpanStatusCode.ERROR,
          message: truncateSpanError(
            error instanceof Error ? error.message : String(error)
          )
        });
        errorStatusSet = true;
        throw error;
      } finally {
        if (!spanContextObj.ended) {
          spanContextObj.ended = true;
          const duration = Date.now() - spanContextObj.startTime;
          span.setAttributes({
            "interaction.duration_ms": duration,
            "qwen-code.turn_status": terminalStatus
          });
          if (terminalStatus === "ok") {
            span.setStatus({ code: SpanStatusCode.OK });
          } else if (terminalStatus === "error" && !errorStatusSet) {
            span.setStatus({
              code: SpanStatusCode.ERROR,
              message: "interaction error"
            });
          }
          span.end();
          activeSpans.delete(spanId);
          strongSpans.delete(spanId);
        }
      }
    })
  );
}
__name(withInteractionSpan, "withInteractionSpan");
function startLLMRequestSpan(model, promptId) {
  if (!isTelemetrySdkInitialized()) {
    return NOOP_SPAN;
  }
  const parentCtx = subagentContext.getStore() ?? interactionContext.getStore();
  const ctx = resolveParentContext(parentCtx);
  const sessionId = resolveSessionId(parentCtx);
  const attributes = {
    ...sessionId ? { "session.id": sessionId } : {},
    "qwen-code.model": model,
    "qwen-code.prompt_id": promptId,
    "llm_request.context": subagentContext.getStore() ? "subagent" : interactionContext.getStore() ? "interaction" : "standalone",
    // Dual-emit OTel GenAI semantic convention (Stable). Private name
    // (qwen-code.model) remains authoritative; gen_ai.* is a compat layer
    // for spec-aware backends. See docs/design/telemetry-llm-request-timing-design.md (D8).
    "gen_ai.request.model": model
  };
  const span = getTracer().startSpan(
    SPAN_LLM_REQUEST,
    { kind: SpanKind.INTERNAL, attributes },
    ctx
  );
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes,
    type: "llm_request"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  return span;
}
__name(startLLMRequestSpan, "startLLMRequestSpan");
function endLLMRequestSpan(span, metadata) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) return;
  if (spanCtx.ended) {
    debugLogger8.debug(
      `endLLMRequestSpan: span ${spanId} already ended (possible TTL sweep race)`
    );
    return;
  }
  spanCtx.ended = true;
  try {
    const duration = metadata?.durationMs ?? Date.now() - spanCtx.startTime;
    const endAttributes = { duration_ms: duration };
    if (metadata) {
      if (metadata.inputTokens !== void 0) {
        endAttributes["input_tokens"] = metadata.inputTokens;
        endAttributes["gen_ai.usage.input_tokens"] = metadata.inputTokens;
      }
      if (metadata.outputTokens !== void 0) {
        endAttributes["output_tokens"] = metadata.outputTokens;
        endAttributes["gen_ai.usage.output_tokens"] = metadata.outputTokens;
      }
      if (metadata.cachedInputTokens !== void 0) {
        endAttributes["cached_input_tokens"] = metadata.cachedInputTokens;
        endAttributes["gen_ai.usage.cached_tokens"] = metadata.cachedInputTokens;
      }
      if (metadata.ttftMs !== void 0) {
        endAttributes["ttft_ms"] = metadata.ttftMs;
        endAttributes["gen_ai.server.time_to_first_token"] = metadata.ttftMs / 1e3;
      }
      if (metadata.requestSetupMs !== void 0) {
        endAttributes["request_setup_ms"] = metadata.requestSetupMs;
      }
      if (metadata.attempt !== void 0) {
        endAttributes["attempt"] = metadata.attempt;
      }
      if (metadata.retryTotalDelayMs !== void 0) {
        endAttributes["retry_total_delay_ms"] = metadata.retryTotalDelayMs;
      }
      if (metadata.ttftMs !== void 0) {
        const samplingMs = Math.max(0, duration - metadata.ttftMs);
        endAttributes["sampling_ms"] = samplingMs;
        if (samplingMs > 0 && metadata.outputTokens !== void 0) {
          endAttributes["output_tokens_per_second"] = Math.round(metadata.outputTokens / (samplingMs / 1e3) * 100) / 100;
        }
      }
      endAttributes["success"] = metadata.success;
      if (metadata.error !== void 0)
        endAttributes["error"] = truncateSpanError(metadata.error);
      if (metadata.responseId !== void 0) {
        endAttributes["response_id"] = metadata.responseId;
        endAttributes["gen_ai.response.id"] = metadata.responseId;
      }
      if (metadata.finishReason !== void 0) {
        endAttributes["finish_reason"] = metadata.finishReason;
        endAttributes["gen_ai.response.finish_reasons"] = [
          metadata.finishReason
        ];
      }
      if (metadata.thoughtsTokenCount !== void 0) {
        endAttributes["thoughts_token_count"] = metadata.thoughtsTokenCount;
        endAttributes["gen_ai.usage.reasoning_tokens"] = metadata.thoughtsTokenCount;
      }
      if (metadata.subagentName !== void 0) {
        endAttributes["subagent_name"] = metadata.subagentName;
      }
      if (metadata.errorType !== void 0) {
        endAttributes["error_type"] = metadata.errorType;
        endAttributes["error.type"] = metadata.errorType;
      }
      if (metadata.errorStatusCode !== void 0) {
        endAttributes["error_status_code"] = metadata.errorStatusCode;
      }
    }
    spanCtx.span.setAttributes(endAttributes);
    try {
      if (metadata?.config && metadata.success) {
        const model = String(spanCtx.attributes["qwen-code.model"] ?? "");
        if (metadata.requestSetupMs !== void 0) {
          recordApiRequestBreakdown(metadata.config, metadata.requestSetupMs, {
            model,
            phase: "request_preparation" /* REQUEST_PREPARATION */
          });
        }
        if (metadata.ttftMs !== void 0) {
          recordApiRequestBreakdown(metadata.config, metadata.ttftMs, {
            model,
            phase: "network_latency" /* NETWORK_LATENCY */
          });
        }
        const breakdownSamplingMs = metadata.ttftMs !== void 0 ? Math.max(0, duration - metadata.ttftMs) : void 0;
        if (breakdownSamplingMs !== void 0 && breakdownSamplingMs > 0) {
          recordApiRequestBreakdown(metadata.config, breakdownSamplingMs, {
            model,
            phase: "response_processing" /* RESPONSE_PROCESSING */
          });
        }
      }
    } catch (error) {
      debugLogger8.warn(
        `Failed to record API request breakdown histogram: ${error instanceof Error ? error.message : String(error)}`
      );
    }
    if (metadata === void 0 || metadata.success) {
      spanCtx.span.setStatus({ code: SpanStatusCode.OK });
    } else {
      spanCtx.span.setStatus({
        code: SpanStatusCode.ERROR,
        message: metadata.error ? truncateSpanError(metadata.error) : "unknown error"
      });
    }
  } catch (error) {
    debugLogger8.warn(
      `Failed to update LLM request span attributes/status: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  try {
    spanCtx.span.end();
  } catch (error) {
    debugLogger8.warn(
      `Failed to end LLM request span: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  activeSpans.delete(spanId);
  strongSpans.delete(spanId);
}
__name(endLLMRequestSpan, "endLLMRequestSpan");
function startToolSpan(toolName, attrs) {
  if (!isTelemetrySdkInitialized()) {
    return NOOP_SPAN;
  }
  const parentCtx = subagentContext.getStore() ?? interactionContext.getStore();
  const ctx = resolveParentContext(parentCtx);
  const sessionId = resolveSessionId(parentCtx);
  const attributes = {
    ...sessionId ? { "session.id": sessionId } : {},
    "tool.name": toolName,
    ...attrs
  };
  const span = getTracer().startSpan(
    SPAN_TOOL,
    { kind: SpanKind.INTERNAL, attributes },
    ctx
  );
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes,
    type: "tool"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  return span;
}
__name(startToolSpan, "startToolSpan");
function runInToolSpanContext(span, fn) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) return fn();
  const otelCtxWithSpan = trace.setSpan(context.active(), span);
  return toolContext.run(spanCtx, () => context.with(otelCtxWithSpan, fn));
}
__name(runInToolSpanContext, "runInToolSpanContext");
function endToolSpan(span, metadata) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) return;
  if (spanCtx.ended) {
    debugLogger8.debug(
      `endToolSpan: span ${spanId} already ended (possible TTL sweep race)`
    );
    return;
  }
  spanCtx.ended = true;
  try {
    const duration = Date.now() - spanCtx.startTime;
    const endAttributes = { duration_ms: duration };
    if (metadata) {
      if (metadata.success !== void 0)
        endAttributes["success"] = metadata.success;
      if (metadata.error !== void 0)
        endAttributes["error"] = truncateSpanError(metadata.error);
    }
    spanCtx.span.setAttributes(endAttributes);
    if (metadata) {
      if (metadata.success !== false) {
        spanCtx.span.setStatus({ code: SpanStatusCode.OK });
      } else {
        spanCtx.span.setStatus({
          code: SpanStatusCode.ERROR,
          message: metadata.error ? truncateSpanError(metadata.error) : "tool error"
        });
      }
    }
  } catch (error) {
    debugLogger8.warn(
      `Failed to update tool span attributes/status: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  try {
    spanCtx.span.end();
  } catch (error) {
    debugLogger8.warn(
      `Failed to end tool span: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  activeSpans.delete(spanId);
  strongSpans.delete(spanId);
}
__name(endToolSpan, "endToolSpan");
function startToolExecutionSpan() {
  if (!isTelemetrySdkInitialized()) {
    return NOOP_SPAN;
  }
  const parentCtx = toolContext.getStore();
  if (!parentCtx) {
    debugLogger8.warn(
      "startToolExecutionSpan called outside runInToolSpanContext \u2014 span will not be parented to tool span"
    );
  }
  const ctx = resolveParentContext(parentCtx);
  const sessionId = resolveSessionId(
    parentCtx ?? interactionContext.getStore()
  );
  const span = getTracer().startSpan(
    SPAN_TOOL_EXECUTION,
    {
      kind: SpanKind.INTERNAL,
      attributes: sessionId ? { "session.id": sessionId } : {}
    },
    ctx
  );
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes: sessionId ? { "session.id": sessionId } : {},
    type: "tool.execution"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  return span;
}
__name(startToolExecutionSpan, "startToolExecutionSpan");
function endToolExecutionSpan(span, metadata) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) return;
  if (spanCtx.ended) {
    debugLogger8.debug(
      `endToolExecutionSpan: span ${spanId} already ended (possible TTL sweep race)`
    );
    return;
  }
  spanCtx.ended = true;
  try {
    const duration = Date.now() - spanCtx.startTime;
    const endAttributes = { duration_ms: duration };
    if (metadata) {
      if (metadata.success !== void 0)
        endAttributes["success"] = metadata.success;
      if (metadata.error !== void 0)
        endAttributes["error"] = truncateSpanError(metadata.error);
    }
    spanCtx.span.setAttributes(endAttributes);
    if (metadata && !metadata.cancelled) {
      if (metadata.success !== false) {
        spanCtx.span.setStatus({ code: SpanStatusCode.OK });
      } else {
        spanCtx.span.setStatus({
          code: SpanStatusCode.ERROR,
          message: metadata.error ? truncateSpanError(metadata.error) : "tool execution error"
        });
      }
    }
  } catch (error) {
    debugLogger8.warn(
      `Failed to update tool execution span attributes/status: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  try {
    spanCtx.span.end();
  } catch (error) {
    debugLogger8.warn(
      `Failed to end tool execution span: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  activeSpans.delete(spanId);
  strongSpans.delete(spanId);
}
__name(endToolExecutionSpan, "endToolExecutionSpan");
function startToolBlockedOnUserSpan(toolSpan, attrs) {
  if (!isTelemetrySdkInitialized()) {
    return NOOP_SPAN;
  }
  ensureCleanupInterval();
  const parentSpanId = getSpanId(toolSpan);
  const parentSpanCtx = activeSpans.get(parentSpanId)?.deref();
  if (!parentSpanCtx) {
    debugLogger8.debug(
      "startToolBlockedOnUserSpan: tool span not in activeSpans (already ended?) \u2014 using resolveParentContext fallback"
    );
  }
  const ctx = parentSpanCtx ? trace.setSpan(context.active(), parentSpanCtx.span) : resolveParentContext(void 0);
  const sessionParentCtx = parentSpanCtx ?? subagentContext.getStore() ?? interactionContext.getStore() ?? void 0;
  const sessionId = resolveSessionId(sessionParentCtx);
  const attributes = {
    ...sessionId ? { "session.id": sessionId } : {}
  };
  if (attrs?.tool_name !== void 0) attributes["tool.name"] = attrs.tool_name;
  if (attrs?.call_id !== void 0) attributes["tool.call_id"] = attrs.call_id;
  const span = getTracer().startSpan(
    SPAN_TOOL_BLOCKED_ON_USER,
    { kind: SpanKind.INTERNAL, attributes },
    ctx
  );
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes,
    type: "tool.blocked_on_user"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  return span;
}
__name(startToolBlockedOnUserSpan, "startToolBlockedOnUserSpan");
function endToolBlockedOnUserSpan(span, metadata) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) return;
  if (spanCtx.ended) {
    debugLogger8.debug(
      `endToolBlockedOnUserSpan: span ${spanId} already ended (possible TTL sweep race)`
    );
    return;
  }
  spanCtx.ended = true;
  try {
    const duration = Date.now() - spanCtx.startTime;
    const endAttributes = { duration_ms: duration };
    if (metadata?.decision !== void 0)
      endAttributes["decision"] = metadata.decision;
    if (metadata?.source !== void 0)
      endAttributes["source"] = metadata.source;
    spanCtx.span.setAttributes(endAttributes);
  } catch (error) {
    debugLogger8.warn(
      `Failed to update blocked_on_user span attributes: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  try {
    spanCtx.span.end();
  } catch (error) {
    debugLogger8.warn(
      `Failed to end blocked_on_user span: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  activeSpans.delete(spanId);
  strongSpans.delete(spanId);
}
__name(endToolBlockedOnUserSpan, "endToolBlockedOnUserSpan");
function startHookSpan(opts) {
  if (!isTelemetrySdkInitialized()) {
    return NOOP_SPAN;
  }
  ensureCleanupInterval();
  const parentCtx = toolContext.getStore() ?? subagentContext.getStore() ?? interactionContext.getStore() ?? void 0;
  const ctx = resolveParentContext(parentCtx);
  const sessionId = resolveSessionId(parentCtx);
  const attributes = {
    ...sessionId ? { "session.id": sessionId } : {},
    hook_event: opts.hookEvent,
    "tool.name": opts.toolName
  };
  if (opts.toolUseId !== void 0) attributes["tool.use_id"] = opts.toolUseId;
  if (opts.isInterrupt !== void 0)
    attributes["is_interrupt"] = opts.isInterrupt;
  const span = getTracer().startSpan(
    SPAN_HOOK,
    { kind: SpanKind.INTERNAL, attributes },
    ctx
  );
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes,
    type: "hook"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  return span;
}
__name(startHookSpan, "startHookSpan");
function endHookSpan(span, metadata) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) return;
  if (spanCtx.ended) {
    debugLogger8.debug(
      `endHookSpan: span ${spanId} already ended (possible TTL sweep race)`
    );
    return;
  }
  spanCtx.ended = true;
  try {
    const duration = Date.now() - spanCtx.startTime;
    const endAttributes = { duration_ms: duration };
    if (metadata) {
      if (metadata.success !== void 0)
        endAttributes["success"] = metadata.success;
      if (metadata.shouldProceed !== void 0)
        endAttributes["should_proceed"] = metadata.shouldProceed;
      if (metadata.shouldStop !== void 0)
        endAttributes["should_stop"] = metadata.shouldStop;
      if (metadata.blockType !== void 0)
        endAttributes["block_type"] = metadata.blockType;
      if (metadata.hasAdditionalContext !== void 0)
        endAttributes["has_additional_context"] = metadata.hasAdditionalContext;
      if (metadata.postBatchStop !== void 0)
        endAttributes["post_batch_stop"] = metadata.postBatchStop;
      if (metadata.postBatchStopReason !== void 0)
        endAttributes["post_batch_stop_reason"] = truncateSpanError(
          metadata.postBatchStopReason
        );
      if (metadata.error !== void 0)
        endAttributes["error"] = truncateSpanError(metadata.error);
    }
    spanCtx.span.setAttributes(endAttributes);
    if (metadata?.error !== void 0) {
      spanCtx.span.setStatus({
        code: SpanStatusCode.ERROR,
        message: truncateSpanError(metadata.error)
      });
    }
  } catch (error) {
    debugLogger8.warn(
      `Failed to update hook span attributes/status: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  try {
    spanCtx.span.end();
  } catch (error) {
    debugLogger8.warn(
      `Failed to end hook span: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  activeSpans.delete(spanId);
  strongSpans.delete(spanId);
}
__name(endHookSpan, "endHookSpan");
function startSubagentSpan(opts) {
  if (!isTelemetrySdkInitialized()) return NOOP_SPAN;
  ensureCleanupInterval();
  const attributes = {
    // Spec-aligned (OTel GenAI Agent Spans, Development status).
    "gen_ai.operation.name": "invoke_agent",
    "gen_ai.provider.name": SERVICE_NAME,
    "gen_ai.agent.id": opts.agentId,
    "gen_ai.agent.name": opts.subagentName,
    "gen_ai.conversation.id": opts.sessionId,
    // Vendor (qwen-code-specific). Dual-emit id/name so dashboards already
    // querying spec keys still work.
    "qwen-code.subagent.id": opts.agentId,
    "qwen-code.subagent.name": opts.subagentName,
    "qwen-code.subagent.invocation_kind": opts.invocationKind,
    "qwen-code.subagent.is_built_in": opts.isBuiltIn,
    "qwen-code.subagent.depth": opts.depth
  };
  if (opts.modelOverride !== void 0) {
    attributes["gen_ai.request.model"] = opts.modelOverride;
  }
  if (opts.parentAgentId !== void 0) {
    attributes["qwen-code.subagent.parent_agent_id"] = opts.parentAgentId;
  }
  if (opts.invokingRequestId !== void 0) {
    attributes["qwen-code.subagent.invoking_request_id"] = opts.invokingRequestId;
  }
  const tracer2 = getTracer();
  let span;
  if (opts.invocationKind === "foreground") {
    span = tracer2.startSpan(SPAN_SUBAGENT, {
      kind: SpanKind.INTERNAL,
      attributes
    });
  } else {
    span = tracer2.startSpan(SPAN_SUBAGENT, {
      kind: SpanKind.INTERNAL,
      attributes,
      root: true,
      links: opts.invokerSpanContext ? [
        {
          context: opts.invokerSpanContext,
          attributes: { "qwen-code.link.kind": "invoker" }
        }
      ] : void 0
    });
  }
  const spanId = getSpanId(span);
  const spanContextObj = {
    span,
    startTime: Date.now(),
    attributes,
    type: "subagent"
  };
  activeSpans.set(spanId, new WeakRef(spanContextObj));
  strongSpans.set(spanId, spanContextObj);
  return span;
}
__name(startSubagentSpan, "startSubagentSpan");
function runInSubagentSpanContext(span, fn) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) return fn();
  const otelCtxWithSpan = trace.setSpan(context.active(), span);
  return subagentContext.run(
    spanCtx,
    () => toolContext.run(void 0, () => context.with(otelCtxWithSpan, fn))
  );
}
__name(runInSubagentSpanContext, "runInSubagentSpanContext");
function endSubagentSpan(span, metadata) {
  const spanId = getSpanId(span);
  const spanCtx = activeSpans.get(spanId)?.deref();
  if (!spanCtx) {
    if (isTelemetrySdkInitialized()) {
      debugLogger8.warn(
        `endSubagentSpan: span ${spanId} not found in activeSpans (already swept?) \u2014 intended status=${metadata.status}, reason=${metadata.terminateReason ?? "none"}`
      );
    }
    return;
  }
  if (spanCtx.ended) {
    debugLogger8.warn(
      `endSubagentSpan: span ${spanId} already ended \u2014 intended status=${metadata.status}, reason=${metadata.terminateReason ?? "none"} (possible TTL sweep race)`
    );
    return;
  }
  spanCtx.ended = true;
  try {
    const duration = Date.now() - spanCtx.startTime;
    const endAttributes = {
      duration_ms: duration,
      "qwen-code.subagent.duration_ms": duration,
      "qwen-code.subagent.status": metadata.status
    };
    if (metadata.terminateReason !== void 0) {
      endAttributes["qwen-code.subagent.terminate_reason"] = metadata.terminateReason;
    }
    if (metadata.resultSummaryPresent !== void 0) {
      endAttributes["qwen-code.subagent.result_summary_present"] = metadata.resultSummaryPresent;
    }
    if (metadata.error !== void 0) {
      const truncated = truncateSpanError(metadata.error);
      endAttributes["exception.message"] = truncated;
    }
    if (metadata.errorType !== void 0) {
      endAttributes["error.type"] = metadata.errorType;
    }
    spanCtx.span.setAttributes(endAttributes);
    if (metadata.status === "completed") {
      spanCtx.span.setStatus({ code: SpanStatusCode.OK });
    } else if (metadata.status === "failed") {
      spanCtx.span.setStatus({
        code: SpanStatusCode.ERROR,
        message: metadata.error ? truncateSpanError(metadata.error) : "subagent failed"
      });
    }
  } catch (error) {
    debugLogger8.warn(
      `Failed to update subagent span attributes/status: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  try {
    spanCtx.span.end();
  } catch (error) {
    debugLogger8.warn(
      `Failed to end subagent span: ${error instanceof Error ? error.message : String(error)}`
    );
  }
  activeSpans.delete(spanId);
  strongSpans.delete(spanId);
}
__name(endSubagentSpan, "endSubagentSpan");
function getActiveInteractionSpan() {
  const ctx = interactionContext.getStore() ?? lastInteractionCtx;
  if (!ctx || ctx.ended) return void 0;
  return ctx.span;
}
__name(getActiveInteractionSpan, "getActiveInteractionSpan");

// packages/core/src/telemetry/log-to-span-processor.ts
var BRIDGE_SKIP_EVENT_NAMES = /* @__PURE__ */ new Set([EVENT_SUBAGENT_EXECUTION]);
var EXPORT_TIMEOUT_MS = 3e4;
var DEFAULT_MAX_BUFFER_SIZE = 1e4;
var BUFFER_OVERFLOW_WARNING_INTERVAL_MS = 3e4;
var LOG_EVENT_ERROR_STATUS_MESSAGE = "Log event recorded error";
var DEFAULT_LOG_SPAN_NAME = "log.event";
var MAX_SPAN_NAME_LENGTH = 128;
var SENSITIVE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
  "error",
  "error.message",
  "error_message",
  "prompt",
  "function_args",
  "response_text"
]);
var defaultDiagnosticsSink = /* @__PURE__ */ __name((message) => {
  process.stderr.write(`${message}
`);
}, "defaultDiagnosticsSink");
var LogToSpanProcessor = class {
  constructor(spanExporter, flushIntervalMsOrOptions = 5e3, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
    this.spanExporter = spanExporter;
    if (typeof flushIntervalMsOrOptions === "number") {
      this.flushIntervalMs = flushIntervalMsOrOptions;
      this.includeSensitiveSpanAttributes = false;
      this.maxBufferSize = normalizeMaxBufferSize(maxBufferSize);
      this.diagnosticsSink = defaultDiagnosticsSink;
    } else {
      this.flushIntervalMs = flushIntervalMsOrOptions.flushIntervalMs ?? 5e3;
      this.includeSensitiveSpanAttributes = flushIntervalMsOrOptions.includeSensitiveSpanAttributes ?? false;
      this.maxBufferSize = normalizeMaxBufferSize(
        flushIntervalMsOrOptions.maxBufferSize
      );
      this.diagnosticsSink = flushIntervalMsOrOptions.diagnosticsSink ?? defaultDiagnosticsSink;
    }
    this.flushTimer = setInterval(() => {
      void this.flush();
    }, this.flushIntervalMs);
    this.flushTimer.unref();
  }
  static {
    __name(this, "LogToSpanProcessor");
  }
  buffer = [];
  flushTimer;
  inFlightExport;
  flushIntervalMs;
  cachedSessionId;
  cachedTraceId;
  includeSensitiveSpanAttributes;
  maxBufferSize;
  diagnosticsSink;
  lastBufferOverflowWarningMs;
  droppedSpansSinceLastBufferWarning = 0;
  totalDroppedSpans = 0;
  isShutdown = false;
  onEmit(logRecord) {
    if (this.isShutdown) {
      return;
    }
    const eventName = logRecord.attributes?.["event.name"];
    if (typeof eventName === "string" && BRIDGE_SKIP_EVENT_NAMES.has(eventName) && isInNativeSubagentSpan()) {
      return;
    }
    const name = deriveSpanName(logRecord);
    const startTime = logRecord.hrTime;
    const attributes = {};
    if (logRecord.attributes) {
      for (const [key, value] of Object.entries(logRecord.attributes)) {
        if (value !== void 0 && value !== null && (this.includeSensitiveSpanAttributes || !SENSITIVE_ATTRIBUTE_KEYS.has(key))) {
          attributes[key] = typeof value === "object" ? safeStringify(value) : value;
        }
      }
    }
    attributes["log.bridge"] = true;
    if (logRecord.severityNumber !== void 0) {
      attributes["log.severity_number"] = logRecord.severityNumber;
    }
    if (logRecord.severityText) {
      attributes["log.severity_text"] = logRecord.severityText;
    }
    let endTime = startTime;
    const durationMs = logRecord.attributes?.["duration_ms"];
    if (typeof durationMs === "number" && Number.isFinite(durationMs) && durationMs > 0) {
      const [secs, nanos] = startTime;
      const durationNanos = durationMs * 1e6;
      const endNanos = nanos + durationNanos;
      endTime = [secs + Math.floor(endNanos / 1e9), endNanos % 1e9];
    }
    const parentSpanContext = getValidParentSpanContext(logRecord.spanContext);
    const sessionId = logRecord.attributes?.["session.id"] || getCurrentSessionId();
    let traceId;
    if (parentSpanContext) {
      traceId = parentSpanContext.traceId;
    } else if (sessionId) {
      const sid = String(sessionId);
      if (sid !== this.cachedSessionId) {
        this.cachedSessionId = sid;
        this.cachedTraceId = deriveTraceId(sid);
      }
      traceId = this.cachedTraceId;
    } else {
      traceId = randomHexString(32);
    }
    const spanId = randomSpanId();
    this.buffer.push({
      name,
      kind: SpanKind.INTERNAL,
      spanContext: /* @__PURE__ */ __name(() => ({
        traceId,
        spanId,
        traceFlags: parentSpanContext?.traceFlags ?? TraceFlags.SAMPLED
      }), "spanContext"),
      startTime,
      endTime,
      duration: hrTimeDiff(startTime, endTime),
      attributes,
      status: deriveSpanStatus(logRecord.attributes),
      events: [],
      links: [],
      resource: logRecord.resource ?? (0, import_resources.resourceFromAttributes)({}),
      instrumentationScope: logRecord.instrumentationScope ?? {
        name: SERVICE_NAME,
        version: ""
      },
      ended: true,
      parentSpanContext,
      droppedAttributesCount: 0,
      droppedEventsCount: 0,
      droppedLinksCount: 0,
      recordException: /* @__PURE__ */ __name(() => {
      }, "recordException")
    });
    if (this.buffer.length > this.maxBufferSize) {
      const droppedSpanCount = this.buffer.length - this.maxBufferSize;
      this.buffer.splice(0, droppedSpanCount);
      this.warnBufferOverflow(droppedSpanCount);
    }
  }
  warnBufferOverflow(droppedSpanCount) {
    this.droppedSpansSinceLastBufferWarning += droppedSpanCount;
    this.totalDroppedSpans += droppedSpanCount;
    const now = Date.now();
    if (this.lastBufferOverflowWarningMs !== void 0 && now - this.lastBufferOverflowWarningMs < BUFFER_OVERFLOW_WARNING_INTERVAL_MS) {
      return;
    }
    this.emitBufferOverflowWarning(now);
  }
  emitBufferOverflowWarning(now = Date.now()) {
    if (this.droppedSpansSinceLastBufferWarning === 0) {
      return;
    }
    const droppedSinceLastWarning = this.droppedSpansSinceLastBufferWarning;
    this.droppedSpansSinceLastBufferWarning = 0;
    this.lastBufferOverflowWarningMs = now;
    this.emitDiagnostic(
      `[LogToSpan] buffer exceeded max size (${this.maxBufferSize}); dropped ${droppedSinceLastWarning} oldest span(s) since last warning, ${this.totalDroppedSpans} total`
    );
  }
  /**
   * Route a diagnostic message to the configured sink, swallowing any sink
   * error so a misbehaving sink can never interrupt telemetry ingestion.
   *
   * Tradeoff: when the sink itself is broken (e.g. file-logger failing on
   * EACCES), bridge-specific diagnostics go dark. We accept that — the host
   * surfaces overall logging health via `isDebugLoggingDegraded()`, and
   * falling back to stderr here would re-introduce the TUI-pollution this
   * sink injection was added to prevent.
   */
  emitDiagnostic(message) {
    try {
      this.diagnosticsSink(message);
    } catch {
    }
  }
  flush() {
    if (this.inFlightExport) return this.inFlightExport;
    if (this.buffer.length === 0) return Promise.resolve();
    const spans = this.buffer.splice(0);
    const exportPromise = new Promise((resolve2) => {
      const timeout = setTimeout(() => {
        this.emitDiagnostic(
          `[LogToSpan] export timeout after ${EXPORT_TIMEOUT_MS}ms (${spans.length} span(s))`
        );
        resolve2();
      }, EXPORT_TIMEOUT_MS);
      timeout.unref();
      try {
        this.spanExporter.export(
          spans,
          (result) => {
            clearTimeout(timeout);
            if (result.code !== 0) {
              this.emitDiagnostic(
                `[LogToSpan] export failed: code=${result.code} ${formatExportError(result.error)}`
              );
            }
            resolve2();
          }
        );
      } catch (err) {
        clearTimeout(timeout);
        const detail = err instanceof Error ? formatExportError(err) : `error=${JSON.stringify(String(err))}`;
        this.emitDiagnostic(`[LogToSpan] export threw: ${detail}`);
        resolve2();
      }
    });
    this.inFlightExport = exportPromise.finally(() => {
      this.inFlightExport = void 0;
    });
    return this.inFlightExport;
  }
  async shutdown() {
    if (this.isShutdown) {
      return;
    }
    this.isShutdown = true;
    if (this.flushTimer) {
      clearInterval(this.flushTimer);
      this.flushTimer = void 0;
    }
    if (this.inFlightExport) {
      await this.inFlightExport;
    }
    await this.flush();
    this.emitBufferOverflowWarning();
    await this.spanExporter.shutdown();
  }
  async forceFlush() {
    if (this.isShutdown) {
      return;
    }
    if (this.inFlightExport) {
      await this.inFlightExport;
    }
    await this.flush();
    await this.spanExporter.forceFlush?.();
  }
};
function normalizeMaxBufferSize(value) {
  if (typeof value !== "number" || !Number.isFinite(value) || value < 1) {
    return DEFAULT_MAX_BUFFER_SIZE;
  }
  return Math.floor(value);
}
__name(normalizeMaxBufferSize, "normalizeMaxBufferSize");
function deriveSpanName(logRecord) {
  const eventName = logRecord.attributes?.["event.name"] ?? logRecord.eventName;
  if (typeof eventName === "string" && eventName.trim().length > 0) {
    return sanitizeSpanName(eventName);
  }
  return DEFAULT_LOG_SPAN_NAME;
}
__name(deriveSpanName, "deriveSpanName");
function sanitizeSpanName(body) {
  const rawName = String(body ?? "unknown");
  return rawName.length > MAX_SPAN_NAME_LENGTH ? `${rawName.slice(0, MAX_SPAN_NAME_LENGTH)}...` : rawName;
}
__name(sanitizeSpanName, "sanitizeSpanName");
function getValidParentSpanContext(spanContext) {
  if (!spanContext || !isSpanContextValid(spanContext)) {
    return void 0;
  }
  return spanContext;
}
__name(getValidParentSpanContext, "getValidParentSpanContext");
function safeStringify(value) {
  try {
    return JSON.stringify(value);
  } catch {
    return "[unserializable]";
  }
}
__name(safeStringify, "safeStringify");
function deriveSpanStatus(attrs) {
  if (!attrs) return { code: SpanStatusCode.OK };
  if (!!attrs["error"] || !!attrs["error.message"] || !!attrs["error_message"] || !!attrs["error_type"]) {
    return {
      code: SpanStatusCode.ERROR,
      message: LOG_EVENT_ERROR_STATUS_MESSAGE
    };
  }
  return { code: SpanStatusCode.OK };
}
__name(deriveSpanStatus, "deriveSpanStatus");
function formatExportError(err) {
  if (!err) return 'error="unknown"';
  const extra = err;
  const msg = err.message || err.name || "unknown";
  const parts = [`error=${JSON.stringify(msg)}`];
  if (typeof extra.code === "number") parts.push(`httpCode=${extra.code}`);
  if (typeof extra.data === "string" && extra.data.length > 0) {
    parts.push(`data=${JSON.stringify(extra.data.slice(0, 200))}`);
  }
  return parts.join(" ");
}
__name(formatExportError, "formatExportError");
function hrTimeDiff(start, end) {
  let secs = end[0] - start[0];
  let nanos = end[1] - start[1];
  if (nanos < 0) {
    secs -= 1;
    nanos += 1e9;
  }
  return [secs, nanos];
}
__name(hrTimeDiff, "hrTimeDiff");

// packages/core/src/telemetry/tracer.ts
init_esbuild_shims();
init_esm();
var tracer = trace.getTracer(SERVICE_NAME);
var debugLogger9 = createDebugLogger("OTEL_TRACER");
var TELEMETRY_WARNING_INTERVAL_MS = 3e4;
var API_CALL_FAILED_SPAN_STATUS_MESSAGE = "API call failed";
var API_CALL_ABORTED_SPAN_STATUS_MESSAGE = "API call aborted";
var lastTelemetryWarningMs;
var suppressedTelemetryWarnings = 0;
function warnTelemetryOperationFailed(operation, error) {
  const now = Date.now();
  if (lastTelemetryWarningMs !== void 0 && now - lastTelemetryWarningMs < TELEMETRY_WARNING_INTERVAL_MS) {
    suppressedTelemetryWarnings += 1;
    return;
  }
  const suppressedSuffix = suppressedTelemetryWarnings > 0 ? `; suppressed ${suppressedTelemetryWarnings} similar warning(s)` : "";
  suppressedTelemetryWarnings = 0;
  lastTelemetryWarningMs = now;
  try {
    debugLogger9.warn(
      `OTel span ${operation} failed: ${error instanceof Error ? error.message : String(error)}${suppressedSuffix}`
    );
  } catch {
  }
}
__name(warnTelemetryOperationFailed, "warnTelemetryOperationFailed");
function safeSetStatus(span, status) {
  try {
    span.setStatus(status);
  } catch (error) {
    warnTelemetryOperationFailed("setStatus", error);
  }
}
__name(safeSetStatus, "safeSetStatus");
function shouldForceSampled() {
  const sampler = process.env["OTEL_TRACES_SAMPLER"]?.trim().toLowerCase() ?? "";
  if (!sampler || sampler.startsWith("parentbased_")) {
    if (sampler.includes("always_off")) return false;
    return true;
  }
  return sampler === "always_on";
}
__name(shouldForceSampled, "shouldForceSampled");
function createSessionRootContext(sessionId) {
  const traceId = deriveTraceId(sessionId);
  const spanId = randomSpanId();
  const rootSpan = trace.wrapSpanContext({
    traceId,
    spanId,
    traceFlags: shouldForceSampled() ? TraceFlags.SAMPLED : TraceFlags.NONE,
    isRemote: false
  });
  return trace.setSpan(ROOT_CONTEXT, rootSpan);
}
__name(createSessionRootContext, "createSessionRootContext");

// packages/core/src/telemetry/sdk.ts
function createTelemetryDiagLogger() {
  const debugLogger14 = createDebugLogger("OTEL");
  return {
    error: /* @__PURE__ */ __name((message, ...args) => debugLogger14.error(message, ...args), "error"),
    warn: /* @__PURE__ */ __name((message, ...args) => debugLogger14.warn(message, ...args), "warn"),
    info: /* @__PURE__ */ __name((message, ...args) => debugLogger14.info(message, ...args), "info"),
    debug: /* @__PURE__ */ __name((message, ...args) => debugLogger14.debug(message, ...args), "debug"),
    verbose: /* @__PURE__ */ __name((message, ...args) => debugLogger14.debug(message, ...args), "verbose")
  };
}
__name(createTelemetryDiagLogger, "createTelemetryDiagLogger");
diag.setLogger(createTelemetryDiagLogger(), DiagLogLevel.WARN);
var OTLP_SIGNAL_PATHS = {
  traces: "v1/traces",
  logs: "v1/logs",
  metrics: "v1/metrics"
};
function resolveHttpOtlpUrl(baseEndpoint, signal) {
  const signalPath = OTLP_SIGNAL_PATHS[signal];
  const url = new URL(baseEndpoint);
  const normalizedPath = url.pathname.replace(/\/+$/, "");
  if (normalizedPath.endsWith(signalPath)) {
    return url.href;
  }
  url.pathname = normalizedPath + "/" + signalPath;
  return url.href;
}
__name(resolveHttpOtlpUrl, "resolveHttpOtlpUrl");
var SHUTDOWN_TIMEOUT_MS = 1e4;
var NOOP_PROPAGATOR = {
  inject() {
  },
  extract(context2) {
    return context2;
  },
  fields() {
    return [];
  }
};
var sdk;
var telemetryInitialized = false;
var telemetryShutdownPromise;
var activeMetricReader;
function isTelemetrySdkInitialized() {
  return telemetryInitialized;
}
__name(isTelemetrySdkInitialized, "isTelemetrySdkInitialized");
function parseOtlpEndpoint(otlpEndpointSetting, protocol) {
  if (!otlpEndpointSetting) {
    return void 0;
  }
  const trimmedEndpoint = otlpEndpointSetting.replace(/^["']|["']$/g, "");
  try {
    const url = new URL(trimmedEndpoint);
    if (protocol === "grpc") {
      return url.origin;
    }
    return url.href;
  } catch (error) {
    diag.error("Invalid OTLP endpoint URL provided:", trimmedEndpoint, error);
    return void 0;
  }
}
__name(parseOtlpEndpoint, "parseOtlpEndpoint");
function validateUrl(url) {
  if (!url) return void 0;
  try {
    const parsed = new URL(url);
    if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
      diag.error(
        `OTLP endpoint must use http or https, got ${parsed.protocol}`
      );
      return void 0;
    }
    if (!parsed.hostname) {
      diag.error("OTLP endpoint missing hostname");
      return void 0;
    }
    return url;
  } catch {
    diag.error("Invalid OTLP signal endpoint URL, skipping:", url);
    return void 0;
  }
}
__name(validateUrl, "validateUrl");
var SessionIdSpanProcessor = class {
  static {
    __name(this, "SessionIdSpanProcessor");
  }
  onStart(span) {
    try {
      if (span.attributes?.["session.id"]) return;
      const sessionId = getCurrentSessionId();
      if (sessionId) {
        span.setAttribute("session.id", sessionId);
      }
    } catch {
    }
  }
  onEnd(_span) {
  }
  async shutdown() {
  }
  async forceFlush() {
  }
};
function initializeTelemetry(config) {
  if (telemetryInitialized || !config.getTelemetryEnabled()) {
    return;
  }
  const debugLogger14 = createDebugLogger("OTEL");
  const userAttrs = config.getTelemetryResourceAttributes() ?? {};
  const userServiceName = userAttrs["service.name"];
  const {
    "service.name": _ignoredServiceName,
    "service.version": _ignoredServiceVersion,
    "session.id": _ignoredSessionId,
    ...nonReservedUserAttrs
  } = userAttrs;
  const resource = (0, import_resources2.resourceFromAttributes)({
    ...nonReservedUserAttrs,
    // `.trim() || SERVICE_NAME`: catches both empty string (`""`) and
    // whitespace-only values (`" "`, `"\t"`) that would otherwise produce
    // a blank service name on Resource (some backends reject these). Both
    // settings (no value trimming there) and env (`%20` decodes to `" "`)
    // can deliver whitespace-only values, so trim at the fallback point.
    [SemanticResourceAttributes.SERVICE_NAME]: userServiceName?.trim() || SERVICE_NAME,
    [SemanticResourceAttributes.SERVICE_VERSION]: config.getCliVersion() || "unknown"
  });
  const attrWarnings = config.getTelemetryResourceAttributeWarnings() ?? [];
  if (attrWarnings.length > 0) {
    console.warn(
      `[qwen-code telemetry] ${attrWarnings.length} resource attribute issue(s):`
    );
    for (const w of attrWarnings) {
      console.warn(`  - ${w}`);
    }
  }
  const otlpEndpoint = config.getTelemetryOtlpEndpoint();
  const otlpProtocol = config.getTelemetryOtlpProtocol();
  const parsedEndpoint = parseOtlpEndpoint(otlpEndpoint, otlpProtocol);
  const telemetryOutfile = config.getTelemetryOutfile();
  const hasPerSignalEndpoint = !!config.getTelemetryOtlpTracesEndpoint() || !!config.getTelemetryOtlpLogsEndpoint() || !!config.getTelemetryOtlpMetricsEndpoint();
  const useOtlp = (!!parsedEndpoint || hasPerSignalEndpoint) && !telemetryOutfile;
  let spanExporter;
  let logExporter;
  let metricReader;
  let logToSpanProcessor;
  if (useOtlp) {
    if (otlpProtocol === "http") {
      const tracesUrl = validateUrl(
        config.getTelemetryOtlpTracesEndpoint() ?? (parsedEndpoint ? resolveHttpOtlpUrl(parsedEndpoint, "traces") : void 0)
      );
      const logsUrl = validateUrl(
        config.getTelemetryOtlpLogsEndpoint() ?? (parsedEndpoint ? resolveHttpOtlpUrl(parsedEndpoint, "logs") : void 0)
      );
      const metricsUrl = validateUrl(
        config.getTelemetryOtlpMetricsEndpoint() ?? (parsedEndpoint ? resolveHttpOtlpUrl(parsedEndpoint, "metrics") : void 0)
      );
      debugLogger14.debug(
        `OTLP HTTP endpoints: traces=${tracesUrl ?? "none"}, logs=${logsUrl ?? "none"}, metrics=${metricsUrl ?? "none"}`
      );
      if (tracesUrl) {
        spanExporter = new import_exporter_trace_otlp_http.OTLPTraceExporter({ url: tracesUrl });
      }
      if (logsUrl) {
        logExporter = new import_exporter_logs_otlp_http.OTLPLogExporter({ url: logsUrl });
      } else if (tracesUrl) {
        logToSpanProcessor = new LogToSpanProcessor(
          new import_exporter_trace_otlp_http.OTLPTraceExporter({ url: tracesUrl }),
          {
            includeSensitiveSpanAttributes: config.getTelemetryIncludeSensitiveSpanAttributes(),
            // In interactive (TUI) mode, route bridge diagnostics to the OTEL
            // debug log file so they don't break out of the Ink render area
            // via raw stderr. In non-interactive mode, leave the default sink
            // alone so CI / scripts can still see export failures on stderr
            // the canonical diagnostic channel for batch runs.
            //
            // Caveat for interactive mode: when the user has explicitly
            // disabled file logging via QWEN_DEBUG_LOG_FILE=0, debugLogger.warn
            // silently no-ops and bridge diagnostics are fully lost — accepted
            // trade-off, since falling back to stderr would re-introduce the
            // TUI pollution this injection was added to prevent.
            ...config.isInteractive() && {
              diagnosticsSink: /* @__PURE__ */ __name((message) => debugLogger14.warn(message), "diagnosticsSink")
            }
          }
        );
      }
      if (metricsUrl) {
        metricReader = new import_sdk_metrics2.PeriodicExportingMetricReader({
          exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter({ url: metricsUrl }),
          exportIntervalMillis: 1e4
        });
      }
    } else {
      if (!parsedEndpoint) {
        const warning = 'Per-signal OTLP endpoints are only supported with HTTP protocol. Set otlpProtocol to "http" or provide a base otlpEndpoint for gRPC. Telemetry SDK startup was skipped because no supported gRPC endpoint was configured.';
        diag.warn(warning);
        debugLogger14.warn(warning);
        return;
      } else {
        spanExporter = new import_exporter_trace_otlp_grpc.OTLPTraceExporter({
          url: parsedEndpoint,
          compression: CompressionAlgorithm.GZIP
        });
        logExporter = new import_exporter_logs_otlp_grpc.OTLPLogExporter({
          url: parsedEndpoint,
          compression: CompressionAlgorithm.GZIP
        });
        metricReader = new import_sdk_metrics2.PeriodicExportingMetricReader({
          exporter: new import_exporter_metrics_otlp_grpc.OTLPMetricExporter({
            url: parsedEndpoint,
            compression: CompressionAlgorithm.GZIP
          }),
          exportIntervalMillis: 1e4
        });
      }
    }
  } else if (telemetryOutfile) {
    spanExporter = new FileSpanExporter(telemetryOutfile);
    logExporter = new FileLogExporter(telemetryOutfile);
    metricReader = new import_sdk_metrics2.PeriodicExportingMetricReader({
      exporter: new FileMetricExporter(telemetryOutfile),
      exportIntervalMillis: 1e4
    });
  }
  function normalizeOtlpPrefix(raw) {
    if (!raw) return void 0;
    const s = raw.trim().replace(/^["']|["']$/g, "");
    try {
      const u = new URL(s);
      const pathname = u.pathname === "/" ? "" : u.pathname.replace(/\/$/, "");
      return { origin: u.origin, pathname };
    } catch {
      diag.warn(
        `Telemetry OTLP endpoint "${raw}" is not a valid URL; instrumentation feedback-loop guard for it is disabled.`
      );
      return void 0;
    }
  }
  __name(normalizeOtlpPrefix, "normalizeOtlpPrefix");
  const otlpUrlPrefixes = [
    config.getTelemetryOtlpEndpoint(),
    config.getTelemetryOtlpTracesEndpoint(),
    config.getTelemetryOtlpLogsEndpoint(),
    config.getTelemetryOtlpMetricsEndpoint()
  ].map(normalizeOtlpPrefix).filter((u) => !!u);
  const matchesOtlpPrefix = /* @__PURE__ */ __name((origin, path11) => {
    for (const prefix of otlpUrlPrefixes) {
      if (origin !== prefix.origin) continue;
      if (prefix.pathname === "") return true;
      if (!path11.startsWith(prefix.pathname)) continue;
      const next = path11.charAt(prefix.pathname.length);
      if (next === "" || next === "/" || next === "?" || next === "#") {
        return true;
      }
    }
    return false;
  }, "matchesOtlpPrefix");
  const stripPathSuffix = /* @__PURE__ */ __name((path11) => {
    const qIdx = path11.indexOf("?");
    const fIdx = path11.indexOf("#");
    let cut = path11.length;
    if (qIdx !== -1) cut = Math.min(cut, qIdx);
    if (fIdx !== -1) cut = Math.min(cut, fIdx);
    return path11.slice(0, cut);
  }, "stripPathSuffix");
  const textMapPropagator = config.getOutboundCorrelationPropagateTraceContext() ? void 0 : NOOP_PROPAGATOR;
  sdk = new import_sdk_node.NodeSDK({
    resource,
    // Disable async host/process/env resource detectors: they leave attributes
    // pending and trigger an OTel diag.error on any resource attribute read
    // before the detectors settle (e.g. during HttpInstrumentation span creation).
    autoDetectResources: false,
    ...textMapPropagator && { textMapPropagator },
    spanProcessors: spanExporter ? [new SessionIdSpanProcessor(), new import_sdk_trace_node.BatchSpanProcessor(spanExporter)] : [],
    logRecordProcessors: logExporter ? [new import_sdk_logs.BatchLogRecordProcessor(logExporter)] : logToSpanProcessor ? [logToSpanProcessor] : [],
    ...metricReader && { metricReader },
    instrumentations: [
      new import_instrumentation_http.HttpInstrumentation({
        // OTLP HTTP exporter uses node:http (patched here, not by undici).
        // Without this, every OTLP upload batch creates a parasitic client
        // span that itself gets exported → feedback loop.
        ignoreOutgoingRequestHook: /* @__PURE__ */ __name((req) => {
          if (otlpUrlPrefixes.length === 0) return false;
          const proto = req.protocol ? String(req.protocol).replace(/:$/, "") : void 0;
          if (!proto) return false;
          let host = req.hostname || "";
          if (!host && req.host) {
            const h = String(req.host);
            const bracketEnd = h.indexOf("]");
            const portIdx = bracketEnd !== -1 ? h.indexOf(":", bracketEnd) : h.indexOf(":");
            host = portIdx !== -1 ? h.slice(0, portIdx) : h;
          }
          const portPart = req.port !== void 0 && req.port !== null && String(req.port) ? `:${req.port}` : "";
          let origin;
          try {
            origin = new URL(`${proto}://${host}${portPart}`).origin;
          } catch {
            return false;
          }
          const path11 = typeof req.path === "string" ? stripPathSuffix(req.path) : "";
          return matchesOtlpPrefix(origin, path11);
        }, "ignoreOutgoingRequestHook")
      }),
      // Modern fetch (`globalThis.fetch` / undici) is the HTTP layer used by
      // `openai`, `@google/genai`, and `@anthropic-ai/sdk`. Without this
      // instrumentation, outbound LLM requests carry no `traceparent` header
      // and the trace tree terminates at the qwen-code process boundary.
      new import_instrumentation_undici.UndiciInstrumentation({
        ignoreRequestHook: /* @__PURE__ */ __name((request4) => {
          if (otlpUrlPrefixes.length === 0) return false;
          const path11 = typeof request4.path === "string" ? stripPathSuffix(request4.path) : "";
          return matchesOtlpPrefix(request4.origin, path11);
        }, "ignoreRequestHook")
      })
    ]
  });
  try {
    sdk.start();
    debugLogger14.debug("OpenTelemetry SDK started successfully.");
    telemetryInitialized = true;
    activeMetricReader = metricReader;
    const sessionId = config.getSessionId();
    setSessionContext(createSessionRootContext(sessionId), sessionId);
    setShellTracePropagation(
      config.getOutboundCorrelationPropagateTraceContext()
    );
    initializeMetrics(config);
  } catch (error) {
    debugLogger14.error("Error starting OpenTelemetry SDK:", error);
  }
}
__name(initializeTelemetry, "initializeTelemetry");
function refreshSessionContext(sessionId) {
  if (!telemetryInitialized) return;
  try {
    setSessionContext(createSessionRootContext(sessionId), sessionId);
  } catch (error) {
    createDebugLogger("OTEL").warn("Failed to refresh session context:", error);
  }
}
__name(refreshSessionContext, "refreshSessionContext");
async function shutdownTelemetry() {
  if (telemetryShutdownPromise) {
    return telemetryShutdownPromise;
  }
  if (!telemetryInitialized || !sdk) {
    return;
  }
  endInteractionSpan("cancelled");
  const currentSdk = sdk;
  const debugLogger14 = createDebugLogger("OTEL");
  telemetryShutdownPromise = (async () => {
    let timer;
    let timedOut = false;
    try {
      const sdkShutdown = Promise.resolve(currentSdk.shutdown());
      sdkShutdown.catch((err) => {
        if (timedOut) {
          debugLogger14.warn(
            "SDK shutdown rejected after timeout:",
            err instanceof Error ? err.message : err
          );
        }
      });
      const timeout = new Promise((resolve2) => {
        timer = setTimeout(() => {
          timedOut = true;
          resolve2("timeout");
        }, SHUTDOWN_TIMEOUT_MS);
        timer.unref?.();
      });
      const result = await Promise.race([sdkShutdown, timeout]);
      clearTimeout(timer);
      if (result === "timeout") {
        const msg = `Telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms.`;
        diag.warn(msg);
        debugLogger14.warn(msg);
      } else {
        debugLogger14.debug("OpenTelemetry SDK shut down successfully.");
      }
    } catch (error) {
      clearTimeout(timer);
      diag.error("Error shutting down SDK:", error);
      debugLogger14.error("Error shutting down SDK:", error);
    } finally {
      telemetryInitialized = false;
      sdk = void 0;
      activeMetricReader = void 0;
      telemetryShutdownPromise = void 0;
      setSessionContext(void 0);
      setShellTracePropagation(false);
    }
  })();
  return telemetryShutdownPromise;
}
__name(shutdownTelemetry, "shutdownTelemetry");
var FORCE_FLUSH_TIMEOUT_MS = 2e3;
async function forceFlushMetrics() {
  if (!telemetryInitialized || !activeMetricReader) return;
  const flush = activeMetricReader.forceFlush();
  flush.catch(() => {
  });
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(
      () => reject(
        new Error(
          `forceFlushMetrics timed out after ${FORCE_FLUSH_TIMEOUT_MS}ms`
        )
      ),
      FORCE_FLUSH_TIMEOUT_MS
    );
    timer.unref?.();
  });
  try {
    await Promise.race([flush, timeout]);
  } finally {
    clearTimeout(timer);
  }
}
__name(forceFlushMetrics, "forceFlushMetrics");

// packages/core/src/telemetry/config.ts
init_esbuild_shims();

// packages/core/src/telemetry/resource-attributes.ts
init_esbuild_shims();
init_esm();
var RESERVED_RESOURCE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
  "service.version",
  "session.id"
]);
function warn(msg, warnings) {
  diag.warn(msg);
  warnings?.push(msg);
}
__name(warn, "warn");
function parseOtelResourceAttributes(raw, warnings) {
  if (!raw) return {};
  const out = {};
  for (const pair of raw.split(",")) {
    const trimmed = pair.trim();
    if (!trimmed) continue;
    const idx = trimmed.indexOf("=");
    if (idx < 0) {
      warn(
        `Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${trimmed}" (hint: percent-encode literal commas as %2C)`,
        warnings
      );
      continue;
    }
    const rawKey = trimmed.slice(0, idx).trim();
    if (!rawKey) continue;
    const valueRaw = trimmed.slice(idx + 1).trim();
    let key;
    try {
      key = decodeURIComponent(rawKey);
    } catch {
      warn(
        `Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${rawKey}", using raw key`,
        warnings
      );
      key = rawKey;
    }
    let value;
    try {
      value = decodeURIComponent(valueRaw);
    } catch {
      warn(
        `Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${key}", using raw value`,
        warnings
      );
      value = valueRaw;
    }
    out[key] = value;
  }
  return out;
}
__name(parseOtelResourceAttributes, "parseOtelResourceAttributes");
function stripReservedResourceAttributes(attrs, source, warnings) {
  for (const k of RESERVED_RESOURCE_ATTRIBUTE_KEYS) {
    if (k in attrs) {
      warn(`${source} cannot override reserved key "${k}"; ignoring`, warnings);
      delete attrs[k];
    }
  }
  return attrs;
}
__name(stripReservedResourceAttributes, "stripReservedResourceAttributes");
function coerceStringResourceAttributes(raw, warnings) {
  if (raw === null || raw === void 0) return {};
  if (typeof raw !== "object" || Array.isArray(raw)) {
    warn(
      "settings.telemetry.resourceAttributes must be an object; ignoring",
      warnings
    );
    return {};
  }
  const out = {};
  for (const [k, v] of Object.entries(raw)) {
    const key = k.trim();
    if (!key) {
      warn(
        "settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",
        warnings
      );
      continue;
    }
    if (typeof v === "string") {
      out[key] = v;
    } else {
      warn(
        `settings.telemetry.resourceAttributes value for "${key}" must be a string (got ${typeof v}); ignoring`,
        warnings
      );
    }
  }
  return out;
}
__name(coerceStringResourceAttributes, "coerceStringResourceAttributes");

// packages/core/src/telemetry/config.ts
function parseBooleanEnvFlag(value) {
  if (value === void 0) return void 0;
  return value === "true" || value === "1";
}
__name(parseBooleanEnvFlag, "parseBooleanEnvFlag");
function parseTelemetryTargetValue(value) {
  if (value === void 0) return void 0;
  if (value === "local" /* LOCAL */ || value === "local") {
    return "local" /* LOCAL */;
  }
  if (value === "gcp" /* GCP */ || value === "gcp") {
    return "gcp" /* GCP */;
  }
  return void 0;
}
__name(parseTelemetryTargetValue, "parseTelemetryTargetValue");
function parseSensitiveSpanAttributeMaxLengthEnvValue(envName, value) {
  if (value === void 0) return void 0;
  const trimmed = value.trim();
  const parsed = Number(trimmed);
  if (!/^\d+$/.test(trimmed) || !isValidSensitiveSpanAttributeMaxLength(parsed)) {
    throw new FatalConfigError(
      `Invalid ${envName}: must be a positive integer no greater than ${SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT}, got '${value}'`
    );
  }
  return parsed;
}
__name(parseSensitiveSpanAttributeMaxLengthEnvValue, "parseSensitiveSpanAttributeMaxLengthEnvValue");
function parseSensitiveSpanAttributeMaxLengthSetting(settingName, value) {
  if (value === void 0) return void 0;
  if (typeof value !== "number" || !isValidSensitiveSpanAttributeMaxLength(value)) {
    throw new FatalConfigError(
      `Invalid ${settingName}: must be a positive integer no greater than ${SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT}, got ${String(
        value
      )}`
    );
  }
  return value;
}
__name(parseSensitiveSpanAttributeMaxLengthSetting, "parseSensitiveSpanAttributeMaxLengthSetting");
async function resolveTelemetrySettings(options) {
  const argv = options.argv ?? {};
  const env = options.env ?? {};
  const settings = options.settings ?? {};
  const enabled = argv.telemetry ?? parseBooleanEnvFlag(env["QWEN_TELEMETRY_ENABLED"]) ?? settings.enabled;
  const rawTarget = argv.telemetryTarget ?? env["QWEN_TELEMETRY_TARGET"] ?? settings.target;
  const target = parseTelemetryTargetValue(rawTarget);
  if (rawTarget !== void 0 && target === void 0) {
    throw new FatalConfigError(
      `Invalid telemetry target: ${String(
        rawTarget
      )}. Valid values are: local, gcp`
    );
  }
  const otlpEndpoint = argv.telemetryOtlpEndpoint ?? env["QWEN_TELEMETRY_OTLP_ENDPOINT"] ?? env["OTEL_EXPORTER_OTLP_ENDPOINT"] ?? settings.otlpEndpoint;
  const rawProtocol = argv.telemetryOtlpProtocol ?? env["QWEN_TELEMETRY_OTLP_PROTOCOL"] ?? settings.otlpProtocol;
  const otlpProtocol = ["grpc", "http"].find(
    (p) => p === rawProtocol
  );
  if (rawProtocol !== void 0 && otlpProtocol === void 0) {
    throw new FatalConfigError(
      `Invalid telemetry OTLP protocol: ${String(
        rawProtocol
      )}. Valid values are: grpc, http`
    );
  }
  const logPrompts = argv.telemetryLogPrompts ?? parseBooleanEnvFlag(env["QWEN_TELEMETRY_LOG_PROMPTS"]) ?? settings.logPrompts;
  const includeSensitiveSpanAttributes = parseBooleanEnvFlag(
    env["QWEN_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES"]
  ) ?? settings.includeSensitiveSpanAttributes ?? false;
  const sensitiveSpanAttributeMaxLength = parseSensitiveSpanAttributeMaxLengthEnvValue(
    "QWEN_TELEMETRY_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH",
    env["QWEN_TELEMETRY_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH"]
  ) ?? parseSensitiveSpanAttributeMaxLengthSetting(
    "telemetry.sensitiveSpanAttributeMaxLength",
    settings.sensitiveSpanAttributeMaxLength
  ) ?? DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH;
  const outfile = argv.telemetryOutfile ?? env["QWEN_TELEMETRY_OUTFILE"] ?? settings.outfile;
  const otlpTracesEndpoint = env["QWEN_TELEMETRY_OTLP_TRACES_ENDPOINT"] ?? env["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] ?? settings.otlpTracesEndpoint;
  const otlpLogsEndpoint = env["QWEN_TELEMETRY_OTLP_LOGS_ENDPOINT"] ?? env["OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"] ?? settings.otlpLogsEndpoint;
  const otlpMetricsEndpoint = env["QWEN_TELEMETRY_OTLP_METRICS_ENDPOINT"] ?? env["OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"] ?? settings.otlpMetricsEndpoint;
  const resourceAttributeWarnings = [];
  const envResourceAttrs = stripReservedResourceAttributes(
    parseOtelResourceAttributes(
      env["OTEL_RESOURCE_ATTRIBUTES"],
      resourceAttributeWarnings
    ),
    "OTEL_RESOURCE_ATTRIBUTES",
    resourceAttributeWarnings
  );
  const settingsResourceAttrs = stripReservedResourceAttributes(
    coerceStringResourceAttributes(
      settings.resourceAttributes,
      resourceAttributeWarnings
    ),
    "settings.telemetry.resourceAttributes",
    resourceAttributeWarnings
  );
  const mergedResourceAttrs = {
    ...envResourceAttrs,
    ...settingsResourceAttrs
  };
  const otelServiceName = env["OTEL_SERVICE_NAME"]?.trim();
  if (otelServiceName) {
    mergedResourceAttrs["service.name"] = otelServiceName;
  }
  const resourceAttributes = Object.keys(mergedResourceAttrs).length ? mergedResourceAttrs : void 0;
  const metricsIncludeSessionId = parseBooleanEnvFlag(env["QWEN_TELEMETRY_METRICS_INCLUDE_SESSION_ID"]) ?? settings.metrics?.includeSessionId ?? false;
  return {
    enabled,
    target,
    otlpEndpoint,
    otlpProtocol,
    otlpTracesEndpoint,
    otlpLogsEndpoint,
    otlpMetricsEndpoint,
    logPrompts,
    includeSensitiveSpanAttributes,
    sensitiveSpanAttributeMaxLength,
    outfile,
    resourceAttributes,
    metrics: { includeSessionId: metricsIncludeSessionId },
    resourceAttributeWarnings: resourceAttributeWarnings.length ? resourceAttributeWarnings : void 0
  };
}
__name(resolveTelemetrySettings, "resolveTelemetrySettings");

// packages/core/src/telemetry/index.ts
init_esm();
init_esm2();

// packages/core/src/telemetry/uiTelemetry.ts
init_esbuild_shims();
import { EventEmitter } from "node:events";
var createInitialModelMetricsCore = /* @__PURE__ */ __name(() => ({
  api: {
    totalRequests: 0,
    totalErrors: 0,
    totalLatencyMs: 0
  },
  tokens: {
    prompt: 0,
    candidates: 0,
    total: 0,
    cached: 0,
    thoughts: 0
  }
}), "createInitialModelMetricsCore");
var createInitialModelMetrics = /* @__PURE__ */ __name(() => ({
  ...createInitialModelMetricsCore(),
  bySource: /* @__PURE__ */ Object.create(null)
}), "createInitialModelMetrics");
var createInitialSkillMetrics = /* @__PURE__ */ __name(() => ({
  totalCalls: 0,
  totalSuccess: 0,
  totalFail: 0,
  byName: {}
}), "createInitialSkillMetrics");
var createInitialMetrics = /* @__PURE__ */ __name(() => ({
  models: {},
  tools: {
    totalCalls: 0,
    totalSuccess: 0,
    totalFail: 0,
    totalDurationMs: 0,
    totalDecisions: {
      ["accept" /* ACCEPT */]: 0,
      ["reject" /* REJECT */]: 0,
      ["modify" /* MODIFY */]: 0,
      ["auto_accept" /* AUTO_ACCEPT */]: 0
    },
    byName: {}
  },
  files: {
    totalLinesAdded: 0,
    totalLinesRemoved: 0
  },
  skills: createInitialSkillMetrics()
}), "createInitialMetrics");
var UiTelemetryService = class _UiTelemetryService extends EventEmitter {
  static {
    __name(this, "UiTelemetryService");
  }
  static #MAX_CLOSED_SESSIONS = 1e3;
  #metrics = createInitialMetrics();
  #sessionMetrics = /* @__PURE__ */ new Map();
  #closedSessions = /* @__PURE__ */ new Set();
  #lastPromptTokenCount = 0;
  #lastCachedContentTokenCount = 0;
  #sessionStartTime = /* @__PURE__ */ new Date();
  addEvent(event, sessionId) {
    if (!this.#accumulateEvent(this.#metrics, event)) return;
    if (sessionId && !this.#closedSessions.has(sessionId)) {
      if (!this.#sessionMetrics.has(sessionId)) {
        this.#sessionMetrics.set(sessionId, createInitialMetrics());
      }
      this.#accumulateEvent(this.#sessionMetrics.get(sessionId), event);
    }
    this.emit("update", {
      metrics: this.#metrics,
      lastPromptTokenCount: this.#lastPromptTokenCount
    });
  }
  getMetrics() {
    return this.#metrics;
  }
  getMetricsForSession(sessionId) {
    return this.#sessionMetrics.get(sessionId) ?? createInitialMetrics();
  }
  recordSkillInvocation(skillName, success, sessionId) {
    this.#accumulateSkillInvocation(this.#metrics, skillName, success);
    if (sessionId && !this.#closedSessions.has(sessionId)) {
      if (!this.#sessionMetrics.has(sessionId)) {
        this.#sessionMetrics.set(sessionId, createInitialMetrics());
      }
      this.#accumulateSkillInvocation(
        this.#sessionMetrics.get(sessionId),
        skillName,
        success
      );
    }
    this.emit("update", {
      metrics: this.#metrics,
      lastPromptTokenCount: this.#lastPromptTokenCount
    });
  }
  getLastPromptTokenCount() {
    return this.#lastPromptTokenCount;
  }
  setLastPromptTokenCount(lastPromptTokenCount) {
    this.#lastPromptTokenCount = lastPromptTokenCount;
    this.emit("update", {
      metrics: this.#metrics,
      lastPromptTokenCount: this.#lastPromptTokenCount
    });
  }
  getSessionStartTime() {
    return this.#sessionStartTime;
  }
  getLastCachedContentTokenCount() {
    return this.#lastCachedContentTokenCount;
  }
  setLastCachedContentTokenCount(count) {
    this.#lastCachedContentTokenCount = count;
  }
  /**
   * Resets metrics to the initial state (used when resuming a session).
   */
  reset() {
    this.#metrics = createInitialMetrics();
    this.#sessionMetrics.clear();
    this.#closedSessions.clear();
    this.#lastPromptTokenCount = 0;
    this.#lastCachedContentTokenCount = 0;
    this.#sessionStartTime = /* @__PURE__ */ new Date();
    this.emit("update", {
      metrics: this.#metrics,
      lastPromptTokenCount: this.#lastPromptTokenCount
    });
  }
  resetSession(sessionId) {
    this.#sessionMetrics.set(sessionId, createInitialMetrics());
    this.#closedSessions.delete(sessionId);
  }
  removeSession(sessionId) {
    this.#sessionMetrics.delete(sessionId);
    this.#closedSessions.add(sessionId);
    if (this.#closedSessions.size > _UiTelemetryService.#MAX_CLOSED_SESSIONS) {
      const oldest = this.#closedSessions.values().next().value;
      if (oldest) this.#closedSessions.delete(oldest);
    }
  }
  #accumulateEvent(metrics2, event) {
    switch (event["event.name"]) {
      case EVENT_API_RESPONSE:
        this.#accumulateApiResponse(metrics2, event);
        return true;
      case EVENT_API_ERROR:
        this.#accumulateApiError(metrics2, event);
        return true;
      case EVENT_TOOL_CALL:
        this.#accumulateToolCall(metrics2, event);
        return true;
      default:
        return false;
    }
  }
  #accumulateApiResponse(metrics2, event) {
    const modelMetrics = this.#getOrCreateModelMetrics(metrics2, event.model);
    const sourceMetrics = this.#getOrCreateSourceMetrics(
      modelMetrics,
      event.subagent_name ?? MAIN_SOURCE
    );
    for (const bucket of [modelMetrics, sourceMetrics]) {
      bucket.api.totalRequests++;
      bucket.api.totalLatencyMs += event.duration_ms;
      bucket.tokens.prompt += event.input_token_count;
      bucket.tokens.candidates += event.output_token_count;
      bucket.tokens.total += event.total_token_count;
      bucket.tokens.cached += event.cached_content_token_count;
      bucket.tokens.thoughts += event.thoughts_token_count;
    }
  }
  #accumulateApiError(metrics2, event) {
    const modelMetrics = this.#getOrCreateModelMetrics(metrics2, event.model);
    const sourceMetrics = this.#getOrCreateSourceMetrics(
      modelMetrics,
      event.subagent_name ?? MAIN_SOURCE
    );
    for (const bucket of [modelMetrics, sourceMetrics]) {
      bucket.api.totalRequests++;
      bucket.api.totalErrors++;
      bucket.api.totalLatencyMs += event.duration_ms;
    }
  }
  #accumulateToolCall(metrics2, event) {
    const { tools, files } = metrics2;
    tools.totalCalls++;
    tools.totalDurationMs += event.duration_ms;
    if (event.success) {
      tools.totalSuccess++;
    } else {
      tools.totalFail++;
    }
    if (!tools.byName[event.function_name]) {
      tools.byName[event.function_name] = {
        count: 0,
        success: 0,
        fail: 0,
        durationMs: 0,
        decisions: {
          ["accept" /* ACCEPT */]: 0,
          ["reject" /* REJECT */]: 0,
          ["modify" /* MODIFY */]: 0,
          ["auto_accept" /* AUTO_ACCEPT */]: 0
        }
      };
    }
    const toolStats = tools.byName[event.function_name];
    toolStats.count++;
    toolStats.durationMs += event.duration_ms;
    if (event.success) {
      toolStats.success++;
    } else {
      toolStats.fail++;
    }
    if (event.decision) {
      tools.totalDecisions[event.decision]++;
      toolStats.decisions[event.decision]++;
    }
    if (event.metadata) {
      if (event.metadata["model_added_lines"] !== void 0) {
        files.totalLinesAdded += event.metadata["model_added_lines"];
      }
      if (event.metadata["model_removed_lines"] !== void 0) {
        files.totalLinesRemoved += event.metadata["model_removed_lines"];
      }
    }
  }
  #accumulateSkillInvocation(metrics2, skillName, success) {
    const skills = metrics2.skills ?? createInitialSkillMetrics();
    metrics2.skills = skills;
    skills.totalCalls++;
    if (success) {
      skills.totalSuccess++;
    } else {
      skills.totalFail++;
    }
    if (!Object.prototype.hasOwnProperty.call(skills.byName, skillName)) {
      Object.defineProperty(skills.byName, skillName, {
        value: {
          count: 0,
          success: 0,
          fail: 0
        },
        enumerable: true,
        configurable: true,
        writable: true
      });
    }
    const skillStats = skills.byName[skillName];
    if (!skillStats) {
      return;
    }
    skillStats.count++;
    if (success) {
      skillStats.success++;
    } else {
      skillStats.fail++;
    }
  }
  #getOrCreateModelMetrics(metrics2, modelName) {
    if (!metrics2.models[modelName]) {
      metrics2.models[modelName] = createInitialModelMetrics();
    }
    return metrics2.models[modelName];
  }
  #getOrCreateSourceMetrics(modelMetrics, source) {
    if (!modelMetrics.bySource[source]) {
      modelMetrics.bySource[source] = createInitialModelMetricsCore();
    }
    return modelMetrics.bySource[source];
  }
};
var uiTelemetryService = new UiTelemetryService();

// packages/core/src/telemetry/daemon-tracing.ts
init_esbuild_shims();
init_esm();
var import_api_logs = __toESM(require_src2(), 1);
import { createHash as createHash3 } from "node:crypto";
var DAEMON_TRACEPARENT_META_KEY = "qwen.telemetry.traceparent";
var DAEMON_TRACESTATE_META_KEY = "qwen.telemetry.tracestate";
var SPAN_DAEMON_REQUEST = "qwen-code.daemon.request";
var SPAN_DAEMON_BRIDGE = "qwen-code.daemon.bridge";
var EVENT_DAEMON_ERROR = "qwen-code.daemon.error";
function errorMessage(error) {
  if (error instanceof Error) return error.message;
  return String(error);
}
__name(errorMessage, "errorMessage");
function errorType(error) {
  if (error instanceof Error) return error.name || "Error";
  return typeof error;
}
__name(errorType, "errorType");
var INVALID_TRACE_ID = "0".repeat(32);
var INVALID_SPAN_ID = "0".repeat(16);
function stripReservedTraceMeta(meta) {
  if (!meta || typeof meta !== "object" || Array.isArray(meta)) return {};
  const record = meta;
  if (!(DAEMON_TRACEPARENT_META_KEY in record) && !(DAEMON_TRACESTATE_META_KEY in record)) {
    return { ...record };
  }
  const out = { ...record };
  delete out[DAEMON_TRACEPARENT_META_KEY];
  delete out[DAEMON_TRACESTATE_META_KEY];
  return out;
}
__name(stripReservedTraceMeta, "stripReservedTraceMeta");
function hashDaemonWorkspace(workspace) {
  return createHash3("sha256").update(workspace).digest("hex").slice(0, 16);
}
__name(hashDaemonWorkspace, "hashDaemonWorkspace");
async function withDaemonSpan(name, attributes, fn, options = {}) {
  if (!isTelemetrySdkInitialized()) {
    return await fn(void 0);
  }
  const autoOkOnSuccess = options.autoOkOnSuccess ?? true;
  const tracer2 = trace.getTracer(SERVICE_NAME);
  return await tracer2.startActiveSpan(
    name,
    { kind: SpanKind.INTERNAL, attributes },
    async (span) => {
      try {
        const result = await fn(span);
        if (autoOkOnSuccess) {
          span.setStatus({ code: SpanStatusCode.OK });
        }
        return result;
      } catch (error) {
        recordDaemonError(span, error);
        throw error;
      } finally {
        span.end();
      }
    }
  );
}
__name(withDaemonSpan, "withDaemonSpan");
async function withDaemonRequestSpan(options, fn) {
  return await withDaemonSpan(
    SPAN_DAEMON_REQUEST,
    {
      "http.request.method": options.method,
      "http.route": options.route,
      "qwen-code.daemon.operation": "http_request",
      ...options.workspaceHash ? { "qwen-code.workspace.hash": options.workspaceHash } : {},
      ...options.sessionId ? { "session.id": options.sessionId } : {},
      ...options.clientId ? { "qwen-code.client_id": options.clientId } : {},
      ...options.permissionRequestId ? {
        "qwen-code.daemon.permission.request_id": options.permissionRequestId
      } : {}
    },
    fn,
    { autoOkOnSuccess: false }
  );
}
__name(withDaemonRequestSpan, "withDaemonRequestSpan");
async function withDaemonBridgeSpan(operation, attributes, fn) {
  return await withDaemonSpan(
    SPAN_DAEMON_BRIDGE,
    {
      "qwen-code.daemon.operation": operation,
      ...attributes
    },
    async () => await fn()
  );
}
__name(withDaemonBridgeSpan, "withDaemonBridgeSpan");
function recordDaemonHttpResponse(span, statusCode) {
  try {
    span?.setAttribute("http.response.status_code", statusCode);
  } catch {
  }
}
__name(recordDaemonHttpResponse, "recordDaemonHttpResponse");
function addDaemonRequestAttribute(key, value) {
  try {
    trace.getSpan(context.active())?.setAttribute(key, value);
  } catch {
  }
}
__name(addDaemonRequestAttribute, "addDaemonRequestAttribute");
function recordDaemonError(span, error, attributes = {}) {
  const target = span ?? trace.getSpan(context.active());
  if (!target) return;
  try {
    const message = truncateSpanError(errorMessage(error));
    target.recordException(error instanceof Error ? error : new Error(message));
    target.setAttributes({
      "error.type": errorType(error),
      "error.message": message,
      ...attributes
    });
    target.setStatus({ code: SpanStatusCode.ERROR, message });
  } catch {
  }
}
__name(recordDaemonError, "recordDaemonError");
function emitDaemonLog(body, attributes = {}, options) {
  if (!isTelemetrySdkInitialized()) return;
  try {
    import_api_logs.logs.getLogger(SERVICE_NAME).emit({
      body,
      timestamp: /* @__PURE__ */ new Date(),
      attributes: {
        "event.name": options?.eventName ?? EVENT_DAEMON_ERROR,
        ...attributes
      },
      ...options?.severityNumber != null ? { severityNumber: options.severityNumber } : {}
    });
  } catch {
  }
}
__name(emitDaemonLog, "emitDaemonLog");
function captureDaemonTelemetryContext() {
  return { context: context.active() };
}
__name(captureDaemonTelemetryContext, "captureDaemonTelemetryContext");
async function runWithDaemonTelemetryContext(captured, fn) {
  const ctx = captured && typeof captured === "object" && "context" in captured && captured.context ? captured.context : void 0;
  if (!ctx) return await fn();
  return await context.with(ctx, fn);
}
__name(runWithDaemonTelemetryContext, "runWithDaemonTelemetryContext");
function injectDaemonTraceContext(request4) {
  const currentMeta = request4._meta;
  const nextMeta = stripReservedTraceMeta(currentMeta);
  try {
    const ctx = getActiveSpanTraceContext();
    if (ctx) {
      nextMeta[DAEMON_TRACEPARENT_META_KEY] = formatTraceparent(ctx);
    }
  } catch {
  }
  if (!currentMeta && !nextMeta[DAEMON_TRACEPARENT_META_KEY]) {
    return request4;
  }
  return {
    ...request4,
    _meta: nextMeta
  };
}
__name(injectDaemonTraceContext, "injectDaemonTraceContext");
function extractDaemonTraceContext(source) {
  const meta = source?._meta;
  if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
    return void 0;
  }
  const record = meta;
  const traceparent = record[DAEMON_TRACEPARENT_META_KEY];
  if (typeof traceparent !== "string" || traceparent.length === 0) {
    return void 0;
  }
  const carrier = { traceparent };
  const tracestate = record[DAEMON_TRACESTATE_META_KEY];
  if (typeof tracestate === "string" && tracestate.length > 0) {
    carrier["tracestate"] = tracestate;
  }
  const extracted = propagation.extract(ROOT_CONTEXT, carrier);
  if (trace.getSpanContext(extracted)) return extracted;
  const parts = traceparent.split("-");
  const traceId = parts[1];
  const spanId = parts[2];
  const flags = parts[3];
  if (parts[0] !== "00" || !traceId?.match(/^[0-9a-f]{32}$/) || !spanId?.match(/^[0-9a-f]{16}$/) || !flags?.match(/^[0-9a-f]{2}$/) || traceId === INVALID_TRACE_ID || spanId === INVALID_SPAN_ID) {
    return void 0;
  }
  return trace.setSpan(
    ROOT_CONTEXT,
    trace.wrapSpanContext({
      traceId,
      spanId,
      traceFlags: Number.parseInt(flags, 16),
      isRemote: true
    })
  );
}
__name(extractDaemonTraceContext, "extractDaemonTraceContext");
function createDaemonBridgeTelemetry() {
  return {
    captureContext: captureDaemonTelemetryContext,
    runWithContext: runWithDaemonTelemetryContext,
    withSpan: withDaemonBridgeSpan,
    event(name, attributes) {
      if (!isTelemetrySdkInitialized()) return;
      try {
        const activeSpan = trace.getSpan(context.active());
        if (activeSpan) {
          activeSpan.addEvent(name, attributes);
          return;
        }
        const span = trace.getTracer(SERVICE_NAME).startSpan(SPAN_DAEMON_BRIDGE, {
          kind: SpanKind.INTERNAL,
          attributes: {
            "event.name": name,
            "qwen-code.daemon.operation": `event.${name}`,
            ...attributes
          }
        });
        span.addEvent(name, attributes);
        span.setStatus({ code: SpanStatusCode.OK });
        span.end();
      } catch {
      }
    },
    injectPromptContext: injectDaemonTraceContext
  };
}
__name(createDaemonBridgeTelemetry, "createDaemonBridgeTelemetry");

// packages/core/src/telemetry/daemon-metrics.ts
init_esbuild_shims();
init_esm();
var DAEMON_HTTP_REQUEST_COUNT = `${SERVICE_NAME}.daemon.http.request.count`;
var DAEMON_HTTP_REQUEST_DURATION = `${SERVICE_NAME}.daemon.http.request.duration`;
var DAEMON_SESSION_ACTIVE = `${SERVICE_NAME}.daemon.session.active`;
var DAEMON_SESSION_LIFECYCLE = `${SERVICE_NAME}.daemon.session.lifecycle`;
var DAEMON_CHANNEL_LIFECYCLE = `${SERVICE_NAME}.daemon.channel.lifecycle`;
var DAEMON_PROMPT_QUEUE_WAIT = `${SERVICE_NAME}.daemon.prompt.queue_wait`;
var DAEMON_PROMPT_DURATION = `${SERVICE_NAME}.daemon.prompt.duration`;
var DAEMON_BRIDGE_ERROR_COUNT = `${SERVICE_NAME}.daemon.bridge.error.count`;
var DAEMON_CANCEL_COUNT = `${SERVICE_NAME}.daemon.cancel.count`;
var DAEMON_PIPE_MESSAGE_BYTES = `${SERVICE_NAME}.daemon.pipe.message_bytes`;
var DAEMON_SSE_ACTIVE = `${SERVICE_NAME}.daemon.sse.active`;
var DAEMON_PROCESS_HEAP_USED = `${SERVICE_NAME}.daemon.process.heap_used`;
var KNOWN_ERROR_TYPES = /* @__PURE__ */ new Set([
  "SessionNotFoundError",
  "WorkspaceMismatchError",
  "InvalidClientIdError",
  "SessionLimitExceededError",
  "RestoreInProgressError",
  "InvalidSessionScopeError",
  "TrustGateError",
  "WorkspaceInitConflictError",
  "WorkspaceInitPathEscapeError",
  "WorkspaceInitSymlinkError",
  "WorkspaceInitRaceError",
  "McpServerNotFoundError",
  "McpServerRestartFailedError",
  "PromptDeadlineExceededError",
  "InvalidSessionMetadataError",
  "SubscriberLimitExceededError",
  "BridgeChannelClosedError",
  "BridgeTimeoutError",
  "PermissionForbiddenError"
]);
var initialized = false;
var httpRequestCounter;
var httpRequestDurationHistogram;
var sessionLifecycleCounter;
var channelLifecycleCounter;
var promptQueueWaitHistogram;
var promptDurationHistogram;
var bridgeErrorCounter;
var cancelCounter;
var pipeMessageBytesHistogram;
function normalizeErrorType(err) {
  const name = err instanceof Error ? err.name : typeof err;
  return KNOWN_ERROR_TYPES.has(name) ? name : "unknown";
}
__name(normalizeErrorType, "normalizeErrorType");
function initializeDaemonMetrics() {
  if (initialized) return;
  const meter = getMeter();
  if (!meter) return;
  httpRequestCounter = meter.createCounter(DAEMON_HTTP_REQUEST_COUNT, {
    description: "Daemon HTTP request count by route and status class.",
    valueType: ValueType.INT
  });
  httpRequestDurationHistogram = meter.createHistogram(
    DAEMON_HTTP_REQUEST_DURATION,
    {
      description: "Daemon HTTP request duration in milliseconds.",
      unit: "ms",
      valueType: ValueType.DOUBLE,
      advice: {
        explicitBucketBoundaries: [
          1,
          2,
          5,
          10,
          25,
          50,
          100,
          250,
          500,
          1e3,
          2500,
          5e3,
          1e4,
          3e4
        ]
      }
    }
  );
  sessionLifecycleCounter = meter.createCounter(DAEMON_SESSION_LIFECYCLE, {
    description: "Daemon session lifecycle events (spawn, close, die).",
    valueType: ValueType.INT
  });
  channelLifecycleCounter = meter.createCounter(DAEMON_CHANNEL_LIFECYCLE, {
    description: "Daemon ACP channel lifecycle events (spawn, exit).",
    valueType: ValueType.INT
  });
  promptQueueWaitHistogram = meter.createHistogram(DAEMON_PROMPT_QUEUE_WAIT, {
    description: "Time a prompt waited in the per-session FIFO queue.",
    unit: "ms",
    valueType: ValueType.DOUBLE,
    advice: {
      explicitBucketBoundaries: [
        1,
        5,
        10,
        50,
        100,
        500,
        1e3,
        5e3,
        1e4,
        3e4,
        6e4
      ]
    }
  });
  promptDurationHistogram = meter.createHistogram(DAEMON_PROMPT_DURATION, {
    description: "End-to-end prompt duration from dispatch to completion.",
    unit: "ms",
    valueType: ValueType.DOUBLE,
    advice: {
      explicitBucketBoundaries: [
        100,
        500,
        1e3,
        2500,
        5e3,
        1e4,
        3e4,
        6e4,
        12e4,
        3e5,
        6e5
      ]
    }
  });
  bridgeErrorCounter = meter.createCounter(DAEMON_BRIDGE_ERROR_COUNT, {
    description: "Daemon bridge error count by normalized error type.",
    valueType: ValueType.INT
  });
  cancelCounter = meter.createCounter(DAEMON_CANCEL_COUNT, {
    description: "Daemon cancel request count.",
    valueType: ValueType.INT
  });
  pipeMessageBytesHistogram = meter.createHistogram(DAEMON_PIPE_MESSAGE_BYTES, {
    description: "Daemon ACP child pipe message payload size in bytes.",
    unit: "By",
    valueType: ValueType.INT,
    advice: {
      explicitBucketBoundaries: [
        256,
        1024,
        4096,
        16384,
        65536,
        262144,
        1048576,
        4194304,
        16777216
      ]
    }
  });
  initialized = true;
}
__name(initializeDaemonMetrics, "initializeDaemonMetrics");
var gaugesRegistered = false;
function registerDaemonGaugeCallbacks(callbacks) {
  if (gaugesRegistered) return;
  const meter = getMeter();
  if (!meter) return;
  meter.createObservableGauge(DAEMON_SESSION_ACTIVE, {
    description: "Current number of active daemon sessions.",
    valueType: ValueType.INT
  }).addCallback((result) => {
    try {
      result.observe(callbacks.sessionCount());
    } catch {
    }
  });
  meter.createObservableGauge(DAEMON_SSE_ACTIVE, {
    description: "Current number of active SSE connections.",
    valueType: ValueType.INT
  }).addCallback((result) => {
    try {
      result.observe(callbacks.sseCount());
    } catch {
    }
  });
  meter.createObservableGauge(DAEMON_PROCESS_HEAP_USED, {
    description: "Daemon process heap memory usage in bytes.",
    unit: "bytes",
    valueType: ValueType.INT
  }).addCallback((result) => {
    try {
      result.observe(callbacks.heapUsed());
    } catch {
    }
  });
  gaugesRegistered = true;
}
__name(registerDaemonGaugeCallbacks, "registerDaemonGaugeCallbacks");
function recordDaemonHttpRequest(durationMs, route, statusCode) {
  if (!initialized) return;
  const statusClass = `${Math.floor(statusCode / 100)}xx`;
  httpRequestCounter?.add(1, { route, status_class: statusClass });
  httpRequestDurationHistogram?.record(durationMs, { route });
}
__name(recordDaemonHttpRequest, "recordDaemonHttpRequest");
function recordDaemonSessionLifecycle(action) {
  if (!initialized) return;
  sessionLifecycleCounter?.add(1, { action });
}
__name(recordDaemonSessionLifecycle, "recordDaemonSessionLifecycle");
function recordDaemonChannelLifecycle(action, expected) {
  if (!initialized) return;
  channelLifecycleCounter?.add(1, {
    action,
    ...expected != null ? { expected } : {}
  });
}
__name(recordDaemonChannelLifecycle, "recordDaemonChannelLifecycle");
function recordDaemonPromptQueueWait(durationMs) {
  if (!initialized) return;
  promptQueueWaitHistogram?.record(durationMs);
}
__name(recordDaemonPromptQueueWait, "recordDaemonPromptQueueWait");
function recordDaemonPromptDuration(durationMs) {
  if (!initialized) return;
  promptDurationHistogram?.record(durationMs);
}
__name(recordDaemonPromptDuration, "recordDaemonPromptDuration");
function recordDaemonBridgeError(err) {
  if (!initialized) return;
  bridgeErrorCounter?.add(1, { error_type: normalizeErrorType(err) });
}
__name(recordDaemonBridgeError, "recordDaemonBridgeError");
function recordDaemonCancel() {
  if (!initialized) return;
  cancelCounter?.add(1);
}
__name(recordDaemonCancel, "recordDaemonCancel");
function recordDaemonPipeMessage(direction, bytes) {
  if (!initialized) return;
  pipeMessageBytesHistogram?.record(bytes, { direction });
}
__name(recordDaemonPipeMessage, "recordDaemonPipeMessage");

// packages/core/src/telemetry/event-loop-lag.ts
init_esbuild_shims();
import { monitorEventLoopDelay } from "node:perf_hooks";
var DEFAULT_RESOLUTION_MS = 20;
var DEFAULT_STALL_THRESHOLD_MS = 1e3;
var NS_PER_MS = 1e6;
function startEventLoopLagMonitor(options = {}) {
  const resolutionMs = positiveFiniteOrDefault(
    options.resolutionMs,
    DEFAULT_RESOLUTION_MS
  );
  const stallThresholdMs = positiveFiniteOrDefault(
    options.stallThresholdMs,
    DEFAULT_STALL_THRESHOLD_MS
  );
  const histogram = monitorEventLoopDelay({ resolution: resolutionMs });
  histogram.enable();
  let disposed = false;
  let lastReportedMaxMs = 0;
  const readMaxMs = /* @__PURE__ */ __name(() => nsToMs(histogram.max), "readMaxMs");
  const checkForNewMaxStall = /* @__PURE__ */ __name(() => {
    if (disposed || !options.onNewMaxStall) return;
    const maxMs = readMaxMs();
    if (maxMs >= stallThresholdMs && maxMs > lastReportedMaxMs) {
      lastReportedMaxMs = maxMs;
      try {
        options.onNewMaxStall(maxMs);
      } catch {
      }
    }
  }, "checkForNewMaxStall");
  const interval = options.onNewMaxStall !== void 0 ? setInterval(checkForNewMaxStall, resolutionMs) : void 0;
  interval?.unref();
  return {
    snapshot() {
      return {
        meanMs: nsToMs(histogram.mean),
        p50Ms: nsToMs(histogram.percentile(50)),
        p99Ms: nsToMs(histogram.percentile(99)),
        maxMs: readMaxMs()
      };
    },
    dispose() {
      if (disposed) return;
      disposed = true;
      if (interval) {
        clearInterval(interval);
      }
      histogram.disable();
    }
  };
}
__name(startEventLoopLagMonitor, "startEventLoopLagMonitor");
function nsToMs(value) {
  return Number.isFinite(value) ? value / NS_PER_MS : 0;
}
__name(nsToMs, "nsToMs");
function positiveFiniteOrDefault(value, fallback) {
  return value !== void 0 && Number.isFinite(value) && value > 0 ? value : fallback;
}
__name(positiveFiniteOrDefault, "positiveFiniteOrDefault");

// packages/core/src/telemetry/event-loop-lag-metrics.ts
init_esbuild_shims();
init_esm();
var DAEMON_EVENT_LOOP_LAG = `${SERVICE_NAME}.daemon.event_loop.lag`;
var ACP_EVENT_LOOP_LAG = `${SERVICE_NAME}.acp.event_loop.lag`;
var daemonGaugeRegistered = false;
var acpGaugeRegistered = false;
function registerDaemonEventLoopLagGauge(read2) {
  if (daemonGaugeRegistered) return;
  daemonGaugeRegistered = registerEventLoopLagGauge(
    DAEMON_EVENT_LOOP_LAG,
    read2
  );
}
__name(registerDaemonEventLoopLagGauge, "registerDaemonEventLoopLagGauge");
function registerAcpEventLoopLagGauge(read2) {
  if (acpGaugeRegistered) return;
  acpGaugeRegistered = registerEventLoopLagGauge(ACP_EVENT_LOOP_LAG, read2);
}
__name(registerAcpEventLoopLagGauge, "registerAcpEventLoopLagGauge");
function registerEventLoopLagGauge(name, read2) {
  const meter = getMeter();
  if (!meter) return false;
  meter.createObservableGauge(name, {
    description: "Event loop lag in milliseconds.",
    unit: "ms",
    valueType: ValueType.DOUBLE
  }).addCallback((result) => {
    try {
      const snapshot = read2();
      result.observe(snapshot.meanMs, { stat: "mean" });
      result.observe(snapshot.p50Ms, { stat: "p50" });
      result.observe(snapshot.p99Ms, { stat: "p99" });
      result.observe(snapshot.maxMs, { stat: "max" });
    } catch {
    }
  });
  return true;
}
__name(registerEventLoopLagGauge, "registerEventLoopLagGauge");

// packages/core/src/telemetry/index.ts
var TelemetryTarget = /* @__PURE__ */ ((TelemetryTarget2) => {
  TelemetryTarget2["GCP"] = "gcp";
  TelemetryTarget2["LOCAL"] = "local";
  return TelemetryTarget2;
})(TelemetryTarget || {});
var DEFAULT_TELEMETRY_TARGET = "local" /* LOCAL */;
var DEFAULT_OTLP_ENDPOINT = "http://localhost:4317";

// packages/core/src/core/loggingContentGenerator/streamContentDetection.ts
init_esbuild_shims();
function hasUserVisibleContent(chunk) {
  const parts = chunk.candidates?.[0]?.content?.parts;
  if (!parts || parts.length === 0) return false;
  return parts.some(isUserVisiblePart);
}
__name(hasUserVisibleContent, "hasUserVisibleContent");
function isUserVisiblePart(part) {
  if (part === null || typeof part !== "object") return false;
  const p = part;
  if (typeof p.text === "string" && p.text.length > 0) return true;
  if (p.functionCall !== void 0) return true;
  if (p.inlineData !== void 0) return true;
  if (p.executableCode !== void 0) return true;
  if (p.thought === true) return true;
  return false;
}
__name(isUserVisiblePart, "isUserVisiblePart");

// packages/core/src/utils/retryContext.ts
init_esbuild_shims();
import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
var retryContext = new AsyncLocalStorage4();

// packages/core/src/core/loggingContentGenerator/loggingContentGenerator.ts
function snapshotRetryMetadata() {
  const ctx = retryContext.getStore();
  return {
    attempt: ctx?.attempt ?? 1,
    requestSetupMs: ctx?.requestSetupMs,
    retryTotalDelayMs: ctx?.retryTotalDelayMs
  };
}
__name(snapshotRetryMetadata, "snapshotRetryMetadata");
var debugLogger10 = createDebugLogger("LOGGING_CONTENT_GENERATOR");
var MAX_RESPONSE_TEXT_LENGTH = 4096;
var RESPONSE_TEXT_TRUNCATION_SUFFIX = "...[truncated]";
var LoggingContentGenerator = class {
  constructor(wrapped, config, generatorConfig) {
    this.wrapped = wrapped;
    this.config = config;
    this.modalities = generatorConfig.modalities;
    this.splitToolMedia = generatorConfig.splitToolMedia;
    this.toolResultContentFormat = generatorConfig.toolResultContentFormat;
    this.generatorAuthType = generatorConfig.authType;
    if (generatorConfig.enableOpenAILogging) {
      this.openaiLogger = new OpenAILogger(
        generatorConfig.openAILoggingDir,
        config.getWorkingDir()
      );
      this.schemaCompliance = generatorConfig.schemaCompliance;
    }
  }
  static {
    __name(this, "LoggingContentGenerator");
  }
  openaiLogger;
  schemaCompliance;
  modalities;
  splitToolMedia;
  toolResultContentFormat;
  generatorAuthType;
  getWrapped() {
    return this.wrapped;
  }
  logApiRequest(contents, model, promptId) {
    const requestText = JSON.stringify(contents);
    logApiRequest(
      this.config,
      new ApiRequestEvent(
        model,
        promptId,
        requestText,
        subagentNameContext.getStore()
      )
    );
  }
  _logApiResponse(responseId, durationMs, model, prompt_id, usageMetadata, responseText) {
    logApiResponse(
      this.config,
      new ApiResponseEvent(
        responseId,
        model,
        durationMs,
        prompt_id,
        this.generatorAuthType,
        usageMetadata,
        responseText,
        subagentNameContext.getStore()
      )
    );
  }
  _logApiError(responseId, durationMs, error, model, prompt_id) {
    const errorMessage2 = getErrorMessage(error);
    const errorType2 = getErrorType(error);
    const errorResponseId = error?.requestID || error?.request_id || responseId;
    const errorStatus = getErrorStatus(error);
    logApiError(
      this.config,
      new ApiErrorEvent({
        responseId: errorResponseId,
        model,
        durationMs,
        promptId: prompt_id,
        authType: this.generatorAuthType,
        errorMessage: errorMessage2,
        errorType: errorType2,
        statusCode: errorStatus,
        subagentName: subagentNameContext.getStore()
      })
    );
  }
  safelyLogApiError(responseId, durationMs, error, model, prompt_id) {
    try {
      this._logApiError(responseId, durationMs, error, model, prompt_id);
    } catch (loggingError) {
      debugLogger10.warn("Failed to log API error:", loggingError);
    }
  }
  safelyLogApiResponse(responseId, durationMs, model, prompt_id, usageMetadata, responseText) {
    try {
      this._logApiResponse(
        responseId,
        durationMs,
        model,
        prompt_id,
        usageMetadata,
        responseText
      );
    } catch (loggingError) {
      debugLogger10.warn("Failed to log API response:", loggingError);
    }
  }
  async generateContent(req, userPromptId) {
    const retrySnapshot = snapshotRetryMetadata();
    const llmSpan = startLLMRequestSpan(req.model, userPromptId);
    try {
      llmSpan.setAttribute("llm_request.stream", false);
    } catch {
    }
    const spanContext = trace.setSpan(context.active(), llmSpan);
    const startTime = Date.now();
    const isInternal = isInternalPromptId(userPromptId);
    const session = this.startCaptureSession();
    try {
      runtimeDiagnostics.recordGenerateContentRequest(req, {
        stream: false,
        source: "generateContent"
      });
      if (!isInternal) {
        addSystemPromptAttributes(
          this.config,
          llmSpan,
          req.config?.systemInstruction
        );
        addToolSchemaAttributes(
          this.config,
          llmSpan,
          req.config?.tools
        );
      }
      const response = await context.with(spanContext, async () => {
        if (!isInternal) {
          this.logApiRequest(
            this.toContents(req.contents),
            req.model,
            userPromptId
          );
        }
        const result = await session.wrap(
          () => this.wrapped.generateContent(req, userPromptId)
        );
        const durationMs = Date.now() - startTime;
        const shouldCollectSensitiveSpanAttributes = !isInternal && this.shouldCollectSensitiveSpanAttributes();
        const modelOutput = shouldCollectSensitiveSpanAttributes ? this.extractResponseTextForSensitiveSpan(
          result,
          this.config.getTelemetrySensitiveSpanAttributeMaxLength()
        ) : void 0;
        const responseText = isInternal ? void 0 : this.extractResponseText(result, MAX_RESPONSE_TEXT_LENGTH);
        if (shouldCollectSensitiveSpanAttributes) {
          this.safelyAddModelOutputAttributes(llmSpan, modelOutput);
        }
        this.safelyLogApiResponse(
          result.responseId ?? "",
          durationMs,
          result.modelVersion || req.model,
          userPromptId,
          result.usageMetadata,
          responseText
        );
        try {
          await this.safelyLogOpenAIInteraction(
            await session.resolve(req),
            result,
            void 0,
            userPromptId
          );
        } catch (loggingError) {
          debugLogger10.warn("Failed to log OpenAI interaction:", loggingError);
        }
        return result;
      });
      endLLMRequestSpan(llmSpan, {
        success: true,
        inputTokens: response.usageMetadata?.promptTokenCount,
        outputTokens: response.usageMetadata?.candidatesTokenCount,
        cachedInputTokens: response.usageMetadata?.cachedContentTokenCount,
        durationMs: Date.now() - startTime,
        responseId: response.responseId || void 0,
        finishReason: response.candidates?.[0]?.finishReason || void 0,
        thoughtsTokenCount: response.usageMetadata?.thoughtsTokenCount,
        subagentName: subagentNameContext.getStore() || void 0,
        ...retrySnapshot,
        config: this.config
      });
      return response;
    } catch (error) {
      const durationMs = Date.now() - startTime;
      const aborted = req.config?.abortSignal?.aborted ?? false;
      endLLMRequestSpan(llmSpan, {
        success: false,
        durationMs,
        error: aborted ? API_CALL_ABORTED_SPAN_STATUS_MESSAGE : API_CALL_FAILED_SPAN_STATUS_MESSAGE,
        errorType: getErrorType(error),
        errorStatusCode: getErrorStatus(error),
        subagentName: subagentNameContext.getStore() || void 0,
        ...retrySnapshot,
        config: this.config
      });
      await context.with(spanContext, async () => {
        this.safelyLogApiError("", durationMs, error, req.model, userPromptId);
        try {
          await this.safelyLogOpenAIInteraction(
            await session.resolve(req),
            void 0,
            error,
            userPromptId
          );
        } catch (loggingError) {
          debugLogger10.warn("Failed to log OpenAI interaction:", loggingError);
        }
      });
      throw error;
    }
  }
  async generateContentStream(req, userPromptId) {
    const retrySnapshot = snapshotRetryMetadata();
    const llmSpan = startLLMRequestSpan(req.model, userPromptId);
    try {
      llmSpan.setAttribute("llm_request.stream", true);
    } catch {
    }
    const spanContext = trace.setSpan(context.active(), llmSpan);
    const startTime = Date.now();
    const isInternal = isInternalPromptId(userPromptId);
    const session = this.startCaptureSession();
    let stream;
    try {
      runtimeDiagnostics.recordGenerateContentRequest(req, {
        stream: true,
        source: "generateContentStream"
      });
      if (!isInternal) {
        addSystemPromptAttributes(
          this.config,
          llmSpan,
          req.config?.systemInstruction
        );
        addToolSchemaAttributes(
          this.config,
          llmSpan,
          req.config?.tools
        );
      }
      stream = await context.with(spanContext, async () => {
        if (!isInternal) {
          this.logApiRequest(
            this.toContents(req.contents),
            req.model,
            userPromptId
          );
        }
        return session.wrap(
          () => this.wrapped.generateContentStream(req, userPromptId)
        );
      });
    } catch (error) {
      const durationMs = Date.now() - startTime;
      context.with(
        spanContext,
        () => this.safelyLogApiError("", durationMs, error, req.model, userPromptId)
      );
      const aborted = req.config?.abortSignal?.aborted ?? false;
      endLLMRequestSpan(llmSpan, {
        success: false,
        durationMs,
        error: aborted ? API_CALL_ABORTED_SPAN_STATUS_MESSAGE : API_CALL_FAILED_SPAN_STATUS_MESSAGE,
        errorType: getErrorType(error),
        errorStatusCode: getErrorStatus(error),
        subagentName: subagentNameContext.getStore() || void 0,
        ...retrySnapshot,
        config: this.config
      });
      try {
        await this.safelyLogOpenAIInteraction(
          await session.resolve(req),
          void 0,
          error,
          userPromptId
        );
      } catch (loggingError) {
        debugLogger10.warn("Failed to log OpenAI interaction:", loggingError);
      }
      throw error;
    }
    let resolvedRequest;
    if (this.openaiLogger) {
      try {
        resolvedRequest = await session.resolve(req);
      } catch (loggingError) {
        debugLogger10.warn("Failed to resolve OpenAI request:", loggingError);
      }
    }
    return context.with(
      spanContext,
      () => this.loggingStreamWrapper(
        stream,
        startTime,
        userPromptId,
        req.model,
        resolvedRequest,
        llmSpan,
        spanContext,
        req.config?.abortSignal,
        retrySnapshot
      )
    );
  }
  startCaptureSession() {
    let captured;
    const skipCapture = !this.openaiLogger;
    return {
      wrap: /* @__PURE__ */ __name((fn) => skipCapture ? fn() : openaiRequestCaptureContext.run((built) => {
        captured = built;
      }, fn), "wrap"),
      resolve: /* @__PURE__ */ __name(async (req) => this.openaiLogger ? captured ?? await this.buildOpenAIRequestForLogging(req) : void 0, "resolve")
    };
  }
  async *loggingStreamWrapper(stream, startTime, userPromptId, model, openaiRequest, span, spanContext, abortSignal, retrySnapshot) {
    const isInternal = isInternalPromptId(userPromptId);
    const shouldCollectResponses = !isInternal || !!this.openaiLogger;
    const responses = [];
    let firstResponseId = "";
    let firstModelVersion = "";
    let lastUsageMetadata;
    let errorOccurred = false;
    let lastFinishReason;
    let lastError;
    const subagentName = subagentNameContext.getStore();
    let ttftMs;
    let spanEndedByTimeout = false;
    const runInSpan = /* @__PURE__ */ __name((fn) => spanContext ? context.with(spanContext, fn) : fn(), "runInSpan");
    const STREAM_IDLE_TIMEOUT_MS = 5 * 6e4;
    let spanEndTimeout;
    const resetSpanTimeout = span ? () => {
      if (spanEndedByTimeout) return;
      if (spanEndTimeout !== void 0) clearTimeout(spanEndTimeout);
      spanEndTimeout = setTimeout(() => {
        try {
          span.setAttribute("stream.timed_out", true);
        } catch {
        }
        endLLMRequestSpan(span, {
          success: false,
          durationMs: Date.now() - startTime,
          error: "Stream span timed out (idle)",
          responseId: firstResponseId || void 0,
          subagentName: subagentName || void 0,
          ...retrySnapshot,
          config: this.config
        });
        spanEndedByTimeout = true;
      }, STREAM_IDLE_TIMEOUT_MS);
      spanEndTimeout.unref();
    } : void 0;
    resetSpanTimeout?.();
    try {
      for await (const response of stream) {
        if (!firstResponseId && response.responseId) {
          firstResponseId = response.responseId;
        }
        if (!firstModelVersion && response.modelVersion) {
          firstModelVersion = response.modelVersion;
        }
        if (shouldCollectResponses) {
          responses.push(response);
        }
        if (response.usageMetadata) {
          lastUsageMetadata = response.usageMetadata;
        }
        const candidate = response.candidates?.[0];
        if (candidate?.finishReason) {
          lastFinishReason = candidate.finishReason;
        }
        if (ttftMs === void 0 && hasUserVisibleContent(response)) {
          ttftMs = Date.now() - startTime;
        }
        resetSpanTimeout?.();
        yield response;
      }
      if (spanEndTimeout !== void 0) {
        clearTimeout(spanEndTimeout);
        spanEndTimeout = void 0;
      }
      const durationMs = Date.now() - startTime;
      const consolidatedResponse = shouldCollectResponses ? this.consolidateGeminiResponsesForLogging(responses) : void 0;
      const shouldCollectSensitiveSpanAttributes = !isInternal && span !== void 0 && this.shouldCollectSensitiveSpanAttributes();
      const streamModelOutput = shouldCollectSensitiveSpanAttributes ? this.extractResponseTextForSensitiveSpan(
        consolidatedResponse,
        this.config.getTelemetrySensitiveSpanAttributeMaxLength()
      ) : void 0;
      const streamResponseText = isInternal ? void 0 : this.extractResponseText(
        consolidatedResponse,
        MAX_RESPONSE_TEXT_LENGTH
      );
      if (!spanEndedByTimeout) {
        runInSpan(
          () => this.safelyLogApiResponse(
            firstResponseId,
            durationMs,
            firstModelVersion || model,
            userPromptId,
            lastUsageMetadata,
            streamResponseText
          )
        );
        if (shouldCollectSensitiveSpanAttributes && span) {
          this.safelyAddModelOutputAttributes(span, streamModelOutput);
        }
        await runInSpan(
          () => this.safelyLogOpenAIInteraction(
            openaiRequest,
            consolidatedResponse,
            void 0,
            userPromptId
          )
        );
      }
    } catch (error) {
      errorOccurred = true;
      lastError = error;
      if (!spanEndedByTimeout) {
        const durationMs = Date.now() - startTime;
        runInSpan(
          () => this.safelyLogApiError(
            firstResponseId,
            durationMs,
            error,
            firstModelVersion || model,
            userPromptId
          )
        );
        await runInSpan(
          () => this.safelyLogOpenAIInteraction(
            openaiRequest,
            void 0,
            error,
            userPromptId
          )
        );
      }
      throw error;
    } finally {
      if (spanEndTimeout !== void 0) {
        clearTimeout(spanEndTimeout);
      }
      if (span && !spanEndedByTimeout) {
        const aborted = abortSignal?.aborted ?? false;
        endLLMRequestSpan(span, {
          success: !errorOccurred,
          inputTokens: lastUsageMetadata?.promptTokenCount,
          outputTokens: lastUsageMetadata?.candidatesTokenCount,
          cachedInputTokens: lastUsageMetadata?.cachedContentTokenCount,
          ttftMs,
          durationMs: Date.now() - startTime,
          error: errorOccurred ? aborted ? API_CALL_ABORTED_SPAN_STATUS_MESSAGE : API_CALL_FAILED_SPAN_STATUS_MESSAGE : void 0,
          responseId: firstResponseId || void 0,
          finishReason: lastFinishReason,
          thoughtsTokenCount: lastUsageMetadata?.thoughtsTokenCount,
          subagentName: subagentName || void 0,
          errorType: lastError ? getErrorType(lastError) : void 0,
          errorStatusCode: lastError ? getErrorStatus(lastError) : void 0,
          ...retrySnapshot,
          config: this.config
        });
      }
    }
  }
  async buildOpenAIRequestForLogging(request4) {
    if (!this.openaiLogger) {
      return void 0;
    }
    const requestContext = this.createLoggingRequestContext(request4.model);
    const messages = OpenAIContentConverter.convertGeminiRequestToOpenAI(
      request4,
      requestContext,
      {
        cleanOrphanToolCalls: false
      }
    );
    const openaiRequest = {
      model: request4.model,
      messages
    };
    if (request4.config?.tools) {
      openaiRequest.tools = await OpenAIContentConverter.convertGeminiToolsToOpenAI(
        request4.config.tools,
        this.schemaCompliance ?? "auto"
      );
    }
    if (request4.config?.temperature !== void 0) {
      openaiRequest.temperature = request4.config.temperature;
    }
    if (request4.config?.topP !== void 0) {
      openaiRequest.top_p = request4.config.topP;
    }
    if (request4.config?.maxOutputTokens !== void 0) {
      openaiRequest.max_tokens = request4.config.maxOutputTokens;
    }
    if (request4.config?.presencePenalty !== void 0) {
      openaiRequest.presence_penalty = request4.config.presencePenalty;
    }
    if (request4.config?.frequencyPenalty !== void 0) {
      openaiRequest.frequency_penalty = request4.config.frequencyPenalty;
    }
    return openaiRequest;
  }
  createLoggingRequestContext(model) {
    return {
      model,
      modalities: this.modalities ?? {},
      // Mirror the pipeline default (see pipeline.ts createRequestContext) so the
      // --openai-logging fallback reconstruction reflects the same split as the
      // request actually sent. Opt out via generationConfig.splitToolMedia = false.
      splitToolMedia: this.splitToolMedia ?? true,
      toolResultContentFormat: this.toolResultContentFormat ?? "parts",
      startTime: 0
    };
  }
  async logOpenAIInteraction(openaiRequest, response, error, promptId) {
    if (!this.openaiLogger || !openaiRequest) {
      return;
    }
    const openaiResponse = response ? this.convertGeminiResponseToOpenAIForLogging(response, openaiRequest) : void 0;
    await this.openaiLogger.logInteraction(
      openaiRequest,
      openaiResponse,
      error instanceof Error ? error : error ? new Error(String(error)) : void 0,
      promptId
    );
  }
  async safelyLogOpenAIInteraction(openaiRequest, response, error, promptId) {
    try {
      await this.logOpenAIInteraction(openaiRequest, response, error, promptId);
    } catch (loggingError) {
      debugLogger10.warn("Failed to log OpenAI interaction:", loggingError);
    }
  }
  convertGeminiResponseToOpenAIForLogging(response, openaiRequest) {
    return OpenAIContentConverter.convertGeminiResponseToOpenAI(
      response,
      this.createLoggingRequestContext(openaiRequest.model)
    );
  }
  consolidateGeminiResponsesForLogging(responses) {
    if (responses.length === 0) {
      return void 0;
    }
    const consolidated = new GenerateContentResponse();
    const combinedParts = [];
    const functionCallIndex = /* @__PURE__ */ new Map();
    let finishReason;
    let usageMetadata;
    for (const response of responses) {
      if (response.usageMetadata) {
        usageMetadata = response.usageMetadata;
      }
      const candidate = response.candidates?.[0];
      if (candidate?.finishReason) {
        finishReason = candidate.finishReason;
      }
      const parts = candidate?.content?.parts ?? [];
      for (const part of parts) {
        if (typeof part === "string") {
          combinedParts.push({ text: part });
          continue;
        }
        if ("text" in part) {
          if (part.text) {
            combinedParts.push({
              text: part.text,
              ...part.thought ? { thought: true } : {},
              ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
            });
          }
          continue;
        }
        if ("functionCall" in part && part.functionCall) {
          const callKey = part.functionCall.id || part.functionCall.name || "tool_call";
          const existingIndex = functionCallIndex.get(callKey);
          const functionPart = { functionCall: part.functionCall };
          if (existingIndex !== void 0) {
            combinedParts[existingIndex] = functionPart;
          } else {
            functionCallIndex.set(callKey, combinedParts.length);
            combinedParts.push(functionPart);
          }
          continue;
        }
        if ("functionResponse" in part && part.functionResponse) {
          combinedParts.push({ functionResponse: part.functionResponse });
          continue;
        }
        combinedParts.push(part);
      }
    }
    const lastResponse = responses[responses.length - 1];
    const lastCandidate = lastResponse.candidates?.[0];
    consolidated.responseId = lastResponse.responseId;
    consolidated.createTime = lastResponse.createTime;
    consolidated.modelVersion = lastResponse.modelVersion;
    consolidated.promptFeedback = lastResponse.promptFeedback;
    consolidated.usageMetadata = usageMetadata;
    consolidated.candidates = [
      {
        content: {
          role: lastCandidate?.content?.role || "model",
          parts: combinedParts
        },
        ...finishReason ? { finishReason } : {},
        index: 0,
        safetyRatings: lastCandidate?.safetyRatings || []
      }
    ];
    return consolidated;
  }
  extractResponseText(response, maxLength) {
    let text = "";
    let truncated = false;
    const maxPrefixLength = Math.max(
      0,
      maxLength - RESPONSE_TEXT_TRUNCATION_SUFFIX.length
    );
    const hasText = this.forEachVisibleResponseText(response, (partText) => {
      if (truncated) {
        return;
      }
      const remaining = maxPrefixLength - text.length;
      if (partText.length <= remaining) {
        text += partText;
        return;
      }
      text += partText.slice(0, Math.max(0, remaining));
      truncated = true;
    });
    if (!hasText) {
      return void 0;
    }
    return truncated ? `${text}${RESPONSE_TEXT_TRUNCATION_SUFFIX}` : text;
  }
  extractResponseTextForSensitiveSpan(response, maxLength) {
    let text = "";
    let originalLength = 0;
    const hasText = this.forEachVisibleResponseText(response, (partText) => {
      originalLength += partText.length;
      const remaining = maxLength - text.length;
      if (remaining > 0) {
        text += partText.slice(0, remaining);
      }
    });
    if (!hasText) {
      return void 0;
    }
    return { text, originalLength };
  }
  forEachVisibleResponseText(response, onText) {
    const parts = response?.candidates?.[0]?.content?.parts;
    if (!parts?.length) {
      return false;
    }
    let hasText = false;
    for (const part of parts) {
      const text = this.getVisibleResponsePartText(part);
      if (text === void 0) {
        continue;
      }
      hasText = true;
      onText(text);
    }
    return hasText;
  }
  getVisibleResponsePartText(part) {
    if (typeof part === "string") {
      return part;
    }
    if ("text" in part && typeof part.text === "string" && !("thought" in part && part.thought)) {
      return part.text;
    }
    return void 0;
  }
  safelyAddModelOutputAttributes(span, modelOutput) {
    try {
      addModelOutputAttributes(
        this.config,
        span,
        modelOutput?.text,
        modelOutput?.originalLength
      );
    } catch (error) {
      debugLogger10.warn("Failed to add model output span attributes:", error);
    }
  }
  shouldCollectSensitiveSpanAttributes() {
    return areSensitiveSpanAttributesEnabled(this.config);
  }
  async countTokens(req) {
    return this.wrapped.countTokens(req);
  }
  async embedContent(req) {
    return this.wrapped.embedContent(req);
  }
  useSummarizedThinking() {
    return this.wrapped.useSummarizedThinking();
  }
  toContents(contents) {
    if (Array.isArray(contents)) {
      return contents.map((c) => this.toContent(c));
    }
    return [this.toContent(contents)];
  }
  toContent(content) {
    if (Array.isArray(content)) {
      return {
        role: "user",
        parts: this.toParts(content)
      };
    }
    if (typeof content === "string") {
      return {
        role: "user",
        parts: [{ text: content }]
      };
    }
    if ("parts" in content) {
      return {
        ...content,
        parts: content.parts ? this.toParts(content.parts.filter((p) => p != null)) : []
      };
    }
    return {
      role: "user",
      parts: [this.toPart(content)]
    };
  }
  toParts(parts) {
    return parts.map((p) => this.toPart(p));
  }
  toPart(part) {
    if (typeof part === "string") {
      return { text: part };
    }
    if ("thought" in part && part.thought) {
      const thoughtText = `[Thought: ${part.thought}]`;
      const newPart = { ...part };
      delete newPart["thought"];
      const hasApiContent = "functionCall" in newPart || "functionResponse" in newPart || "inlineData" in newPart || "fileData" in newPart;
      if (hasApiContent) {
        return newPart;
      }
      const text = newPart.text;
      const existingText = text ? String(text) : "";
      const combinedText = existingText ? `${existingText}
${thoughtText}` : thoughtText;
      return {
        ...newPart,
        text: combinedText
      };
    }
    return part;
  }
};

// packages/core/src/models/modelConfigErrors.ts
init_esbuild_shims();
function getDefaultApiKeyEnvVar(authType) {
  switch (authType) {
    case "openai":
      return "OPENAI_API_KEY";
    case "anthropic":
      return "ANTHROPIC_API_KEY";
    case "gemini":
      return "GEMINI_API_KEY";
    case "vertex-ai":
      return "GOOGLE_API_KEY";
    default:
      return "API_KEY";
  }
}
__name(getDefaultApiKeyEnvVar, "getDefaultApiKeyEnvVar");
function getDefaultModelEnvVar(authType) {
  switch (authType) {
    case "openai":
      return "OPENAI_MODEL";
    case "anthropic":
      return "ANTHROPIC_MODEL";
    case "gemini":
      return "GEMINI_MODEL";
    case "vertex-ai":
      return "GOOGLE_MODEL";
    default:
      return "MODEL";
  }
}
__name(getDefaultModelEnvVar, "getDefaultModelEnvVar");
var ModelConfigError = class extends Error {
  static {
    __name(this, "ModelConfigError");
  }
  constructor(message) {
    super(message);
    this.name = new.target.name;
    Object.setPrototypeOf(this, new.target.prototype);
  }
};
var StrictMissingCredentialsError = class extends ModelConfigError {
  static {
    __name(this, "StrictMissingCredentialsError");
  }
  code = "STRICT_MISSING_CREDENTIALS";
  constructor(authType, model, envKey) {
    const providerKey = authType || "(unknown)";
    const modelName = model || "(unknown)";
    super(
      `Missing credentials for modelProviders model '${modelName}'. ` + (envKey ? `Current configured envKey: '${envKey}'. Set that environment variable, or update modelProviders.${providerKey}[].envKey.` : `Configure modelProviders.${providerKey}[].envKey and set that environment variable.`)
    );
  }
};
var StrictMissingModelIdError = class extends ModelConfigError {
  static {
    __name(this, "StrictMissingModelIdError");
  }
  code = "STRICT_MISSING_MODEL_ID";
  constructor(authType) {
    super(
      `Missing model id for strict modelProviders resolution (authType: ${authType}).`
    );
  }
};
var MissingApiKeyError = class extends ModelConfigError {
  static {
    __name(this, "MissingApiKeyError");
  }
  code = "MISSING_API_KEY";
  constructor(params) {
    super(
      `Missing API key for ${params.authType} auth. Current model: '${params.model || "(unknown)"}', baseUrl: '${params.baseUrl || "(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${params.envKey}'.`
    );
  }
};
var MissingModelError = class extends ModelConfigError {
  static {
    __name(this, "MissingModelError");
  }
  code = "MISSING_MODEL";
  constructor(params) {
    super(
      `Missing model for ${params.authType} auth. Set the environment variable '${params.envKey}'.`
    );
  }
};
var MissingBaseUrlError = class extends ModelConfigError {
  static {
    __name(this, "MissingBaseUrlError");
  }
  code = "MISSING_BASE_URL";
  constructor(params) {
    super(
      `Missing baseUrl for modelProviders model '${params.model || "(unknown)"}'. Configure modelProviders.${params.authType || "(unknown)"}[].baseUrl.`
    );
  }
};
var MissingAnthropicBaseUrlEnvError = class extends ModelConfigError {
  static {
    __name(this, "MissingAnthropicBaseUrlEnvError");
  }
  code = "MISSING_ANTHROPIC_BASE_URL_ENV";
  constructor() {
    super("ANTHROPIC_BASE_URL environment variable not found.");
  }
};

// packages/core/src/models/constants.ts
init_esbuild_shims();
var MODEL_GENERATION_CONFIG_FIELDS = [
  "samplingParams",
  "timeout",
  "maxRetries",
  "retryErrorCodes",
  "enableCacheControl",
  "schemaCompliance",
  "reasoning",
  "contextWindowSize",
  "customHeaders",
  "extra_body",
  "modalities",
  "splitToolMedia",
  "toolResultContentFormat"
];
var CREDENTIAL_FIELDS = [
  "model",
  "apiKey",
  "apiKeyEnvKey",
  "baseUrl"
];
var PROVIDER_SOURCED_FIELDS = [
  ...CREDENTIAL_FIELDS,
  ...MODEL_GENERATION_CONFIG_FIELDS
];
var AUTH_ENV_MAPPINGS = {
  openai: {
    apiKey: ["OPENAI_API_KEY"],
    baseUrl: ["OPENAI_BASE_URL"],
    model: ["OPENAI_MODEL", "QWEN_MODEL"]
  },
  anthropic: {
    apiKey: ["ANTHROPIC_API_KEY"],
    baseUrl: ["ANTHROPIC_BASE_URL"],
    model: ["ANTHROPIC_MODEL"]
  },
  gemini: {
    apiKey: ["GEMINI_API_KEY"],
    baseUrl: [],
    model: ["GEMINI_MODEL"]
  },
  "vertex-ai": {
    apiKey: ["GOOGLE_API_KEY"],
    baseUrl: [],
    model: ["GOOGLE_MODEL"]
  },
  "qwen-oauth": {
    apiKey: [],
    baseUrl: [],
    model: []
  }
};
var DEFAULT_MODELS = {
  openai: MAINLINE_CODER_MODEL,
  "qwen-oauth": DEFAULT_QWEN_MODEL
};
var QWEN_OAUTH_MODELS = [
  {
    id: "coder-model",
    name: "coder-model",
    description: "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance",
    capabilities: { vision: true }
  }
];
var QWEN_OAUTH_ALLOWED_MODELS = QWEN_OAUTH_MODELS.map(
  (model) => model.id
);

// packages/core/src/core/contentGenerator.ts
var AuthType = /* @__PURE__ */ ((AuthType2) => {
  AuthType2["USE_OPENAI"] = "openai";
  AuthType2["QWEN_OAUTH"] = "qwen-oauth";
  AuthType2["USE_GEMINI"] = "gemini";
  AuthType2["USE_VERTEX_AI"] = "vertex-ai";
  AuthType2["USE_ANTHROPIC"] = "anthropic";
  return AuthType2;
})(AuthType || {});
function setSource(sources, path11, source) {
  sources[path11] = source;
}
__name(setSource, "setSource");
function getSeedSource(seed, path11) {
  return seed?.[path11];
}
__name(getSeedSource, "getSeedSource");
function resolveContentGeneratorConfigWithSources(config, authType, generationConfig, seedSources, options) {
  const sources = { ...seedSources || {} };
  const strictModelProvider = options?.strictModelProvider === true;
  const newContentGeneratorConfig = {
    ...generationConfig || {},
    authType,
    proxy: config?.getProxy()
  };
  setSource(sources, "authType", {
    kind: "computed",
    detail: "provided by caller"
  });
  if (config?.getProxy()) {
    setSource(sources, "proxy", {
      kind: "computed",
      detail: "Config.getProxy()"
    });
  }
  const seedOrUnknown = /* @__PURE__ */ __name((path11) => getSeedSource(seedSources, path11) ?? { kind: "unknown" }, "seedOrUnknown");
  for (const field of PROVIDER_SOURCED_FIELDS) {
    if (generationConfig && field in generationConfig && !sources[field]) {
      setSource(sources, field, seedOrUnknown(field));
    }
  }
  const validation = validateModelConfig(
    newContentGeneratorConfig,
    strictModelProvider
  );
  if (!validation.valid) {
    throw new Error(validation.errors.map((e) => e.message).join("\n"));
  }
  return {
    config: newContentGeneratorConfig,
    sources
  };
}
__name(resolveContentGeneratorConfigWithSources, "resolveContentGeneratorConfigWithSources");
function validateModelConfig(config, isStrictModelProvider = false) {
  const errors = [];
  if (config.authType === "qwen-oauth" /* QWEN_OAUTH */) {
    return { valid: true, errors: [] };
  }
  if (!config.apiKey) {
    if (isStrictModelProvider) {
      errors.push(
        new StrictMissingCredentialsError(
          config.authType,
          config.model,
          config.apiKeyEnvKey
        )
      );
    } else {
      const envKey = config.apiKeyEnvKey || getDefaultApiKeyEnvVar(config.authType);
      errors.push(
        new MissingApiKeyError({
          authType: config.authType,
          model: config.model,
          baseUrl: config.baseUrl,
          envKey
        })
      );
    }
  }
  if (!config.model) {
    if (isStrictModelProvider) {
      errors.push(new StrictMissingModelIdError(config.authType));
    } else {
      const envKey = getDefaultModelEnvVar(config.authType);
      errors.push(new MissingModelError({ authType: config.authType, envKey }));
    }
  }
  if (config.authType === "anthropic" /* USE_ANTHROPIC */ && !config.baseUrl) {
    if (isStrictModelProvider) {
      errors.push(
        new MissingBaseUrlError({
          authType: config.authType,
          model: config.model
        })
      );
    } else if (config.authType === "anthropic" /* USE_ANTHROPIC */) {
      errors.push(new MissingAnthropicBaseUrlEnvError());
    }
  }
  return { valid: errors.length === 0, errors };
}
__name(validateModelConfig, "validateModelConfig");
function createContentGeneratorConfig(config, authType, generationConfig) {
  return resolveContentGeneratorConfigWithSources(
    config,
    authType,
    generationConfig
  ).config;
}
__name(createContentGeneratorConfig, "createContentGeneratorConfig");
function getModuleNotFoundError(error) {
  let current = error;
  while (current instanceof Error) {
    if ("code" in current && current.code === "ERR_MODULE_NOT_FOUND") {
      return current;
    }
    current = current.cause;
  }
  return void 0;
}
__name(getModuleNotFoundError, "getModuleNotFoundError");
async function createContentGenerator(generatorConfig, config, isInitialAuth) {
  const validation = validateModelConfig(generatorConfig, false);
  if (!validation.valid) {
    throw new Error(validation.errors.map((e) => e.message).join("\n"));
  }
  const authType = generatorConfig.authType;
  if (!authType) {
    throw new Error("ContentGeneratorConfig must have an authType");
  }
  let baseGenerator;
  try {
    if (authType === "openai" /* USE_OPENAI */) {
      const { createOpenAIContentGenerator } = await import("./openaiContentGenerator-KFXI3E52.js");
      baseGenerator = createOpenAIContentGenerator(generatorConfig, config);
    } else if (authType === "qwen-oauth" /* QWEN_OAUTH */) {
      const { getQwenOAuthClient: getQwenOauthClient } = await import("./qwenOAuth2-LWLA6MQG.js");
      const { QwenContentGenerator } = await import("./qwenContentGenerator-6VNHHLD5.js");
      try {
        const qwenClient = await getQwenOauthClient(
          config,
          isInitialAuth ? { requireCachedCredentials: true } : void 0
        );
        baseGenerator = new QwenContentGenerator(
          qwenClient,
          generatorConfig,
          config
        );
      } catch (error) {
        if (getModuleNotFoundError(error)) {
          throw error;
        }
        throw new Error(error instanceof Error ? error.message : String(error));
      }
    } else if (authType === "anthropic" /* USE_ANTHROPIC */) {
      const { createAnthropicContentGenerator } = await import("./anthropicContentGenerator-H5ZOEENQ.js");
      baseGenerator = createAnthropicContentGenerator(generatorConfig, config);
    } else if (authType === "gemini" /* USE_GEMINI */ || authType === "vertex-ai" /* USE_VERTEX_AI */) {
      const { createGeminiContentGenerator } = await import("./geminiContentGenerator-YDUUKAM2.js");
      baseGenerator = createGeminiContentGenerator(generatorConfig, config);
    } else {
      throw new Error(
        `Error creating contentGenerator: Unsupported authType: ${authType}`
      );
    }
  } catch (error) {
    const moduleNotFoundError = getModuleNotFoundError(error);
    if (moduleNotFoundError) {
      throw new Error(
        `Qwen Code was updated in the background and needs to be restarted.
Please exit and restart Qwen Code to use the '${authType}' provider.`,
        { cause: moduleNotFoundError }
      );
    }
    throw error;
  }
  return new LoggingContentGenerator(baseGenerator, config, generatorConfig);
}
__name(createContentGenerator, "createContentGenerator");

// packages/core/src/telemetry/qwen-logger/qwen-logger.ts
var USAGE_STATS_HOSTNAME = "gb4w8c3ygj-default-sea.rum.aliyuncs.com";
var USAGE_STATS_PATH = "/";
var RUN_APP_ID = "gb4w8c3ygj@851d5d500f08f92";
var FLUSH_INTERVAL_MS = 1e3 * 60;
var ERROR_LOG_INTERVAL_MS = 5 * 60 * 1e3;
var MAX_EVENTS = 1e3;
var MAX_RETRY_EVENTS = 100;
var QwenLogger = class _QwenLogger {
  static {
    __name(this, "QwenLogger");
  }
  static instance;
  config;
  debugLogger;
  installationManager;
  /**
   * Queue of pending events that need to be flushed to the server. New events
   * are added to this queue and then flushed on demand (via `flushToRum`)
   */
  events;
  /**
   * The last time that the events were successfully flushed to the server.
   */
  lastFlushTime = Date.now();
  userId;
  sessionId;
  /**
   * Cached source information read from source.json.
   * Only read once at session start to avoid repeated file I/O.
   */
  sourceInfo = "";
  /**
   * The value is true when there is a pending flush happening. This prevents
   * concurrent flush operations.
   */
  isFlushInProgress = false;
  /**
   * This value is true when a flush was requested during an ongoing flush.
   */
  pendingFlush = false;
  /**
   * Timestamp of the last network error log to prevent log spam.
   */
  lastErrorLogTime = 0;
  constructor(config) {
    this.config = config;
    this.debugLogger = createDebugLogger("QWEN_LOGGER");
    this.events = new import_fixed_deque.default(Array, MAX_EVENTS);
    this.installationManager = new InstallationManager();
    this.userId = this.generateUserId();
    this.sessionId = config.getSessionId();
    this.sourceInfo = this.readSourceInfo();
  }
  generateUserId() {
    const installationId = this.installationManager.getInstallationId();
    return `user-${installationId ?? "unknown"}`;
  }
  static getInstance(config) {
    if (config === void 0 || !config?.getUsageStatisticsEnabled())
      return void 0;
    if (!_QwenLogger.instance) {
      _QwenLogger.instance = new _QwenLogger(config);
    }
    return _QwenLogger.instance;
  }
  enqueueLogEvent(event) {
    try {
      const wasAtCapacity = this.events.size >= MAX_EVENTS;
      if (wasAtCapacity) {
        this.events.shift();
      }
      this.events.push(event);
      if (wasAtCapacity) {
        this.debugLogger.debug(
          `QwenLogger: Dropped old event to prevent memory leak (queue size: ${this.events.size})`
        );
      }
    } catch (error) {
      this.debugLogger.error("QwenLogger: Failed to enqueue log event.", error);
    }
  }
  createRumEvent(eventType, type, name, properties) {
    return {
      timestamp: Date.now(),
      event_type: eventType,
      type,
      name,
      ...properties || {}
    };
  }
  createViewEvent(type, name, properties) {
    return this.createRumEvent("view", type, name, properties);
  }
  createActionEvent(type, name, properties) {
    return this.createRumEvent("action", type, name, properties);
  }
  createResourceEvent(type, name, properties) {
    return this.createRumEvent("resource", type, name, properties);
  }
  createExceptionEvent(type, name, properties) {
    return this.createRumEvent("exception", type, name, properties);
  }
  getOsMetadata() {
    return {
      type: os3.platform(),
      version: os3.release()
    };
  }
  async createRumPayload() {
    const authType = this.config?.getAuthType();
    const version = this.config?.getCliVersion() || "unknown";
    const osMetadata = this.getOsMetadata();
    return {
      app: {
        id: RUN_APP_ID,
        env: process.env["DEBUG"] ? "dev" : "prod",
        version: version || "unknown",
        type: "cli",
        channel: this.sourceInfo || void 0
      },
      user: {
        id: this.userId
      },
      session: {
        id: this.sessionId || this.config?.getSessionId()
      },
      view: {
        id: this.sessionId || this.config?.getSessionId(),
        name: "qwen-code-cli"
      },
      os: osMetadata,
      events: this.events.toArray(),
      properties: {
        auth_type: authType,
        model: this.config?.getModel(),
        base_url: authType === "openai" /* USE_OPENAI */ ? this.config?.getContentGeneratorConfig().baseUrl || "" : "",
        ...this.config?.getChannel?.() ? { channel: this.config.getChannel() } : {}
      },
      _v: `qwen-code@${version}`
    };
  }
  flushIfNeeded() {
    if (Date.now() - this.lastFlushTime < FLUSH_INTERVAL_MS) {
      return;
    }
    void this.flushToRum();
  }
  readSourceInfo() {
    try {
      const globalDir = Storage.getGlobalQwenDir();
      const sourceJsonPath = path7.join(globalDir, "source.json");
      const legacyPath = path7.join(os3.homedir(), ".qwen", "source.json");
      const candidates = path7.normalize(sourceJsonPath) !== path7.normalize(legacyPath) ? [sourceJsonPath, legacyPath] : [sourceJsonPath];
      for (const candidate of candidates) {
        if (fs6.existsSync(candidate)) {
          const sourceJsonContent = fs6.readFileSync(candidate, "utf8");
          const sourceData = JSON.parse(sourceJsonContent);
          if (sourceData && typeof sourceData === "object" && sourceData.source && sourceData.source !== "unknown") {
            return sourceData.source;
          }
        }
      }
    } catch (_error) {
    }
    return "";
  }
  async flushToRum() {
    if (this.isFlushInProgress) {
      this.debugLogger.debug(
        "QwenLogger: Flush already in progress, marking pending flush."
      );
      this.pendingFlush = true;
      return Promise.resolve({});
    }
    this.isFlushInProgress = true;
    if (this.events.size === 0) {
      this.isFlushInProgress = false;
      return {};
    }
    const eventsToSend = this.events.toArray();
    this.events.clear();
    const rumPayload = await this.createRumPayload();
    rumPayload.events = eventsToSend;
    try {
      await new Promise((resolve2, reject) => {
        const body = safeJsonStringify(rumPayload);
        const options = {
          hostname: USAGE_STATS_HOSTNAME,
          path: USAGE_STATS_PATH,
          method: "POST",
          headers: {
            "Content-Length": Buffer2.byteLength(body),
            "Content-Type": "text/plain;charset=UTF-8"
          }
        };
        const bufs = [];
        const req = https2.request(
          {
            ...options,
            agent: this.getProxyAgent()
          },
          (res) => {
            if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
              const err = new Error(
                `Request failed with status ${res.statusCode}`
              );
              res.resume();
              return reject(err);
            }
            res.on("data", (buf) => bufs.push(buf));
            res.on("end", () => resolve2(Buffer2.concat(bufs)));
          }
        );
        req.on("error", reject);
        req.end(body);
      });
      this.lastFlushTime = Date.now();
      return {};
    } catch (error) {
      const now = Date.now();
      if (now - this.lastErrorLogTime > ERROR_LOG_INTERVAL_MS) {
        this.debugLogger.error("RUM flush failed.", error);
        this.lastErrorLogTime = now;
      }
      this.requeueFailedEvents(eventsToSend);
      return {};
    } finally {
      this.isFlushInProgress = false;
      if (this.pendingFlush) {
        this.pendingFlush = false;
        void this.flushToRum();
      }
    }
  }
  // session events
  async logStartSessionEvent(event) {
    await this.flushToRum();
    this.events.clear();
    this.sessionId = event.session_id;
    this.sourceInfo = this.readSourceInfo();
    const applicationEvent = this.createViewEvent("session", "session_start", {
      properties: {
        approval_mode: event.approval_mode,
        core_tools_enabled: event.core_tools_enabled,
        debug_enabled: event.debug_enabled,
        hooks: event.hooks,
        ide_enabled: event.ide_enabled,
        interactive_shell_enabled: event.interactive_shell_enabled,
        mcp_servers: event.mcp_servers,
        model: event.model,
        sandbox_enabled: event.sandbox_enabled,
        skills: event.skills,
        subagents: event.subagents,
        telemetry_enabled: event.telemetry_enabled,
        truncate_tool_output_lines: event.truncate_tool_output_lines,
        truncate_tool_output_threshold: event.truncate_tool_output_threshold
      }
    });
    this.enqueueLogEvent(applicationEvent);
    void this.flushToRum();
  }
  logEndSessionEvent(_event) {
    const applicationEvent = this.createViewEvent("session", "session_end", {});
    this.enqueueLogEvent(applicationEvent);
    void this.flushToRum();
  }
  logConversationFinishedEvent(event) {
    const rumEvent = this.createActionEvent(
      "conversation",
      "conversation_finished",
      {
        properties: {
          approval_mode: event.approvalMode,
          turn_count: event.turnCount
        }
      }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // user action events
  logNewPromptEvent(event) {
    const rumEvent = this.createActionEvent("user", "new_prompt", {
      properties: {
        prompt_id: event.prompt_id,
        prompt_length: event.prompt_length,
        ...event.model ? { model: event.model } : {}
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logRetryEvent(event) {
    const rumEvent = this.createActionEvent("user", "retry", {
      properties: {
        prompt_id: event.prompt_id
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logSlashCommandEvent(event) {
    const rumEvent = this.createActionEvent("user", "slash_command", {
      properties: {
        command: event.command,
        subcommand: event.subcommand
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logModelSlashCommandEvent(event) {
    const rumEvent = this.createActionEvent("user", "model_slash_command", {
      properties: {
        model: event.model_name
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // tool call events
  logToolCallEvent(event) {
    const rumEvent = this.createActionEvent(
      "tool",
      `tool_call#${event.function_name}`,
      {
        properties: {
          prompt_id: event.prompt_id,
          response_id: event.response_id,
          tool_name: event.function_name,
          permission: event.decision,
          success: event.success ? 1 : 0,
          duration_ms: event.duration_ms,
          error_type: event.error_type,
          error_message: event.error
        }
      }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logFileOperationEvent(event) {
    const rumEvent = this.createActionEvent(
      "tool",
      `file_operation#${event.tool_name}`,
      {
        properties: {
          tool_name: event.tool_name,
          operation: event.operation,
          lines: event.lines,
          mimetype: event.mimetype,
          extension: event.extension,
          programming_language: event.programming_language
        }
      }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logSubagentExecutionEvent(event) {
    const rumEvent = this.createActionEvent("tool", "subagent_execution", {
      properties: {
        subagent_name: event.subagent_name,
        status: event.status,
        terminate_reason: event.terminate_reason
      },
      snapshots: JSON.stringify({
        ...event.execution_summary ? { execution_summary: event.execution_summary } : {}
      })
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logToolOutputTruncatedEvent(event) {
    const rumEvent = this.createActionEvent("tool", "tool_output_truncated", {
      properties: {
        tool_name: event.tool_name
      },
      snapshots: JSON.stringify({
        original_content_length: event.original_content_length,
        truncated_content_length: event.truncated_content_length,
        threshold: event.threshold,
        lines: event.lines
      })
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // api events
  logApiRequestEvent(event) {
    const rumEvent = this.createResourceEvent("api", "api_request", {
      properties: {
        model: event.model,
        prompt_id: event.prompt_id,
        subagent_name: event.subagent_name
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logApiResponseEvent(event) {
    const rumEvent = this.createResourceEvent("api", "api_response", {
      status_code: event.status_code?.toString() ?? "",
      duration: event.duration_ms,
      success: 1,
      trace_id: event.response_id,
      properties: {
        auth_type: event.auth_type,
        model: event.model,
        prompt_id: event.prompt_id,
        subagent_name: event.subagent_name
      },
      snapshots: JSON.stringify({
        input_token_count: event.input_token_count,
        output_token_count: event.output_token_count,
        cached_content_token_count: event.cached_content_token_count,
        thoughts_token_count: event.thoughts_token_count
      })
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logApiCancelEvent(event) {
    const rumEvent = this.createActionEvent("api", "api_cancel", {
      properties: {
        model: event.model,
        prompt_id: event.prompt_id,
        auth_type: event.auth_type,
        loop_wakeups_cancelled: event.loop_wakeups_cancelled
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logApiErrorEvent(event) {
    const rumEvent = this.createResourceEvent("api", "api_error", {
      status_code: event.status_code?.toString() ?? "",
      duration: event.duration_ms,
      success: 0,
      message: event.error_message,
      trace_id: event.response_id,
      properties: {
        auth_type: event.auth_type,
        model: event.model,
        prompt_id: event.prompt_id,
        subagent_name: event.subagent_name,
        error_message: event.error_message,
        error_type: event.error_type
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // error events
  logInvalidChunkEvent(event) {
    const rumEvent = this.createExceptionEvent("error", "invalid_chunk", {
      subtype: "invalid_chunk",
      message: event.error_message
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logContentRetryFailureEvent(event) {
    const rumEvent = this.createExceptionEvent(
      "error",
      "content_retry_failure",
      {
        subtype: "content_retry_failure",
        message: `Content retry failed after ${event.total_attempts} attempts`,
        properties: {
          error_type: event.final_error_type,
          total_attempts: event.total_attempts,
          total_duration_ms: event.total_duration_ms
        }
      }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logMalformedJsonResponseEvent(event) {
    const rumEvent = this.createExceptionEvent(
      "error",
      "malformed_json_response",
      {
        subtype: "malformed_json_response",
        properties: {
          model: event.model
        }
      }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logLoopDetectedEvent(event) {
    const rumEvent = this.createExceptionEvent("error", "loop_detected", {
      subtype: "loop_detected",
      properties: {
        prompt_id: event.prompt_id,
        error_type: event.loop_type
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logKittySequenceOverflowEvent(event) {
    const rumEvent = this.createExceptionEvent(
      "overflow",
      "kitty_sequence_overflow",
      {
        subtype: "kitty_sequence_overflow",
        properties: {
          sequence_length: event.sequence_length
        },
        snapshots: JSON.stringify({
          truncated_sequence: event.truncated_sequence
        })
      }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // ide events
  logIdeConnectionEvent(event) {
    const rumEvent = this.createActionEvent("ide", "ide_connection", {
      properties: {
        connection_type: event.connection_type
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // extension events
  logExtensionInstallEvent(event) {
    const rumEvent = this.createActionEvent("extension", "extension_install", {
      properties: {
        extension_name: event.extension_name,
        extension_version: event.extension_version,
        extension_source: event.extension_source,
        status: event.status
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logExtensionUninstallEvent(event) {
    const rumEvent = this.createActionEvent(
      "extension",
      "extension_uninstall",
      {
        properties: {
          extension_name: event.extension_name,
          status: event.status
        }
      }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logExtensionUpdateEvent(event) {
    const rumEvent = this.createActionEvent("extension", "extension_update", {
      properties: {
        extension_name: event.extension_name,
        status: event.status,
        extension_id: event.extension_id,
        extension_previous_version: event.extension_previous_version,
        extension_version: event.extension_version,
        extension_source: event.extension_source
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logExtensionEnableEvent(event) {
    const rumEvent = this.createActionEvent("extension", "extension_enable", {
      properties: {
        extension_name: event.extension_name,
        setting_scope: event.setting_scope
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logExtensionDisableEvent(event) {
    const rumEvent = this.createActionEvent("extension", "extension_disable", {
      properties: {
        extension_name: event.extension_name,
        setting_scope: event.setting_scope
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logAuthEvent(event) {
    const rumEvent = this.createActionEvent("auth", "auth", {
      properties: {
        auth_type: event.auth_type,
        action_type: event.action_type,
        success: event.status === "success" ? 1 : 0,
        error_type: event.status !== "success" ? event.status : void 0,
        error_message: event.status === "error" ? event.error_message : void 0
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // misc events
  logFlashFallbackEvent(event) {
    const rumEvent = this.createActionEvent("misc", "flash_fallback", {
      properties: {
        auth_type: event.auth_type
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logRipgrepFallbackEvent(event) {
    const rumEvent = this.createActionEvent("misc", "ripgrep_fallback", {
      properties: {
        platform: process.platform,
        arch: process.arch,
        use_ripgrep: event.use_ripgrep,
        use_builtin_ripgrep: event.use_builtin_ripgrep,
        error_message: event.error
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logLoopDetectionDisabledEvent() {
    const rumEvent = this.createActionEvent(
      "misc",
      "loop_detection_disabled",
      {}
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logNextSpeakerCheck(event) {
    const rumEvent = this.createActionEvent("misc", "next_speaker_check", {
      properties: {
        prompt_id: event.prompt_id,
        finish_reason: event.finish_reason,
        result: event.result
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logSkillLaunchEvent(event) {
    const rumEvent = this.createActionEvent("misc", "skill_launch", {
      properties: {
        skill_name: event.skill_name,
        success: event.success ? 1 : 0,
        prompt_id: event.prompt_id
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logUserFeedbackEvent(event) {
    const rumEvent = this.createActionEvent("user", "user_feedback", {
      properties: {
        session_id: event.session_id,
        rating: event.rating,
        model: event.model,
        approval_mode: event.approval_mode,
        prompt_id: event.prompt_id || ""
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logChatCompressionEvent(event) {
    const rumEvent = this.createActionEvent("misc", "chat_compression", {
      properties: {
        tokens_before: event.tokens_before,
        tokens_after: event.tokens_after
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logContentRetryEvent(event) {
    const rumEvent = this.createActionEvent("misc", "content_retry", {
      properties: {
        error_type: event.error_type,
        attempt_number: event.attempt_number,
        retry_delay_ms: event.retry_delay_ms
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // Phase 4b — HTTP-status retry from retryWithBackoff (429/5xx). Distinct from
  // logContentRetryEvent which is fired by geminiChat's content-recovery loop.
  logApiRetryEvent(event) {
    const rumEvent = this.createActionEvent("misc", "api_retry", {
      properties: {
        model: event.model,
        prompt_id: event.prompt_id ?? "",
        attempt_number: event.attempt_number,
        error_type: event.error_type ?? "unknown",
        status_code: event.status_code !== void 0 ? String(event.status_code) : "",
        retry_delay_ms: event.retry_delay_ms,
        subagent_name: event.subagent_name ?? ""
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  // arena events
  logArenaSessionStartedEvent(event) {
    const rumEvent = this.createActionEvent("arena", "arena_session_started", {
      properties: {
        arena_session_id: event.arena_session_id,
        model_ids: JSON.stringify(event.model_ids),
        task_length: event.task_length
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logArenaAgentCompletedEvent(event) {
    const rumEvent = this.createActionEvent("arena", "arena_agent_completed", {
      properties: {
        arena_session_id: event.arena_session_id,
        agent_session_id: event.agent_session_id,
        agent_model_id: event.agent_model_id,
        status: event.status,
        duration_ms: event.duration_ms,
        rounds: event.rounds,
        total_tokens: event.total_tokens,
        input_tokens: event.input_tokens,
        output_tokens: event.output_tokens,
        tool_calls: event.tool_calls,
        successful_tool_calls: event.successful_tool_calls,
        failed_tool_calls: event.failed_tool_calls
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  logArenaSessionEndedEvent(event) {
    const rumEvent = this.createActionEvent("arena", "arena_session_ended", {
      properties: {
        arena_session_id: event.arena_session_id,
        status: event.status,
        duration_ms: event.duration_ms,
        display_backend: event.display_backend,
        agent_count: event.agent_count,
        completed_agents: event.completed_agents,
        failed_agents: event.failed_agents,
        cancelled_agents: event.cancelled_agents,
        winner_model_id: event.winner_model_id
      }
    });
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  /**
   * Log a hook call event
   * Records hook execution telemetry for observability
   */
  logHookCallEvent(event) {
    const sanitizedHookName = sanitizeHookName(event.hook_name);
    const properties = {
      hook_event_name: event.hook_event_name,
      hook_type: event.hook_type,
      hook_name: sanitizedHookName,
      duration_ms: event.duration_ms,
      success: event.success ? 1 : 0,
      exit_code: event.exit_code
    };
    if (event.error && this.config?.getTelemetryLogPromptsEnabled()) {
      properties["error"] = event.error;
    }
    const rumEvent = this.createActionEvent(
      "hook",
      `hook_call#${event.hook_event_name}`,
      { properties }
    );
    this.enqueueLogEvent(rumEvent);
    this.flushIfNeeded();
  }
  getProxyAgent() {
    const proxyUrl = this.config?.getProxy();
    if (!proxyUrl) return void 0;
    if (/^https?:\/\//i.test(proxyUrl)) {
      return new import_https_proxy_agent.HttpsProxyAgent(proxyUrl);
    } else {
      throw new Error("Unsupported proxy type");
    }
  }
  requeueFailedEvents(eventsToSend) {
    const eventsToRetry = eventsToSend.slice(-MAX_RETRY_EVENTS);
    if (eventsToSend.length > MAX_RETRY_EVENTS) {
      this.debugLogger.warn(
        `QwenLogger: Dropping ${eventsToSend.length - MAX_RETRY_EVENTS} events due to retry queue limit. Total events: ${eventsToSend.length}, keeping: ${MAX_RETRY_EVENTS}`
      );
    }
    const availableSpace = MAX_EVENTS - this.events.size;
    const numEventsToRequeue = Math.min(eventsToRetry.length, availableSpace);
    if (numEventsToRequeue === 0) {
      return;
    }
    const eventsToRequeue = eventsToRetry.slice(
      eventsToRetry.length - numEventsToRequeue
    );
    for (let i = eventsToRequeue.length - 1; i >= 0; i--) {
      this.events.unshift(eventsToRequeue[i]);
    }
    while (this.events.size > MAX_EVENTS) {
      this.events.pop();
    }
    this.debugLogger.debug(
      `QwenLogger: Re-queued ${numEventsToRequeue} events for retry (queue size: ${this.events.size})`
    );
  }
};

// packages/core/src/services/tokenUsageService.ts
init_esbuild_shims();
import path9 from "node:path";
import { randomUUID } from "node:crypto";

// packages/core/src/utils/jsonl-utils.ts
init_esbuild_shims();
import fs7 from "node:fs";
import path8 from "node:path";
import readline from "node:readline";
import { finished } from "node:stream/promises";
var debugLogger11 = createDebugLogger("JSONL");
var fileLocks = /* @__PURE__ */ new Map();
function getFileLock(filePath) {
  if (!fileLocks.has(filePath)) {
    fileLocks.set(filePath, new Mutex());
  }
  return fileLocks.get(filePath);
}
__name(getFileLock, "getFileLock");
function _recoverObjectsFromLine(line) {
  const out = [];
  let depth = 0;
  let inString = false;
  let escape = false;
  let start = -1;
  for (let i = 0; i < line.length; i++) {
    const c = line[i];
    if (escape) {
      escape = false;
      continue;
    }
    if (inString) {
      if (c === "\\") escape = true;
      else if (c === '"') inString = false;
      continue;
    }
    if (c === '"') {
      inString = true;
      continue;
    }
    if (c === "{") {
      if (depth === 0) start = i;
      depth++;
    } else if (c === "}") {
      depth--;
      if (depth === 0 && start >= 0) {
        const fragment = line.slice(start, i + 1);
        try {
          out.push(JSON.parse(fragment));
        } catch {
        }
        start = -1;
      } else if (depth < 0) {
        depth = 0;
        start = -1;
      }
    }
  }
  return out;
}
__name(_recoverObjectsFromLine, "_recoverObjectsFromLine");
function parseLineTolerant(line, filePath) {
  try {
    const parsed = JSON.parse(line);
    if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
      return [parsed];
    }
    debugLogger11.warn(`Skipping non-object JSONL value in ${filePath}`);
    return [];
  } catch {
    const fragments = _recoverObjectsFromLine(line);
    if (fragments.length === 0) {
      debugLogger11.warn(`Failed to parse line in ${filePath}`);
    } else {
      debugLogger11.warn(
        `Recovered ${fragments.length} record(s) from malformed line in ${filePath}`
      );
    }
    return fragments;
  }
}
__name(parseLineTolerant, "parseLineTolerant");
async function closeLineReader(rl, fileStream) {
  rl?.close();
  if (!fileStream || fileStream.closed) {
    return;
  }
  const closed = finished(fileStream, { cleanup: true }).catch(() => void 0);
  if (!fileStream.destroyed) {
    fileStream.destroy();
  }
  await closed;
}
__name(closeLineReader, "closeLineReader");
async function readLines(filePath, count) {
  let fileStream;
  let rl;
  try {
    fileStream = fs7.createReadStream(filePath);
    rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    const results = [];
    for await (const line of rl) {
      if (results.length >= count) break;
      const trimmed = line.trim();
      if (trimmed.length === 0) continue;
      for (const obj of parseLineTolerant(trimmed, filePath)) {
        if (results.length >= count) break;
        results.push(obj);
      }
    }
    return results;
  } catch (error) {
    if (error.code !== "ENOENT") {
      debugLogger11.error(
        `Error reading first ${count} lines from ${filePath}:`,
        error
      );
    }
    return [];
  } finally {
    await closeLineReader(rl, fileStream);
  }
}
__name(readLines, "readLines");
async function read(filePath, options = {}) {
  let fileStream;
  let rl;
  try {
    fileStream = fs7.createReadStream(filePath);
    rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    const results = [];
    for await (const line of rl) {
      const trimmed = line.trim();
      if (trimmed.length === 0) continue;
      for (const obj of parseLineTolerant(trimmed, filePath)) {
        results.push(obj);
      }
    }
    return results;
  } catch (error) {
    if (error.code !== "ENOENT") {
      debugLogger11.error(`Error reading ${filePath}:`, error);
      if (options.throwOnNonEnoentError) {
        throw error;
      }
    }
    return [];
  } finally {
    await closeLineReader(rl, fileStream);
  }
}
__name(read, "read");
var ensuredDirs = /* @__PURE__ */ new Set();
function _resetEnsuredDirsCacheForTest() {
  ensuredDirs.clear();
}
__name(_resetEnsuredDirsCacheForTest, "_resetEnsuredDirsCacheForTest");
async function writeLine(filePath, data) {
  const lock = getFileLock(filePath);
  await lock.runExclusive(async () => {
    const line = `${JSON.stringify(data)}
`;
    const dir = path8.dirname(filePath);
    if (!ensuredDirs.has(dir)) {
      await fs7.promises.mkdir(dir, { recursive: true });
      ensuredDirs.add(dir);
    }
    await fs7.promises.appendFile(filePath, Buffer.from(line, "utf8"), {
      flush: true
    });
  });
}
__name(writeLine, "writeLine");
function writeLineSync(filePath, data) {
  const line = `${JSON.stringify(data)}
`;
  const dir = path8.dirname(filePath);
  if (!fs7.existsSync(dir)) {
    fs7.mkdirSync(dir, { recursive: true });
  }
  fs7.appendFileSync(filePath, Buffer.from(line, "utf8"), { flush: true });
}
__name(writeLineSync, "writeLineSync");
function write(filePath, data) {
  const lines = data.map((item) => JSON.stringify(item)).join("\n");
  const dir = path8.dirname(filePath);
  if (!fs7.existsSync(dir)) {
    fs7.mkdirSync(dir, { recursive: true });
  }
  atomicWriteFileSync(filePath, `${lines}
`, { encoding: "utf8" });
}
__name(write, "write");
async function countLines(filePath) {
  let fileStream;
  let rl;
  try {
    fileStream = fs7.createReadStream(filePath);
    rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    let count = 0;
    for await (const line of rl) {
      if (line.trim().length > 0) {
        count++;
      }
    }
    return count;
  } catch (error) {
    if (error.code !== "ENOENT") {
      debugLogger11.error(`Error counting lines in ${filePath}:`, error);
    }
    return 0;
  } finally {
    await closeLineReader(rl, fileStream);
  }
}
__name(countLines, "countLines");
function exists(filePath) {
  try {
    const stats = fs7.statSync(filePath);
    return stats.isFile() && stats.size > 0;
  } catch {
    return false;
  }
}
__name(exists, "exists");

// packages/core/src/services/tokenUsageService.ts
var debugLogger12 = createDebugLogger("TOKEN_USAGE");
var USAGE_DIR_NAME = "usage";
var FILE_PREFIX = "token-usage-";
var FILE_EXTENSION = ".jsonl";
var SCHEMA_VERSION = 1;
var UNKNOWN_AUTH_TYPE = "unknown";
function createEmptyTotals() {
  return {
    requests: 0,
    inputTokens: 0,
    outputTokens: 0,
    cachedTokens: 0,
    thoughtsTokens: 0,
    totalTokens: 0,
    apiDurationMs: 0
  };
}
__name(createEmptyTotals, "createEmptyTotals");
function addRecordToTotals(totals, record) {
  totals.requests += 1;
  totals.inputTokens += record.inputTokens;
  totals.outputTokens += record.outputTokens;
  totals.cachedTokens += record.cachedTokens;
  totals.thoughtsTokens += record.thoughtsTokens;
  totals.totalTokens += record.totalTokens;
  totals.apiDurationMs += record.apiDurationMs;
}
__name(addRecordToTotals, "addRecordToTotals");
function getLocalDateParts(date) {
  const year = date.getFullYear();
  const monthNumber = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return {
    date: `${year}-${monthNumber}-${day}`,
    month: `${year}-${monthNumber}`
  };
}
__name(getLocalDateParts, "getLocalDateParts");
function currentPeriodValue(period) {
  const parts = getLocalDateParts(/* @__PURE__ */ new Date());
  return period === "day" ? parts.date : parts.month;
}
__name(currentPeriodValue, "currentPeriodValue");
function isValidDay(value) {
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
  if (!match) {
    return false;
  }
  const year = Number(match[1]);
  const month = Number(match[2]);
  const day = Number(match[3]);
  if (month < 1 || month > 12 || day < 1) {
    return false;
  }
  const daysInMonth = [
    31,
    isLeapYear(year) ? 29 : 28,
    31,
    30,
    31,
    30,
    31,
    31,
    30,
    31,
    30,
    31
  ];
  return day <= daysInMonth[month - 1];
}
__name(isValidDay, "isValidDay");
function isValidMonth(value) {
  const match = /^(\d{4})-(\d{2})$/.exec(value);
  if (!match) {
    return false;
  }
  const month = Number(match[2]);
  return month >= 1 && month <= 12;
}
__name(isValidMonth, "isValidMonth");
function isLeapYear(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
__name(isLeapYear, "isLeapYear");
function normalizePeriodValue(period, value) {
  const normalized = value?.trim() || currentPeriodValue(period);
  const isValid = period === "day" ? isValidDay(normalized) : isValidMonth(normalized);
  if (!isValid) {
    throw new Error(
      `Invalid ${period} value "${normalized}". Expected ${period === "day" ? "YYYY-MM-DD" : "YYYY-MM"}.`
    );
  }
  return normalized;
}
__name(normalizePeriodValue, "normalizePeriodValue");
function usageDir() {
  return path9.join(Storage.getRuntimeBaseDir(), USAGE_DIR_NAME);
}
__name(usageDir, "usageDir");
function getTokenUsageFilePath(month) {
  if (!isValidMonth(month)) {
    throw new Error(`Invalid month value "${month}". Expected YYYY-MM.`);
  }
  return path9.join(usageDir(), `${FILE_PREFIX}${month}${FILE_EXTENSION}`);
}
__name(getTokenUsageFilePath, "getTokenUsageFilePath");
function toNonNegativeInteger(value) {
  if (!Number.isFinite(value) || value === void 0 || value <= 0) {
    return 0;
  }
  return Math.trunc(value);
}
__name(toNonNegativeInteger, "toNonNegativeInteger");
function calculateInputTokens(event) {
  const inputTokens = toNonNegativeInteger(event.input_token_count);
  if (inputTokens > 0) {
    return inputTokens;
  }
  return toNonNegativeInteger(event.cached_content_token_count);
}
__name(calculateInputTokens, "calculateInputTokens");
function calculateTotalTokens(event) {
  const total = toNonNegativeInteger(event.total_token_count);
  if (total > 0) {
    return total;
  }
  return calculateInputTokens(event) + toNonNegativeInteger(event.output_token_count) + toNonNegativeInteger(event.thoughts_token_count);
}
__name(calculateTotalTokens, "calculateTotalTokens");
function apiResponseEventToTokenUsageRecord(config, event) {
  const timestamp = event["event.timestamp"] || (/* @__PURE__ */ new Date()).toISOString();
  const date = new Date(timestamp);
  const localParts = getLocalDateParts(
    Number.isNaN(date.getTime()) ? /* @__PURE__ */ new Date() : date
  );
  return {
    schemaVersion: SCHEMA_VERSION,
    id: randomUUID(),
    timestamp,
    localDate: localParts.date,
    localMonth: localParts.month,
    sessionId: config.getSessionId(),
    model: event.model || "unknown",
    authType: event.auth_type || UNKNOWN_AUTH_TYPE,
    source: event.subagent_name || MAIN_SOURCE,
    inputTokens: calculateInputTokens(event),
    outputTokens: toNonNegativeInteger(event.output_token_count),
    cachedTokens: toNonNegativeInteger(event.cached_content_token_count),
    thoughtsTokens: toNonNegativeInteger(event.thoughts_token_count),
    totalTokens: calculateTotalTokens(event),
    apiDurationMs: toNonNegativeInteger(event.duration_ms)
  };
}
__name(apiResponseEventToTokenUsageRecord, "apiResponseEventToTokenUsageRecord");
function isTokenUsageRecord(value) {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    return false;
  }
  const record = value;
  return typeof record.id === "string" && typeof record.sessionId === "string" && typeof record.schemaVersion === "number" && Number.isInteger(record.schemaVersion) && record.schemaVersion > 0 && record.schemaVersion <= SCHEMA_VERSION && typeof record.timestamp === "string" && typeof record.localDate === "string" && typeof record.localMonth === "string" && typeof record.model === "string" && typeof record.authType === "string" && typeof record.source === "string" && typeof record.inputTokens === "number" && typeof record.outputTokens === "number" && typeof record.cachedTokens === "number" && typeof record.thoughtsTokens === "number" && typeof record.totalTokens === "number" && typeof record.apiDurationMs === "number";
}
__name(isTokenUsageRecord, "isTokenUsageRecord");
async function readRecordsForMonth(month) {
  const filePath = getTokenUsageFilePath(month);
  const records = await read(filePath, {
    throwOnNonEnoentError: true
  });
  const valid = [];
  let dropped = 0;
  for (const record of records) {
    if (isTokenUsageRecord(record)) {
      valid.push(record);
    } else {
      dropped++;
    }
  }
  if (dropped > 0) {
    debugLogger12.warn(
      `Dropped ${dropped}/${records.length} invalid record(s) from ${filePath}`
    );
  }
  return valid;
}
__name(readRecordsForMonth, "readRecordsForMonth");
function summarizeRecords(period, value, records) {
  const totals = createEmptyTotals();
  const byModel = /* @__PURE__ */ new Map();
  const byAuthType = /* @__PURE__ */ new Map();
  const byModelAndAuthType = /* @__PURE__ */ new Map();
  const bySource = /* @__PURE__ */ new Map();
  const getGroup = /* @__PURE__ */ __name((map, key, fields) => {
    let group = map.get(key);
    if (!group) {
      group = {
        key,
        ...fields,
        ...createEmptyTotals()
      };
      map.set(key, group);
    }
    return group;
  }, "getGroup");
  for (const record of records) {
    addRecordToTotals(totals, record);
    addRecordToTotals(
      getGroup(byModel, record.model, { model: record.model }),
      record
    );
    addRecordToTotals(
      getGroup(byAuthType, record.authType, { authType: record.authType }),
      record
    );
    addRecordToTotals(
      getGroup(byModelAndAuthType, `${record.model}|${record.authType}`, {
        model: record.model,
        authType: record.authType
      }),
      record
    );
    addRecordToTotals(
      getGroup(bySource, record.source, { source: record.source }),
      record
    );
  }
  const sortGroups = /* @__PURE__ */ __name((groups) => [...groups].sort((a, b) => {
    if (b.totalTokens !== a.totalTokens) {
      return b.totalTokens - a.totalTokens;
    }
    return a.key.localeCompare(b.key);
  }), "sortGroups");
  return {
    period,
    value,
    generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
    totals,
    byModel: sortGroups(byModel.values()),
    byAuthType: sortGroups(byAuthType.values()),
    byModelAndAuthType: sortGroups(byModelAndAuthType.values()),
    bySource: sortGroups(bySource.values())
  };
}
__name(summarizeRecords, "summarizeRecords");
async function recordTokenUsageFromApiResponse(config, event) {
  const record = apiResponseEventToTokenUsageRecord(config, event);
  await writeLine(getTokenUsageFilePath(record.localMonth), record);
}
__name(recordTokenUsageFromApiResponse, "recordTokenUsageFromApiResponse");
var lastLoggedTimeByCode = /* @__PURE__ */ new Map();
var suppressedCountByCode = /* @__PURE__ */ new Map();
var TOKEN_USAGE_FAILURE_LOG_COOLDOWN_MS = 6e4;
var _now = /* @__PURE__ */ __name(() => Date.now(), "_now");
function logTokenUsageWriteFailure(error) {
  debugLogger12.warn("Failed to record token usage:", error);
  const code = error.code;
  if (code && code !== "ENOENT") {
    const now = _now();
    const lastTime = lastLoggedTimeByCode.get(code) ?? 0;
    if (now - lastTime > TOKEN_USAGE_FAILURE_LOG_COOLDOWN_MS) {
      lastLoggedTimeByCode.set(code, now);
      const suppressedCount = suppressedCountByCode.get(code) ?? 0;
      suppressedCountByCode.delete(code);
      const message = error instanceof Error ? error.message : String(error);
      console.error(
        `[token-usage] Write failed (${code}):`,
        suppressedCount > 0 ? `${message} (${suppressedCount} similar suppressed since last log)` : message
      );
    } else {
      suppressedCountByCode.set(
        code,
        (suppressedCountByCode.get(code) ?? 0) + 1
      );
    }
  }
}
__name(logTokenUsageWriteFailure, "logTokenUsageWriteFailure");
function recordTokenUsageFromApiResponseBestEffort(config, event) {
  try {
    const record = apiResponseEventToTokenUsageRecord(config, event);
    void writeLine(getTokenUsageFilePath(record.localMonth), record).catch(logTokenUsageWriteFailure);
  } catch (error) {
    logTokenUsageWriteFailure(error);
  }
}
__name(recordTokenUsageFromApiResponseBestEffort, "recordTokenUsageFromApiResponseBestEffort");
async function queryTokenUsage(query) {
  const value = normalizePeriodValue(query.period, query.value);
  const month = query.period === "day" ? value.slice(0, 7) : value;
  const records = (await readRecordsForMonth(month)).filter(
    (record) => query.period === "day" ? record.localDate === value : record.localMonth === value
  );
  return summarizeRecords(query.period, value, records);
}
__name(queryTokenUsage, "queryTokenUsage");
function csvEscape(value) {
  const stringValue = value === void 0 ? "" : String(value);
  const trimmed = stringValue.trimStart();
  const sanitized = /^[=+\-@]/.test(trimmed) || /^[\t\r\n]/.test(stringValue) ? `'${stringValue}` : stringValue;
  if (/[",\n\r]/.test(sanitized)) {
    return `"${sanitized.replace(/"/g, '""')}"`;
  }
  return sanitized;
}
__name(csvEscape, "csvEscape");
function groupRows(period, value, groupType, groups) {
  return groups.map((group) => [
    period,
    value,
    groupType,
    group.key,
    group.model ?? "",
    group.authType ?? "",
    group.source ?? "",
    String(group.requests),
    String(group.inputTokens),
    String(group.outputTokens),
    String(group.cachedTokens),
    String(group.thoughtsTokens),
    String(group.totalTokens),
    String(group.apiDurationMs)
  ]);
}
__name(groupRows, "groupRows");
function formatTokenUsageSummaryAsCsv(summary) {
  const header = [
    "period",
    "value",
    "group_type",
    "group_key",
    "model",
    "auth_type",
    "source",
    "requests",
    "input_tokens",
    "output_tokens",
    "cached_tokens",
    "thoughts_tokens",
    "total_tokens",
    "api_duration_ms"
  ];
  const rows = [
    [
      summary.period,
      summary.value,
      "total",
      "total",
      "",
      "",
      "",
      String(summary.totals.requests),
      String(summary.totals.inputTokens),
      String(summary.totals.outputTokens),
      String(summary.totals.cachedTokens),
      String(summary.totals.thoughtsTokens),
      String(summary.totals.totalTokens),
      String(summary.totals.apiDurationMs)
    ],
    ...groupRows(summary.period, summary.value, "model", summary.byModel),
    ...groupRows(
      summary.period,
      summary.value,
      "auth_type",
      summary.byAuthType
    ),
    ...groupRows(
      summary.period,
      summary.value,
      "model_auth_type",
      summary.byModelAndAuthType
    ),
    ...groupRows(summary.period, summary.value, "source", summary.bySource)
  ];
  return [
    header.join(","),
    ...rows.map((row) => row.map(csvEscape).join(","))
  ].join("\n");
}
__name(formatTokenUsageSummaryAsCsv, "formatTokenUsageSummaryAsCsv");
function formatTokenUsageSummaryAsJson(summary) {
  return `${JSON.stringify(summary, null, 2)}
`;
}
__name(formatTokenUsageSummaryAsJson, "formatTokenUsageSummaryAsJson");
async function exportTokenUsageSummary(options) {
  const summary = await queryTokenUsage(options);
  return options.format === "json" ? formatTokenUsageSummaryAsJson(summary) : `${formatTokenUsageSummaryAsCsv(summary)}
`;
}
__name(exportTokenUsageSummary, "exportTokenUsageSummary");

// packages/core/src/utils/chat-recording-suppression-context.ts
init_esbuild_shims();
import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
var chatRecordingSuppressionContext = new AsyncLocalStorage5();
function isChatRecordingSuppressed() {
  return chatRecordingSuppressionContext.getStore() === true;
}
__name(isChatRecordingSuppressed, "isChatRecordingSuppressed");
function runWithChatRecordingSuppressed(fn) {
  return chatRecordingSuppressionContext.run(true, fn);
}
__name(runWithChatRecordingSuppressed, "runWithChatRecordingSuppressed");

// packages/core/src/telemetry/loggers.ts
var shouldLogUserPrompts = /* @__PURE__ */ __name((config) => config.getTelemetryLogPromptsEnabled(), "shouldLogUserPrompts");
function getCommonAttributes(config) {
  return {
    "session.id": config.getSessionId()
  };
}
__name(getCommonAttributes, "getCommonAttributes");
function recordUiTelemetryEventToChat(config, uiEvent) {
  if (isChatRecordingSuppressed()) return;
  config.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
}
__name(recordUiTelemetryEventToChat, "recordUiTelemetryEventToChat");
function logStartSession(config, event) {
  QwenLogger.getInstance(config)?.logStartSessionEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_CLI_CONFIG,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    model: event.model,
    sandbox_enabled: event.sandbox_enabled,
    core_tools_enabled: event.core_tools_enabled,
    approval_mode: event.approval_mode,
    file_filtering_respect_git_ignore: event.file_filtering_respect_git_ignore,
    debug_mode: event.debug_enabled,
    truncate_tool_output_threshold: event.truncate_tool_output_threshold,
    truncate_tool_output_lines: event.truncate_tool_output_lines,
    mcp_servers: event.mcp_servers,
    mcp_servers_count: event.mcp_servers_count,
    mcp_tools: event.mcp_tools,
    mcp_tools_count: event.mcp_tools_count,
    hooks: event.hooks,
    ide_enabled: event.ide_enabled,
    interactive_shell_enabled: event.interactive_shell_enabled,
    output_format: event.output_format,
    skills: event.skills,
    subagents: event.subagents
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: "CLI configuration loaded.",
    attributes
  };
  logger.emit(logRecord);
}
__name(logStartSession, "logStartSession");
function logUserPrompt(config, event) {
  QwenLogger.getInstance(config)?.logNewPromptEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_USER_PROMPT,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    prompt_length: event.prompt_length,
    prompt_id: event.prompt_id
  };
  if (event.auth_type) {
    attributes["auth_type"] = event.auth_type;
  }
  if (event.model) {
    attributes["model"] = event.model;
  }
  if (shouldLogUserPrompts(config)) {
    attributes["prompt"] = event.prompt;
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `User prompt. Length: ${event.prompt_length}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logUserPrompt, "logUserPrompt");
function logUserRetry(config, event) {
  QwenLogger.getInstance(config)?.logRetryEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_USER_RETRY,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    prompt_id: event.prompt_id
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `User retry.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logUserRetry, "logUserRetry");
function logToolCall(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_TOOL_CALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent, config.getSessionId());
  if (!isInternalPromptId(event.prompt_id)) {
    recordUiTelemetryEventToChat(config, uiEvent);
  }
  QwenLogger.getInstance(config)?.logToolCallEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_TOOL_CALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    function_args: safeJsonStringify(event.function_args, 2)
  };
  if (event.error) {
    attributes["error.message"] = event.error;
    if (event.error_type) {
      attributes["error.type"] = event.error_type;
    }
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Tool call: ${event.function_name}${event.decision ? `. Decision: ${event.decision}` : ""}. Success: ${event.success}. Duration: ${event.duration_ms}ms.`,
    attributes
  };
  logger.emit(logRecord);
  recordToolCallMetrics(config, event.duration_ms, {
    function_name: event.function_name,
    success: event.success,
    decision: event.decision,
    tool_type: event.tool_type
  });
}
__name(logToolCall, "logToolCall");
function logToolOutputTruncated(config, event) {
  QwenLogger.getInstance(config)?.logToolOutputTruncatedEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    // event class's `eventName` (short, no prefix) leaks via spread — override with
    // full namespaced constant for OTel compliance. Same pattern as other event loggers.
    "event.name": EVENT_TOOL_OUTPUT_TRUNCATED,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Tool output truncated for ${event.tool_name}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logToolOutputTruncated, "logToolOutputTruncated");
function logFileOperation(config, event) {
  QwenLogger.getInstance(config)?.logFileOperationEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_FILE_OPERATION,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    tool_name: event.tool_name,
    operation: event.operation
  };
  if (event.lines) {
    attributes["lines"] = event.lines;
  }
  if (event.mimetype) {
    attributes["mimetype"] = event.mimetype;
  }
  if (event.extension) {
    attributes["extension"] = event.extension;
  }
  if (event.programming_language) {
    attributes["programming_language"] = event.programming_language;
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `File operation: ${event.operation}. Lines: ${event.lines}.`,
    attributes
  };
  logger.emit(logRecord);
  recordFileOperationMetric(config, {
    operation: event.operation,
    lines: event.lines,
    mimetype: event.mimetype,
    extension: event.extension,
    programming_language: event.programming_language
  });
}
__name(logFileOperation, "logFileOperation");
function logApiRequest(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_REQUEST,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API request to ${event.model}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logApiRequest, "logApiRequest");
function logFlashFallback(config, event) {
  QwenLogger.getInstance(config)?.logFlashFallbackEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_FLASH_FALLBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Switching to flash as Fallback.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logFlashFallback, "logFlashFallback");
function logRipgrepFallback(config, event) {
  QwenLogger.getInstance(config)?.logRipgrepFallbackEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_RIPGREP_FALLBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Switching to grep as fallback.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logRipgrepFallback, "logRipgrepFallback");
function logApiError(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_ERROR,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent, config.getSessionId());
  if (!isInternalPromptId(event.prompt_id)) {
    recordUiTelemetryEventToChat(config, uiEvent);
  }
  QwenLogger.getInstance(config)?.logApiErrorEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_ERROR,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    ["error.message"]: event.error_message,
    model_name: event.model,
    duration: event.duration_ms
  };
  if (event.error_type) {
    attributes["error.type"] = event.error_type;
  }
  if (typeof event.status_code === "number") {
    attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API error for ${event.model}. Error: ${event.error_message}. Duration: ${event.duration_ms}ms.`,
    attributes
  };
  logger.emit(logRecord);
  recordApiErrorMetrics(config, event.duration_ms, {
    model: event.model,
    status_code: event.status_code,
    error_type: event.error_type
  });
}
__name(logApiError, "logApiError");
function logApiCancel(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_CANCEL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent, config.getSessionId());
  QwenLogger.getInstance(config)?.logApiCancelEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_CANCEL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    model_name: event.model
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API request cancelled for ${event.model}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logApiCancel, "logApiCancel");
function logApiResponse(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_API_RESPONSE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent, config.getSessionId());
  if (!isInternalPromptId(event.prompt_id)) {
    if (config.getUsageStatisticsEnabled()) {
      recordTokenUsageFromApiResponseBestEffort(config, event);
    }
    recordUiTelemetryEventToChat(config, uiEvent);
  }
  QwenLogger.getInstance(config)?.logApiResponseEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_RESPONSE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  if (event.response_text) {
    attributes["response_text"] = event.response_text;
  }
  if (event.status_code) {
    if (typeof event.status_code === "number") {
      attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
    }
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API response from ${event.model}. Status: ${event.status_code || "N/A"}. Duration: ${event.duration_ms}ms.`,
    attributes
  };
  logger.emit(logRecord);
  recordApiResponseMetrics(config, event.duration_ms, {
    model: event.model,
    status_code: event.status_code
  });
  recordTokenUsageMetrics(config, event.input_token_count, {
    model: event.model,
    type: "input"
  });
  recordTokenUsageMetrics(config, event.output_token_count, {
    model: event.model,
    type: "output"
  });
  recordTokenUsageMetrics(config, event.cached_content_token_count, {
    model: event.model,
    type: "cache"
  });
  recordTokenUsageMetrics(config, event.thoughts_token_count, {
    model: event.model,
    type: "thought"
  });
}
__name(logApiResponse, "logApiResponse");
function logLoopDetected(config, event) {
  QwenLogger.getInstance(config)?.logLoopDetectedEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Loop detected. Type: ${event.loop_type}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logLoopDetected, "logLoopDetected");
function logLoopDetectionDisabled(config, _event) {
  QwenLogger.getInstance(config)?.logLoopDetectionDisabledEvent();
}
__name(logLoopDetectionDisabled, "logLoopDetectionDisabled");
function logNextSpeakerCheck(config, event) {
  QwenLogger.getInstance(config)?.logNextSpeakerCheck(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_NEXT_SPEAKER_CHECK
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Next speaker check.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logNextSpeakerCheck, "logNextSpeakerCheck");
function logSlashCommand(config, event) {
  QwenLogger.getInstance(config)?.logSlashCommandEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_SLASH_COMMAND
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Slash command: ${event.command}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logSlashCommand, "logSlashCommand");
function logIdeConnection(config, event) {
  QwenLogger.getInstance(config)?.logIdeConnectionEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_IDE_CONNECTION
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Ide connection. Type: ${event.connection_type}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logIdeConnection, "logIdeConnection");
function logConversationFinishedEvent(config, event) {
  QwenLogger.getInstance(config)?.logConversationFinishedEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CONVERSATION_FINISHED
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Conversation finished.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logConversationFinishedEvent, "logConversationFinishedEvent");
function logChatCompression(config, event) {
  QwenLogger.getInstance(config)?.logChatCompressionEvent(event);
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CHAT_COMPRESSION
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Chat compression (Saved ${event.tokens_before - event.tokens_after} tokens)`,
    attributes
  };
  logger.emit(logRecord);
  recordChatCompressionMetrics(config, {
    tokens_before: event.tokens_before,
    tokens_after: event.tokens_after
  });
}
__name(logChatCompression, "logChatCompression");
function logKittySequenceOverflow(config, event) {
  QwenLogger.getInstance(config)?.logKittySequenceOverflowEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Kitty sequence buffer overflow: ${event.sequence_length} bytes`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logKittySequenceOverflow, "logKittySequenceOverflow");
function logContentRetry(config, event) {
  QwenLogger.getInstance(config)?.logContentRetryEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CONTENT_RETRY
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Content retry attempt ${event.attempt_number} due to ${event.error_type}.`,
    attributes
  };
  logger.emit(logRecord);
  recordContentRetry(config);
}
__name(logContentRetry, "logContentRetry");
function logContentRetryFailure(config, event) {
  QwenLogger.getInstance(config)?.logContentRetryFailureEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_CONTENT_RETRY_FAILURE
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `All content retries failed after ${event.total_attempts} attempts.`,
    attributes
  };
  logger.emit(logRecord);
  recordContentRetryFailure(config);
}
__name(logContentRetryFailure, "logContentRetryFailure");
function logApiRetry(config, event) {
  QwenLogger.getInstance(config)?.logApiRetryEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_API_RETRY
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `API retry attempt ${event.attempt_number} for ${event.model} (status ${event.status_code ?? "unknown"}).`,
    attributes
  };
  logger.emit(logRecord);
  recordApiRetry(config, { model: event.model });
}
__name(logApiRetry, "logApiRetry");
function logSubagentExecution(config, event) {
  QwenLogger.getInstance(config)?.logSubagentExecutionEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_SUBAGENT_EXECUTION,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Subagent execution: ${event.subagent_name}.`,
    attributes
  };
  logger.emit(logRecord);
  recordSubagentExecutionMetrics(
    config,
    event.subagent_name,
    event.status,
    event.terminate_reason
  );
}
__name(logSubagentExecution, "logSubagentExecution");
function logModelSlashCommand(config, event) {
  QwenLogger.getInstance(config)?.logModelSlashCommandEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_MODEL_SLASH_COMMAND
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Model slash command. Model: ${event.model_name}`,
    attributes
  };
  logger.emit(logRecord);
  recordModelSlashCommand(config, event);
}
__name(logModelSlashCommand, "logModelSlashCommand");
function logHookCall(config, event) {
  QwenLogger.getInstance(config)?.logHookCallEvent(event);
}
__name(logHookCall, "logHookCall");
function logExtensionInstallEvent(config, event) {
  QwenLogger.getInstance(config)?.logExtensionInstallEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_INSTALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    extension_name: event.extension_name,
    extension_version: event.extension_version,
    extension_source: event.extension_source,
    status: event.status
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Installed extension ${event.extension_name}`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logExtensionInstallEvent, "logExtensionInstallEvent");
function logExtensionUninstall(config, event) {
  QwenLogger.getInstance(config)?.logExtensionUninstallEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_UNINSTALL,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Uninstalled extension ${event.extension_name}`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logExtensionUninstall, "logExtensionUninstall");
async function logExtensionUpdateEvent(config, event) {
  QwenLogger.getInstance(config)?.logExtensionUpdateEvent(event);
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_UPDATE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    extension_name: event.extension_name,
    extension_id: event.extension_id,
    extension_previous_version: event.extension_previous_version,
    extension_version: event.extension_version,
    extension_source: event.extension_source
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Updated extension ${event.extension_name} from ${event.extension_previous_version} to ${event.extension_version}`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logExtensionUpdateEvent, "logExtensionUpdateEvent");
function logExtensionEnable(config, event) {
  QwenLogger.getInstance(config)?.logExtensionEnableEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_ENABLE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Enabled extension ${event.extension_name}`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logExtensionEnable, "logExtensionEnable");
function logExtensionDisable(config, event) {
  QwenLogger.getInstance(config)?.logExtensionDisableEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_EXTENSION_DISABLE,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Disabled extension ${event.extension_name}`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logExtensionDisable, "logExtensionDisable");
function logAuth(config, event) {
  QwenLogger.getInstance(config)?.logAuthEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_AUTH,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    auth_type: event.auth_type,
    action_type: event.action_type,
    status: event.status
  };
  if (event.error_message) {
    attributes["error.message"] = event.error_message;
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Auth event: ${event.action_type} ${event.status} for ${event.auth_type}`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logAuth, "logAuth");
function logSkillLaunch(config, event) {
  QwenLogger.getInstance(config)?.logSkillLaunchEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_SKILL_LAUNCH,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Skill launch: ${event.skill_name}. Success: ${event.success}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logSkillLaunch, "logSkillLaunch");
function recordSkillInvocation(config, event) {
  uiTelemetryService.recordSkillInvocation(
    event.skillName,
    event.success,
    config.getSessionId()
  );
}
__name(recordSkillInvocation, "recordSkillInvocation");
function logUserFeedback(config, event) {
  const uiEvent = {
    ...event,
    "event.name": EVENT_USER_FEEDBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  uiTelemetryService.addEvent(uiEvent, config.getSessionId());
  recordUiTelemetryEventToChat(config, uiEvent);
  QwenLogger.getInstance(config)?.logUserFeedbackEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_USER_FEEDBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `User feedback: Rating ${event.rating} for session ${event.session_id}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logUserFeedback, "logUserFeedback");
function logArenaSessionStarted(config, event) {
  QwenLogger.getInstance(config)?.logArenaSessionStartedEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    model_ids: JSON.stringify(event.model_ids),
    "event.name": EVENT_ARENA_SESSION_STARTED,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Arena session started. Agents: ${event.model_ids.length}.`,
    attributes
  };
  logger.emit(logRecord);
  recordArenaSessionStartedMetrics(config);
}
__name(logArenaSessionStarted, "logArenaSessionStarted");
function logArenaAgentCompleted(config, event) {
  QwenLogger.getInstance(config)?.logArenaAgentCompletedEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_ARENA_AGENT_COMPLETED,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Arena agent ${event.agent_model_id} ${event.status}. Duration: ${event.duration_ms}ms. Tokens: ${event.total_tokens}.`,
    attributes
  };
  logger.emit(logRecord);
  recordArenaAgentCompletedMetrics(
    config,
    event.agent_model_id,
    event.status,
    event.duration_ms,
    event.input_tokens,
    event.output_tokens
  );
}
__name(logArenaAgentCompleted, "logArenaAgentCompleted");
function logArenaSessionEnded(config, event) {
  QwenLogger.getInstance(config)?.logArenaSessionEndedEvent(event);
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    ...event,
    "event.name": EVENT_ARENA_SESSION_ENDED,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Arena session ended: ${event.status}.${event.winner_model_id ? ` Winner: ${event.winner_model_id}.` : ""}`,
    attributes
  };
  logger.emit(logRecord);
  recordArenaSessionEndedMetrics(
    config,
    event.status,
    event.display_backend,
    event.duration_ms,
    event.winner_model_id
  );
}
__name(logArenaSessionEnded, "logArenaSessionEnded");
function logPromptSuggestion(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_PROMPT_SUGGESTION,
    "event.timestamp": event["event.timestamp"],
    outcome: event.outcome
  };
  if (event.prompt_id) {
    attributes["prompt_id"] = event.prompt_id;
  }
  if (event.accept_method) {
    attributes["accept_method"] = event.accept_method;
  }
  if (event.accept_source) {
    attributes["accept_source"] = event.accept_source;
  }
  if (event.time_to_accept_ms !== void 0) {
    attributes["time_to_accept_ms"] = event.time_to_accept_ms;
  }
  if (event.time_to_ignore_ms !== void 0) {
    attributes["time_to_ignore_ms"] = event.time_to_ignore_ms;
  }
  if (event.time_to_first_keystroke_ms !== void 0) {
    attributes["time_to_first_keystroke_ms"] = event.time_to_first_keystroke_ms;
  }
  if (event.suggestion_length !== void 0) {
    attributes["suggestion_length"] = event.suggestion_length;
  }
  if (event.similarity !== void 0) {
    attributes["similarity"] = event.similarity;
  }
  if (event.was_focused_when_shown !== void 0) {
    attributes["was_focused_when_shown"] = event.was_focused_when_shown;
  }
  if (event.reason) {
    attributes["reason"] = event.reason;
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Prompt suggestion: ${event.outcome}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logPromptSuggestion, "logPromptSuggestion");
function logSpeculation(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_SPECULATION,
    "event.timestamp": event["event.timestamp"],
    outcome: event.outcome,
    turns_used: event.turns_used,
    files_written: event.files_written,
    tool_use_count: event.tool_use_count,
    duration_ms: event.duration_ms,
    had_pipelined_suggestion: event.had_pipelined_suggestion
  };
  if (event.boundary_type) {
    attributes["boundary_type"] = event.boundary_type;
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Speculation: ${event.outcome}.`,
    attributes
  };
  logger.emit(logRecord);
}
__name(logSpeculation, "logSpeculation");
function logWorkflowKeyword(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_WORKFLOW_KEYWORD,
    "event.timestamp": event["event.timestamp"]
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  logger.emit({ body: "Workflow keyword trigger fired.", attributes });
}
__name(logWorkflowKeyword, "logWorkflowKeyword");
function logWorkflowRun(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_WORKFLOW_RUN,
    "event.timestamp": event["event.timestamp"],
    status: event.status,
    agents_dispatched: event.agents_dispatched,
    agents_completed: event.agents_completed,
    phase_count: event.phase_count,
    tokens_spent: event.tokens_spent,
    duration_ms: event.duration_ms
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  logger.emit({ body: `Workflow run ${event.status}.`, attributes });
}
__name(logWorkflowRun, "logWorkflowRun");
function logMemoryExtract(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_MEMORY_EXTRACT,
    "event.timestamp": event["event.timestamp"],
    trigger: event.trigger,
    status: event.status,
    patches_count: event.patches_count,
    touched_topics: event.touched_topics,
    duration_ms: event.duration_ms
  };
  if (event.skipped_reason) {
    attributes["skipped_reason"] = event.skipped_reason;
  }
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  logger.emit({
    body: `Memory extract: ${event.status}. Patches: ${event.patches_count}. Topics: ${event.touched_topics || "none"}.`,
    attributes
  });
  recordMemoryExtractMetrics(config, event.duration_ms, {
    trigger: event.trigger,
    status: event.status,
    patches_count: event.patches_count
  });
}
__name(logMemoryExtract, "logMemoryExtract");
function logMemoryDream(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_MEMORY_DREAM,
    "event.timestamp": event["event.timestamp"],
    trigger: event.trigger,
    status: event.status,
    deduped_entries: event.deduped_entries,
    touched_topics_count: event.touched_topics_count,
    touched_topics: event.touched_topics,
    duration_ms: event.duration_ms
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  logger.emit({
    body: `Memory dream: ${event.status}. Deduped: ${event.deduped_entries}. Topics: ${event.touched_topics || "none"}.`,
    attributes
  });
  recordMemoryDreamMetrics(config, event.duration_ms, {
    trigger: event.trigger,
    status: event.status,
    deduped_entries: event.deduped_entries
  });
}
__name(logMemoryDream, "logMemoryDream");
function logMemoryRecall(config, event) {
  if (!isTelemetrySdkInitialized()) return;
  const attributes = {
    ...getCommonAttributes(config),
    "event.name": EVENT_MEMORY_RECALL,
    "event.timestamp": event["event.timestamp"],
    query_length: event.query_length,
    docs_scanned: event.docs_scanned,
    docs_selected: event.docs_selected,
    strategy: event.strategy,
    duration_ms: event.duration_ms
  };
  const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
  logger.emit({
    body: `Memory recall: strategy=${event.strategy}. Selected ${event.docs_selected}/${event.docs_scanned} docs.`,
    attributes
  });
  recordMemoryRecallMetrics(config, event.duration_ms, {
    strategy: event.strategy,
    docs_selected: event.docs_selected
  });
}
__name(logMemoryRecall, "logMemoryRecall");

// packages/core/src/memory/memoryAge.ts
init_esbuild_shims();
function memoryAgeDays(mtimeMs) {
  return Math.max(0, Math.floor((Date.now() - mtimeMs) / 864e5));
}
__name(memoryAgeDays, "memoryAgeDays");
function memoryAge(mtimeMs) {
  const d = memoryAgeDays(mtimeMs);
  if (d === 0) return "today";
  if (d === 1) return "yesterday";
  return `${d} days ago`;
}
__name(memoryAge, "memoryAge");
function memoryFreshnessText(mtimeMs) {
  const d = memoryAgeDays(mtimeMs);
  if (d <= 1) return "";
  return `This memory is ${d} days old. Memories are point-in-time observations, not live state \u2014 claims about code behavior or file:line citations may be outdated. Verify against current code before asserting as fact.`;
}
__name(memoryFreshnessText, "memoryFreshnessText");
function memoryFreshnessNote(mtimeMs) {
  const text = memoryFreshnessText(mtimeMs);
  if (!text) return "";
  return `<system-reminder>${text}</system-reminder>
`;
}
__name(memoryFreshnessNote, "memoryFreshnessNote");

// packages/core/src/tools/read-file.ts
var debugLogger13 = createDebugLogger("READ_FILE_CACHE");
var ReadFileToolInvocation = class extends BaseToolInvocation {
  constructor(config, params) {
    super(params);
    this.config = config;
  }
  static {
    __name(this, "ReadFileToolInvocation");
  }
  getDescription() {
    const relativePath = makeRelative(
      this.params.file_path,
      this.config.getTargetDir()
    );
    const shortPath = shortenPath(relativePath);
    if (this.params.pages) {
      return `${shortPath} (pages ${this.params.pages})`;
    }
    const { offset, limit } = this.params;
    if (offset !== void 0 && limit !== void 0) {
      return `${shortPath} (lines ${offset + 1}-${offset + limit})`;
    } else if (offset !== void 0) {
      return `${shortPath} (from line ${offset + 1})`;
    } else if (limit !== void 0) {
      return `${shortPath} (first ${limit} lines)`;
    }
    return shortPath;
  }
  toolLocations() {
    return [{ path: this.params.file_path, line: this.params.offset }];
  }
  /**
   * Returns 'ask' for paths outside the workspace/qwen-managed temp/userSkills
   * directories, so that external file reads require user confirmation.
   */
  async getDefaultPermission() {
    const filePath = path10.resolve(this.params.file_path);
    const workspaceContext = this.config.getWorkspaceContext();
    const allowedRoots = [
      this.config.storage.getProjectTempDir(),
      // Background subagent transcripts live under <projectDir>/subagents/ and
      // are advertised to the model as polling targets via read_file.
      path10.join(this.config.storage.getProjectDir(), "subagents"),
      Storage.getGlobalTempDir(),
      ...this.config.storage.getUserSkillsDirs(),
      Storage.getUserExtensionsDir()
    ];
    if (workspaceContext.isPathWithinWorkspace(filePath) || isSubpaths(allowedRoots, filePath) || // isAnyAutoMemPath narrows to the managed auto-memory roots
    // (per-project + user-level under ~/.qwen/memories/) — never the
    // broad getMemoryBaseDir() — to avoid exposing sensitive ~/.qwen
    // files such as settings.json or OAuth credentials.
    isAnyAutoMemPath(filePath, this.config.getTargetDir())) {
      return "allow";
    }
    return "ask";
  }
  async execute() {
    const absPath = path10.resolve(this.params.file_path);
    const projectRoot = this.config.getTargetDir();
    const isAutoMem = isAnyAutoMemPath(absPath, projectRoot);
    const cacheEnabled = !this.config.getFileReadCacheDisabled();
    const useFastPath = cacheEnabled && !isAutoMem;
    const cache = this.config.getFileReadCache();
    const isFullRead = this.params.offset === void 0 && this.params.limit === void 0 && this.params.pages === void 0;
    let stats;
    try {
      stats = await fs8.stat(absPath);
    } catch (err) {
      debugLogger13.debug("stat-failed", {
        path: absPath,
        code: err.code
      });
    }
    if (useFastPath && stats && isFullRead) {
      const status = cache.check(stats);
      if (status.state === "fresh" && status.entry.lastReadAt !== void 0 && status.entry.lastReadWasFull && status.entry.lastReadCacheable && // Only quote-back if that read is still in history (issue
      // #4239: idle microcompaction flips this off when it blanks it).
      status.entry.readResidentInHistory && (status.entry.lastWriteAt === void 0 || status.entry.lastReadAt > status.entry.lastWriteAt)) {
        debugLogger13.debug("hit", { path: absPath });
        return this.unchangedResult(absPath);
      }
      debugLogger13.debug("miss", { path: absPath, state: status.state });
    }
    const result = await processSingleFileContent(
      this.params.file_path,
      this.config,
      {
        offset: this.params.offset,
        limit: this.params.limit,
        pages: this.params.pages
      }
    );
    if (result.error) {
      return {
        llmContent: result.llmContent,
        returnDisplay: result.returnDisplay || "Error reading file",
        error: {
          message: result.error,
          type: result.errorType
        }
      };
    }
    if (cacheEnabled && (result.stats ?? stats)) {
      const cacheable = typeof result.llmContent === "string" && result.originalLineCount !== void 0;
      const recordStats = result.stats ?? stats;
      cache.recordRead(absPath, recordStats, {
        full: isFullRead && !result.isTruncated,
        cacheable
      });
    }
    let llmContent;
    if (result.isTruncated && result.linesShown && result.originalLineCount !== void 0) {
      const [start, end] = result.linesShown;
      const total = result.originalLineCount;
      llmContent = `Showing lines ${start}-${end} of ${total} total lines.

---

${result.llmContent}`;
    } else {
      llmContent = result.llmContent || "";
    }
    if (typeof llmContent === "string" && isAutoMem) {
      try {
        const memStat = stats ?? await fs8.stat(absPath);
        const note = memoryFreshnessNote(memStat.mtimeMs);
        if (note) {
          llmContent = note + llmContent;
        }
      } catch {
      }
    }
    const lines = typeof result.llmContent === "string" ? result.llmContent.split("\n").length : void 0;
    const mimetype = getSpecificMimeType(this.params.file_path);
    const programming_language = getProgrammingLanguage({
      file_path: this.params.file_path
    });
    logFileOperation(
      this.config,
      new FileOperationEvent(
        ReadFileTool.Name,
        "read" /* READ */,
        lines,
        mimetype,
        path10.extname(this.params.file_path),
        programming_language
      )
    );
    return {
      llmContent,
      returnDisplay: result.returnDisplay || ""
    };
  }
  /**
   * Build the placeholder ToolResult returned when the cache indicates
   * the file has not changed since the model last fully read it. The
   * placeholder is intentionally explicit about its assumptions so the
   * model can decide whether to trust it:
   *
   *  1. The full content was emitted *earlier in this conversation*.
   *     If the conversation has been compacted, summarised, or the
   *     model is a subagent receiving a transformed transcript, the
   *     prior content may no longer be retrievable — the model should
   *     re-read with explicit offset/limit in that case.
   *  2. External mutations the cache cannot observe (shell writes via
   *     run_shell_command, MCP tool writes, other processes touching
   *     the file) will not appear here as `stale`. If the model
   *     suspects drift, it should re-read with explicit offset/limit.
   *
   * No `logFileOperation` is emitted on this path: the file_unchanged
   * fast-path bypasses the read pipeline entirely, and the existing
   * `FileOperationEvent` schema has no representation for "served from
   * cache". A dedicated cache-hit metric can be added when telemetry
   * needs visibility into the fast-path's effectiveness.
   */
  unchangedResult(absPath) {
    const relativePath = shortenPath(
      makeRelative(absPath, this.config.getTargetDir())
    );
    const llmContent = `[File ${relativePath} unchanged since last read in this session \u2014 the full content was provided earlier in this conversation. If you cannot retrieve that prior content (e.g. after context compaction) or you suspect the file was modified outside the read/edit tools (shell command, MCP tool, another process), re-read with explicit offset/limit to fetch current content.]`;
    return {
      llmContent,
      returnDisplay: `Unchanged: ${relativePath}`
    };
  }
};
var ReadFileTool = class _ReadFileTool extends BaseDeclarativeTool {
  constructor(config) {
    super(
      _ReadFileTool.Name,
      ToolDisplayNames.READ_FILE,
      `Reads and returns the content of a specified file. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first. If the file is large, the content will be truncated. The tool's response will clearly indicate if truncation has occurred and will provide details on how to read more of the file using the 'offset' and 'limit' parameters. Handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), PDF files, and Jupyter notebooks (.ipynb). For text files, it can read specific line ranges. For PDF files, use the 'pages' parameter to extract specific page ranges as text (e.g. '1-5'). Max 20 pages per request. This tool can read Jupyter notebooks (.ipynb) and returns structured cell content with outputs.`,
      "read" /* Read */,
      {
        properties: {
          file_path: {
            description: "The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported. You must provide an absolute path.",
            type: "string"
          },
          offset: {
            description: "Optional: For text files, the 0-based line number to start reading from. Requires 'limit' to be set. Use for paginating through large files.",
            type: "number"
          },
          limit: {
            description: "Optional: For text files, maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible, up to a default limit).",
            type: "number"
          },
          pages: {
            description: "Optional: For PDF files, the page range to extract as text (e.g., '1-5', '3', '10-20'). Pages are 1-indexed. Max 20 pages per request. Open-ended ranges like '3-' are not supported. When provided, PDF content is extracted as text regardless of model capabilities.",
            type: "string"
          }
        },
        required: ["file_path"],
        type: "object"
      }
    );
    this.config = config;
  }
  static {
    __name(this, "ReadFileTool");
  }
  static Name = ToolNames.READ_FILE;
  // Self-managed: ReadFile controls its own size via line-based paging
  // (offset/limit, default 2000 lines), so it is exempt from the scheduler's
  // char-based truncation. Oversized reads are bounded by the per-message
  // batch budget instead.
  get maxOutputChars() {
    return Number.POSITIVE_INFINITY;
  }
  validateToolParamValues(params) {
    const filePath = unescapePath(params.file_path.trim());
    params.file_path = filePath;
    if (!filePath) {
      return "The 'file_path' parameter must be non-empty.";
    }
    if (!path10.isAbsolute(filePath)) {
      return `File path must be absolute, but was relative: ${filePath}. You must provide an absolute path.`;
    }
    if (params.offset !== void 0 && params.offset < 0) {
      return "Offset must be a non-negative number";
    }
    if (params.limit !== void 0 && params.limit <= 0) {
      return "Limit must be a positive number";
    }
    if (params.pages !== void 0) {
      const pages = params.pages.trim();
      params.pages = pages.length > 0 ? pages : void 0;
    }
    const ext = path10.extname(filePath).toLowerCase();
    if ((params.offset !== void 0 || params.limit !== void 0) && ext === ".ipynb") {
      return "offset and limit are not supported for Jupyter notebook (.ipynb) files. Notebooks are always read in full with structured cell output.";
    }
    if (params.pages !== void 0 && ext === ".ipynb") {
      return "pages is not supported for Jupyter notebook (.ipynb) files. Notebooks are always read in full with structured cell output.";
    }
    if (params.pages) {
      const parsed = parsePDFPageRange(params.pages);
      if (!parsed) {
        return `Invalid pages parameter: '${params.pages}'. Use formats like '5' or '1-10'.`;
      }
      if (parsed.lastPage === Infinity) {
        return `Open-ended page ranges (e.g. '3-') are not supported; specify an explicit end page within the 20-page limit (e.g. '3-22').`;
      }
      const maxPages = 20;
      if (parsed.lastPage - parsed.firstPage + 1 > maxPages) {
        return `Pages range exceeds maximum of ${maxPages} pages per request.`;
      }
    }
    const fileService = this.config.getFileService();
    if (fileService.shouldQwenIgnoreFile(params.file_path)) {
      return `File path '${filePath}' is ignored by ${fileService.getQwenIgnoreFileDisplayForPath(params.file_path)} pattern(s).`;
    }
    return null;
  }
  createInvocation(params) {
    return new ReadFileToolInvocation(this.config, params);
  }
};

export {
  EVENT_TOOL_CALL,
  EVENT_API_ERROR,
  EVENT_API_RESPONSE,
  DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH,
  SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT,
  isValidSensitiveSpanAttributeMaxLength,
  MAIN_SOURCE,
  subagentNameContext,
  UiTelemetryService,
  uiTelemetryService,
  safeJsonStringify,
  iconvEncode,
  iconvEncodingExists,
  isUtf8CompatibleEncoding,
  DEFAULT_CONTEXT_FILENAME,
  AGENT_CONTEXT_FILENAME,
  LOCAL_CONTEXT_FILENAME,
  MEMORY_SECTION_HEADER,
  setGeminiMdFilename,
  getCurrentGeminiMdFilename,
  getAllGeminiMdFilenames,
  COMMON_IGNORE_PATTERNS,
  BINARY_FILE_PATTERNS,
  MEDIA_FILE_PATTERNS,
  COMMON_DIRECTORY_EXCLUDES,
  PYTHON_EXCLUDES,
  SYSTEM_FILE_EXCLUDES,
  DEFAULT_FILE_EXCLUDES,
  FileExclusions,
  extractExtensionsFromPatterns,
  BINARY_EXTENSIONS,
  resetEncodingCache,
  getCachedEncodingForBuffer,
  getSystemEncoding,
  windowsCodePageToEncoding,
  detectEncodingFromBuffer,
  normalizeSource,
  parseNotebook,
  inferNotebookJsonFormat,
  serializeNotebook,
  getCellDisplayId,
  hasStableCellIds,
  isAmbiguousCellId,
  findCellIndex,
  getNotebookLanguage,
  makeCellId,
  inferInsertedCellSourceArrayStyle,
  toNotebookSource,
  normalizeEditedCell,
  DEFAULT_ENCODING,
  detectBOM,
  decodeBufferWithEncodingInfo,
  readFileWithEncodingInfo,
  readFileWithEncoding,
  countFileLines,
  readFileWithLineAndLimit,
  detectFileEncoding,
  getSpecificMimeType,
  isWithinRoot,
  isBinaryFile,
  detectFileType,
  processSingleFileContent,
  fileExists,
  FileOperation,
  PerformanceMetricType,
  MemoryMetricType,
  ToolExecutionPhase,
  ApiRequestPhase,
  recordToolCallMetrics,
  recordTokenUsageMetrics,
  recordApiResponseMetrics,
  recordApiErrorMetrics,
  recordFileOperationMetric,
  recordInvalidChunk,
  recordContentRetry,
  recordContentRetryFailure,
  recordApiRetry,
  recordStartupPerformance,
  recordMemoryUsage,
  recordCpuUsage,
  recordToolQueueDepth,
  recordToolExecutionBreakdown,
  recordTokenEfficiency,
  recordApiRequestBreakdown,
  recordPerformanceScore,
  recordPerformanceRegression,
  recordBaselineComparison,
  isPerformanceMonitoringActive,
  recordArenaSessionStartedMetrics,
  recordArenaAgentCompletedMetrics,
  recordArenaSessionEndedMetrics,
  recordMemoryExtractMetrics,
  recordMemoryDreamMetrics,
  recordMemoryRecallMetrics,
  getLanguageFromFilePath,
  SemanticAttributes,
  sanitizeHookName,
  QwenLogger,
  areSensitiveSpanAttributesEnabled,
  truncateContent,
  addUserPromptAttributes,
  addSystemPromptAttributes,
  addToolSchemaAttributes,
  addModelOutputAttributes,
  addToolInputAttributes,
  addToolResultAttributes,
  clearDetailedSpanState,
  truncateSpanError,
  startInteractionSpan,
  endInteractionSpan,
  withInteractionSpan,
  startLLMRequestSpan,
  endLLMRequestSpan,
  startToolSpan,
  runInToolSpanContext,
  endToolSpan,
  startToolExecutionSpan,
  endToolExecutionSpan,
  startToolBlockedOnUserSpan,
  endToolBlockedOnUserSpan,
  startHookSpan,
  endHookSpan,
  startSubagentSpan,
  runInSubagentSpanContext,
  endSubagentSpan,
  getActiveInteractionSpan,
  safeSetStatus,
  isTelemetrySdkInitialized,
  initializeTelemetry,
  refreshSessionContext,
  shutdownTelemetry,
  forceFlushMetrics,
  _recoverObjectsFromLine,
  parseLineTolerant,
  readLines,
  read,
  _resetEnsuredDirsCacheForTest,
  writeLine,
  writeLineSync,
  write,
  countLines,
  exists,
  getTokenUsageFilePath,
  apiResponseEventToTokenUsageRecord,
  recordTokenUsageFromApiResponse,
  recordTokenUsageFromApiResponseBestEffort,
  queryTokenUsage,
  formatTokenUsageSummaryAsCsv,
  formatTokenUsageSummaryAsJson,
  exportTokenUsageSummary,
  runWithChatRecordingSuppressed,
  logStartSession,
  logUserPrompt,
  logUserRetry,
  logToolCall,
  logToolOutputTruncated,
  logFileOperation,
  logApiRequest,
  logFlashFallback,
  logRipgrepFallback,
  logApiError,
  logApiCancel,
  logApiResponse,
  logLoopDetected,
  logLoopDetectionDisabled,
  logNextSpeakerCheck,
  logSlashCommand,
  logIdeConnection,
  logConversationFinishedEvent,
  logChatCompression,
  logKittySequenceOverflow,
  logContentRetry,
  logContentRetryFailure,
  logApiRetry,
  logSubagentExecution,
  logModelSlashCommand,
  logHookCall,
  logExtensionInstallEvent,
  logExtensionUninstall,
  logExtensionUpdateEvent,
  logExtensionEnable,
  logExtensionDisable,
  logAuth,
  logSkillLaunch,
  recordSkillInvocation,
  logUserFeedback,
  logArenaSessionStarted,
  logArenaAgentCompleted,
  logArenaSessionEnded,
  logPromptSuggestion,
  logSpeculation,
  logWorkflowKeyword,
  logWorkflowRun,
  logMemoryExtract,
  logMemoryDream,
  logMemoryRecall,
  memoryAge,
  memoryFreshnessText,
  ReadFileTool,
  TOOL_OUTPUT_TRUNCATED_PREFIX,
  truncateToolOutput,
  truncateLlmContent,
  isAlreadyTruncated,
  persistAndTruncateToolResult,
  MCPServerStatus,
  addMCPStatusChangeListener,
  removeMCPStatusChangeListener,
  updateMCPServerStatus,
  removeMCPServerStatus,
  getMCPServerStatus,
  getAllMCPServerStatuses,
  DiscoveredMCPTool,
  generateValidName,
  StartSessionEvent,
  EndSessionEvent,
  UserPromptEvent,
  UserRetryEvent,
  ToolCallEvent,
  ApiRequestEvent,
  ApiErrorEvent,
  ApiCancelEvent,
  ApiResponseEvent,
  FlashFallbackEvent,
  RipgrepFallbackEvent,
  LoopType,
  LoopDetectedEvent,
  LoopDetectionDisabledEvent,
  NextSpeakerCheckEvent,
  makeSlashCommandEvent,
  SlashCommandStatus,
  makeChatCompressionEvent,
  IdeConnectionType,
  IdeConnectionEvent,
  ConversationFinishedEvent,
  KittySequenceOverflowEvent,
  FileOperationEvent,
  ContentRetryEvent,
  ApiRetryEvent,
  ContentRetryFailureEvent,
  ExtensionInstallEvent,
  ToolOutputTruncatedEvent,
  ExtensionUninstallEvent,
  ExtensionUpdateEvent,
  ExtensionEnableEvent,
  ModelSlashCommandEvent,
  SubagentExecutionEvent,
  AuthEvent,
  HookCallEvent,
  SkillLaunchEvent,
  UserFeedbackRating,
  UserFeedbackEvent,
  makeArenaSessionStartedEvent,
  makeArenaAgentCompletedEvent,
  makeArenaSessionEndedEvent,
  ExtensionDisableEvent,
  PromptSuggestionEvent,
  SpeculationEvent,
  WorkflowKeywordEvent,
  WorkflowRunEvent,
  MemoryExtractEvent,
  MemoryDreamEvent,
  MemoryRecallEvent,
  TaggedThinkingParser,
  OpenAIContentConverter,
  openaiRequestCaptureContext,
  resolveOpenAILogDir,
  OpenAILogger,
  openaiLogger,
  parseBooleanEnvFlag,
  parseTelemetryTargetValue,
  resolveTelemetrySettings,
  DAEMON_TRACEPARENT_META_KEY,
  DAEMON_TRACESTATE_META_KEY,
  hashDaemonWorkspace,
  withDaemonSpan,
  withDaemonRequestSpan,
  withDaemonBridgeSpan,
  recordDaemonHttpResponse,
  addDaemonRequestAttribute,
  recordDaemonError,
  emitDaemonLog,
  captureDaemonTelemetryContext,
  runWithDaemonTelemetryContext,
  injectDaemonTraceContext,
  extractDaemonTraceContext,
  createDaemonBridgeTelemetry,
  initializeDaemonMetrics,
  registerDaemonGaugeCallbacks,
  recordDaemonHttpRequest,
  recordDaemonSessionLifecycle,
  recordDaemonChannelLifecycle,
  recordDaemonPromptQueueWait,
  recordDaemonPromptDuration,
  recordDaemonBridgeError,
  recordDaemonCancel,
  recordDaemonPipeMessage,
  startEventLoopLagMonitor,
  registerDaemonEventLoopLagGauge,
  registerAcpEventLoopLagGauge,
  TelemetryTarget,
  DEFAULT_TELEMETRY_TARGET,
  DEFAULT_OTLP_ENDPOINT,
  retryContext,
  MODEL_GENERATION_CONFIG_FIELDS,
  PROVIDER_SOURCED_FIELDS,
  AUTH_ENV_MAPPINGS,
  DEFAULT_MODELS,
  QWEN_OAUTH_MODELS,
  QWEN_OAUTH_ALLOWED_MODELS,
  AuthType,
  resolveContentGeneratorConfigWithSources,
  validateModelConfig,
  createContentGeneratorConfig,
  createContentGenerator
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Internal Prompt ID utilities
 *
 * Centralises the set of prompt IDs used by background operations
 * (suggestion generation, forked queries) so that logging, recording,
 * and UI layers can consistently recognise and filter them.
 */
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
/*! Bundled license information:

@grpc/proto-loader/build/src/util.js:
@grpc/proto-loader/build/src/index.js:
  (**
   * @license
   * Copyright 2018 gRPC authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   *)
*/
